blob: 99c0a8d3215fe96cb24ca0ff213c47826b7eb626 [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')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -070039_DEFAULT_CUDA_VERSION = '8.0'
40_DEFAULT_CUDNN_VERSION = '6'
41_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
268def run_gen_git_source(environ_cp):
269 """Run the gen_git_source to create links.
270
271 The links are for bazel to track dependencies for git hash propagation.
272
273 Args:
274 environ_cp: copy of the os.environ.
275 """
Vijay Vasudevana1fba7f2017-07-28 10:58:56 -0700276 cmd = '"%s" tensorflow/tools/git/gen_git_source.py --configure %s' % (
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700277 environ_cp.get('PYTHON_BIN_PATH'), os.getcwd())
278 os.system(cmd)
279
280
281def cleanup_makefile():
282 """Delete any leftover BUILD files from the Makefile build.
283
284 These files could interfere with Bazel parsing.
285 """
286 makefile_download_dir = 'tensorflow/contrib/makefile/downloads'
287 if os.path.isdir(makefile_download_dir):
288 for root, _, filenames in os.walk(makefile_download_dir):
289 for f in filenames:
290 if f.endswith('BUILD'):
291 os.remove(os.path.join(root, f))
292
293
294def get_var(environ_cp,
295 var_name,
296 query_item,
297 enabled_by_default,
298 question=None,
299 yes_reply=None,
300 no_reply=None):
301 """Get boolean input from user.
302
303 If var_name is not set in env, ask user to enable query_item or not. If the
304 response is empty, use the default.
305
306 Args:
307 environ_cp: copy of the os.environ.
308 var_name: string for name of environment variable, e.g. "TF_NEED_HDFS".
309 query_item: string for feature related to the variable, e.g. "Hadoop File
310 System".
311 enabled_by_default: boolean for default behavior.
312 question: optional string for how to ask for user input.
313 yes_reply: optionanl string for reply when feature is enabled.
314 no_reply: optional string for reply when feature is disabled.
315
316 Returns:
317 boolean value of the variable.
318 """
319 if not question:
320 question = 'Do you wish to build TensorFlow with %s support?' % query_item
321 if not yes_reply:
322 yes_reply = '%s support will be enabled for TensorFlow.' % query_item
323 if not no_reply:
324 no_reply = 'No %s' % yes_reply
325
326 yes_reply += '\n'
327 no_reply += '\n'
328
329 if enabled_by_default:
330 question += ' [Y/n]: '
331 else:
332 question += ' [y/N]: '
333
334 var = environ_cp.get(var_name)
335 while var is None:
336 user_input_origin = get_input(question)
337 user_input = user_input_origin.strip().lower()
338 if user_input == 'y':
339 print(yes_reply)
340 var = True
341 elif user_input == 'n':
342 print(no_reply)
343 var = False
344 elif not user_input:
345 if enabled_by_default:
346 print(yes_reply)
347 var = True
348 else:
349 print(no_reply)
350 var = False
351 else:
352 print('Invalid selection: %s' % user_input_origin)
353 return var
354
355
356def set_build_var(environ_cp, var_name, query_item, option_name,
Michael Case98850a52017-09-14 13:35:57 -0700357 enabled_by_default, bazel_config_name=None):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700358 """Set if query_item will be enabled for the build.
359
360 Ask user if query_item will be enabled. Default is used if no input is given.
361 Set subprocess environment variable and write to .bazelrc if enabled.
362
363 Args:
364 environ_cp: copy of the os.environ.
365 var_name: string for name of environment variable, e.g. "TF_NEED_HDFS".
366 query_item: string for feature related to the variable, e.g. "Hadoop File
367 System".
368 option_name: string for option to define in .bazelrc.
369 enabled_by_default: boolean for default behavior.
Michael Case98850a52017-09-14 13:35:57 -0700370 bazel_config_name: Name for Bazel --config argument to enable build feature.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700371 """
372
373 var = str(int(get_var(environ_cp, var_name, query_item, enabled_by_default)))
374 environ_cp[var_name] = var
375 if var == '1':
376 write_to_bazelrc('build --define %s=true' % option_name)
Michael Case98850a52017-09-14 13:35:57 -0700377 elif bazel_config_name is not None:
378 # TODO(mikecase): Migrate all users of configure.py to use --config Bazel
379 # options and not to set build configs through environment variables.
380 write_to_bazelrc('build:%s --define %s=true'
381 % (bazel_config_name, option_name))
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700382
383
384def set_action_env_var(environ_cp,
385 var_name,
386 query_item,
387 enabled_by_default,
388 question=None,
389 yes_reply=None,
390 no_reply=None):
391 """Set boolean action_env variable.
392
393 Ask user if query_item will be enabled. Default is used if no input is given.
394 Set environment variable and write to .bazelrc.
395
396 Args:
397 environ_cp: copy of the os.environ.
398 var_name: string for name of environment variable, e.g. "TF_NEED_HDFS".
399 query_item: string for feature related to the variable, e.g. "Hadoop File
400 System".
401 enabled_by_default: boolean for default behavior.
402 question: optional string for how to ask for user input.
403 yes_reply: optionanl string for reply when feature is enabled.
404 no_reply: optional string for reply when feature is disabled.
405 """
406 var = int(
407 get_var(environ_cp, var_name, query_item, enabled_by_default, question,
408 yes_reply, no_reply))
409
410 write_action_env_to_bazelrc(var_name, var)
411 environ_cp[var_name] = str(var)
412
413
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700414def convert_version_to_int(version):
415 """Convert a version number to a integer that can be used to compare.
416
A. Unique TensorFlower28ce1d12017-08-15 12:08:29 -0700417 Version strings of the form X.YZ and X.Y.Z-xxxxx are supported. The
418 'xxxxx' part, for instance 'homebrew' on OS/X, is ignored.
419
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700420 Args:
A. Unique TensorFlower28ce1d12017-08-15 12:08:29 -0700421 version: a version to be converted
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700422
423 Returns:
424 An integer if converted successfully, otherwise return None.
425 """
A. Unique TensorFlower28ce1d12017-08-15 12:08:29 -0700426 version = version.split('-')[0]
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700427 version_segments = version.split('.')
428 for seg in version_segments:
429 if not seg.isdigit():
430 return None
431
432 version_str = ''.join(['%03d' % int(seg) for seg in version_segments])
433 return int(version_str)
434
435
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700436def check_bazel_version(min_version):
437 """Check installed bezel version is at least min_version.
438
439 Args:
440 min_version: string for minimum bazel version.
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700441
442 Returns:
443 The bazel version detected.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700444 """
Jonathan Hseu008910f2017-08-25 14:01:05 -0700445 if which('bazel') is None:
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700446 print('Cannot find bazel. Please install bazel.')
447 sys.exit(0)
Jonathan Hseu008910f2017-08-25 14:01:05 -0700448 curr_version = run_shell(['bazel', '--batch', 'version'])
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700449
450 for line in curr_version.split('\n'):
451 if 'Build label: ' in line:
452 curr_version = line.split('Build label: ')[1]
453 break
454
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700455 min_version_int = convert_version_to_int(min_version)
456 curr_version_int = convert_version_to_int(curr_version)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700457
458 # Check if current bazel version can be detected properly.
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700459 if not curr_version_int:
460 print('WARNING: current bazel installation is not a release version.')
461 print('Make sure you are running at least bazel %s' % min_version)
462 return curr_version
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700463
Michael Cased94271a2017-08-22 17:26:52 -0700464 print('You have bazel %s installed.' % curr_version)
A. Unique TensorFlower28ce1d12017-08-15 12:08:29 -0700465
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700466 if curr_version_int < min_version_int:
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700467 print('Please upgrade your bazel installation to version %s or higher to '
468 'build TensorFlow!' % min_version)
469 sys.exit(0)
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700470 return curr_version
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700471
472
473def set_cc_opt_flags(environ_cp):
474 """Set up architecture-dependent optimization flags.
475
476 Also append CC optimization flags to bazel.rc..
477
478 Args:
479 environ_cp: copy of the os.environ.
480 """
481 if is_ppc64le():
482 # gcc on ppc64le does not support -march, use mcpu instead
483 default_cc_opt_flags = '-mcpu=native'
484 else:
485 default_cc_opt_flags = '-march=native'
486 question = ('Please specify optimization flags to use during compilation when'
487 ' bazel option "--config=opt" is specified [Default is %s]: '
488 ) % default_cc_opt_flags
489 cc_opt_flags = get_from_env_or_user_or_default(environ_cp, 'CC_OPT_FLAGS',
490 question, default_cc_opt_flags)
491 for opt in cc_opt_flags.split():
Michael Case00177422017-11-10 13:14:03 -0800492 write_to_bazelrc('build:opt --copt=%s' % opt)
493 # It should be safe on the same build host.
494 write_to_bazelrc('build:opt --host_copt=-march=native')
Michael Casebb3355d2017-11-09 08:46:31 -0800495 write_to_bazelrc('build:opt --define with_default_optimizations=true')
Michael Case00177422017-11-10 13:14:03 -0800496 # TODO(mikecase): Remove these default defines once we are able to get
497 # TF Lite targets building without them.
Andrew Selle0b154392017-11-10 10:35:35 -0800498 write_to_bazelrc('build --copt=-DGEMMLOWP_ALLOW_SLOW_SCALAR_FALLBACK')
499 write_to_bazelrc('build --host_copt=-DGEMMLOWP_ALLOW_SLOW_SCALAR_FALLBACK')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700500
501
502def set_tf_cuda_clang(environ_cp):
503 """set TF_CUDA_CLANG action_env.
504
505 Args:
506 environ_cp: copy of the os.environ.
507 """
508 question = 'Do you want to use clang as CUDA compiler?'
509 yes_reply = 'Clang will be used as CUDA compiler.'
510 no_reply = 'nvcc will be used as CUDA compiler.'
511 set_action_env_var(
512 environ_cp,
513 'TF_CUDA_CLANG',
514 None,
515 False,
516 question=question,
517 yes_reply=yes_reply,
518 no_reply=no_reply)
519
520
521def get_from_env_or_user_or_default(environ_cp, var_name, ask_for_var,
522 var_default):
523 """Get var_name either from env, or user or default.
524
525 If var_name has been set as environment variable, use the preset value, else
526 ask for user input. If no input is provided, the default is used.
527
528 Args:
529 environ_cp: copy of the os.environ.
530 var_name: string for name of environment variable, e.g. "TF_NEED_HDFS".
531 ask_for_var: string for how to ask for user input.
532 var_default: default value string.
533
534 Returns:
535 string value for var_name
536 """
537 var = environ_cp.get(var_name)
538 if not var:
539 var = get_input(ask_for_var)
Michael Cased94271a2017-08-22 17:26:52 -0700540 print('\n')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700541 if not var:
542 var = var_default
543 return var
544
545
546def set_clang_cuda_compiler_path(environ_cp):
547 """Set CLANG_CUDA_COMPILER_PATH."""
Jonathan Hseu008910f2017-08-25 14:01:05 -0700548 default_clang_path = which('clang') or ''
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700549 ask_clang_path = ('Please specify which clang should be used as device and '
550 'host compiler. [Default is %s]: ') % default_clang_path
551
552 while True:
553 clang_cuda_compiler_path = get_from_env_or_user_or_default(
554 environ_cp, 'CLANG_CUDA_COMPILER_PATH', ask_clang_path,
555 default_clang_path)
556 if os.path.exists(clang_cuda_compiler_path):
557 break
558
559 # Reset and retry
560 print('Invalid clang path: %s cannot be found.' % clang_cuda_compiler_path)
561 environ_cp['CLANG_CUDA_COMPILER_PATH'] = ''
562
563 # Set CLANG_CUDA_COMPILER_PATH
564 environ_cp['CLANG_CUDA_COMPILER_PATH'] = clang_cuda_compiler_path
565 write_action_env_to_bazelrc('CLANG_CUDA_COMPILER_PATH',
566 clang_cuda_compiler_path)
567
568
Austin Anderson6afface2017-12-05 11:59:17 -0800569def prompt_loop_or_load_from_env(
570 environ_cp,
571 var_name,
572 var_default,
573 ask_for_var,
574 check_success,
575 error_msg,
576 suppress_default_error=False,
577 n_ask_attempts=_DEFAULT_PROMPT_ASK_ATTEMPTS
578):
579 """Loop over user prompts for an ENV param until receiving a valid response.
580
581 For the env param var_name, read from the environment or verify user input
582 until receiving valid input. When done, set var_name in the environ_cp to its
583 new value.
584
585 Args:
586 environ_cp: (Dict) copy of the os.environ.
587 var_name: (String) string for name of environment variable, e.g. "TF_MYVAR".
588 var_default: (String) default value string.
589 ask_for_var: (String) string for how to ask for user input.
590 check_success: (Function) function that takes one argument and returns a
591 boolean. Should return True if the value provided is considered valid. May
592 contain a complex error message if error_msg does not provide enough
593 information. In that case, set suppress_default_error to True.
594 error_msg: (String) String with one and only one '%s'. Formatted with each
595 invalid response upon check_success(input) failure.
596 suppress_default_error: (Bool) Suppress the above error message in favor of
597 one from the check_success function.
598 n_ask_attempts: (Integer) Number of times to query for valid input before
599 raising an error and quitting.
600
601 Returns:
602 [String] The value of var_name after querying for input.
603
604 Raises:
605 UserInputError: if a query has been attempted n_ask_attempts times without
606 success, assume that the user has made a scripting error, and will continue
607 to provide invalid input. Raise the error to avoid infinitely looping.
608 """
609 default = environ_cp.get(var_name) or var_default
610 full_query = '%s [Default is %s]: ' % (
611 ask_for_var,
612 default,
613 )
614
615 for _ in range(n_ask_attempts):
616 val = get_from_env_or_user_or_default(environ_cp,
617 var_name,
618 full_query,
619 default)
620 if check_success(val):
621 break
622 if not suppress_default_error:
623 print(error_msg % val)
624 environ_cp[var_name] = ''
625 else:
626 raise UserInputError('Invalid %s setting was provided %d times in a row. '
627 'Assuming to be a scripting mistake.' %
628 (var_name, n_ask_attempts))
629
630 environ_cp[var_name] = val
631 return val
632
633
634def create_android_ndk_rule(environ_cp):
635 """Set ANDROID_NDK_HOME and write Android NDK WORKSPACE rule."""
636 if is_windows() or is_cygwin():
637 default_ndk_path = cygpath('%s/Android/Sdk/ndk-bundle' %
638 environ_cp['APPDATA'])
639 elif is_macos():
640 default_ndk_path = '%s/library/Android/Sdk/ndk-bundle' % environ_cp['HOME']
641 else:
642 default_ndk_path = '%s/Android/Sdk/ndk-bundle' % environ_cp['HOME']
643
644 def valid_ndk_path(path):
645 return (os.path.exists(path) and
646 os.path.exists(os.path.join(path, 'source.properties')))
647
648 android_ndk_home_path = prompt_loop_or_load_from_env(
649 environ_cp,
650 var_name='ANDROID_NDK_HOME',
651 var_default=default_ndk_path,
652 ask_for_var='Please specify the home path of the Android NDK to use.',
653 check_success=valid_ndk_path,
654 error_msg=('The path %s or its child file "source.properties" '
655 'does not exist.')
656 )
657
658 write_android_ndk_workspace_rule(android_ndk_home_path)
659
660
661def create_android_sdk_rule(environ_cp):
662 """Set Android variables and write Android SDK WORKSPACE rule."""
663 if is_windows() or is_cygwin():
664 default_sdk_path = cygpath('%s/Android/Sdk' % environ_cp['APPDATA'])
665 elif is_macos():
666 default_sdk_path = '%s/library/Android/Sdk/ndk-bundle' % environ_cp['HOME']
667 else:
668 default_sdk_path = '%s/Android/Sdk' % environ_cp['HOME']
669
670 def valid_sdk_path(path):
671 return (os.path.exists(path) and
672 os.path.exists(os.path.join(path, 'platforms')) and
673 os.path.exists(os.path.join(path, 'build-tools')))
674
675 android_sdk_home_path = prompt_loop_or_load_from_env(
676 environ_cp,
677 var_name='ANDROID_SDK_HOME',
678 var_default=default_sdk_path,
679 ask_for_var='Please specify the home path of the Android SDK to use.',
680 check_success=valid_sdk_path,
681 error_msg=('Either %s does not exist, or it does not contain the '
682 'subdirectories "platforms" and "build-tools".'))
683
684 platforms = os.path.join(android_sdk_home_path, 'platforms')
685 api_levels = sorted(os.listdir(platforms))
686 api_levels = [x.replace('android-', '') for x in api_levels]
687
688 def valid_api_level(api_level):
689 return os.path.exists(os.path.join(android_sdk_home_path,
690 'platforms',
691 'android-' + api_level))
692
693 android_api_level = prompt_loop_or_load_from_env(
694 environ_cp,
695 var_name='ANDROID_API_LEVEL',
696 var_default=api_levels[-1],
697 ask_for_var=('Please specify the Android SDK API level to use. '
698 '[Available levels: %s]') % api_levels,
699 check_success=valid_api_level,
700 error_msg='Android-%s is not present in the SDK path.')
701
702 build_tools = os.path.join(android_sdk_home_path, 'build-tools')
703 versions = sorted(os.listdir(build_tools))
704
705 def valid_build_tools(version):
706 return os.path.exists(os.path.join(android_sdk_home_path,
707 'build-tools',
708 version))
709
710 android_build_tools_version = prompt_loop_or_load_from_env(
711 environ_cp,
712 var_name='ANDROID_BUILD_TOOLS_VERSION',
713 var_default=versions[-1],
714 ask_for_var=('Please specify an Android build tools version to use. '
715 '[Available versions: %s]') % versions,
716 check_success=valid_build_tools,
717 error_msg=('The selected SDK does not have build-tools version %s '
718 'available.'))
719
720 write_android_sdk_workspace_rule(android_sdk_home_path,
721 android_build_tools_version,
722 android_api_level)
723
724
725def write_android_sdk_workspace_rule(android_sdk_home_path,
726 android_build_tools_version,
727 android_api_level):
728 print('Writing android_sdk_workspace rule.\n')
729 with open(_TF_WORKSPACE, 'a') as f:
730 f.write("""
731android_sdk_repository(
732 name="androidsdk",
733 api_level=%s,
734 path="%s",
735 build_tools_version="%s")\n
736""" % (android_api_level, android_sdk_home_path, android_build_tools_version))
737
738
739def write_android_ndk_workspace_rule(android_ndk_home_path):
740 print('Writing android_ndk_workspace rule.')
741 ndk_api_level = check_ndk_level(android_ndk_home_path)
742 if int(ndk_api_level) not in _SUPPORTED_ANDROID_NDK_VERSIONS:
743 print('WARNING: The API level of the NDK in %s is %s, which is not '
744 'supported by Bazel (officially supported versions: %s). Please use '
745 'another version. Compiling Android targets may result in confusing '
746 'errors.\n' % (android_ndk_home_path, ndk_api_level,
747 _SUPPORTED_ANDROID_NDK_VERSIONS))
748 with open(_TF_WORKSPACE, 'a') as f:
749 f.write("""
750android_ndk_repository(
751 name="androidndk",
752 path="%s",
753 api_level=%s)\n
754""" % (android_ndk_home_path, ndk_api_level))
755
756
757def check_ndk_level(android_ndk_home_path):
758 """Check the revision number of an Android NDK path."""
759 properties_path = '%s/source.properties' % android_ndk_home_path
760 if is_windows() or is_cygwin():
761 properties_path = cygpath(properties_path)
762 with open(properties_path, 'r') as f:
763 filedata = f.read()
764
765 revision = re.search(r'Pkg.Revision = (\d+)', filedata)
766 if revision:
767 return revision.group(1)
768 return None
769
770
771def workspace_has_any_android_rule():
772 """Check the WORKSPACE for existing android_*_repository rules."""
773 with open(_TF_WORKSPACE, 'r') as f:
774 workspace = f.read()
775 has_any_rule = re.search(r'^android_[ns]dk_repository',
776 workspace,
777 re.MULTILINE)
778 return has_any_rule
779
780
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700781def set_gcc_host_compiler_path(environ_cp):
782 """Set GCC_HOST_COMPILER_PATH."""
Jonathan Hseu008910f2017-08-25 14:01:05 -0700783 default_gcc_host_compiler_path = which('gcc') or ''
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700784 cuda_bin_symlink = '%s/bin/gcc' % environ_cp.get('CUDA_TOOLKIT_PATH')
785
786 if os.path.islink(cuda_bin_symlink):
787 # os.readlink is only available in linux
Jonathan Hseu008910f2017-08-25 14:01:05 -0700788 default_gcc_host_compiler_path = os.path.realpath(cuda_bin_symlink)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700789
Austin Anderson6afface2017-12-05 11:59:17 -0800790 gcc_host_compiler_path = prompt_loop_or_load_from_env(
791 environ_cp,
792 var_name='GCC_HOST_COMPILER_PATH',
793 var_default=default_gcc_host_compiler_path,
794 ask_for_var=
795 'Please specify which gcc should be used by nvcc as the host compiler.',
796 check_success=os.path.exists,
797 error_msg='Invalid gcc path. %s cannot be found.',
798 )
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700799
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700800 write_action_env_to_bazelrc('GCC_HOST_COMPILER_PATH', gcc_host_compiler_path)
801
802
803def set_tf_cuda_version(environ_cp):
804 """Set CUDA_TOOLKIT_PATH and TF_CUDA_VERSION."""
805 ask_cuda_version = (
806 'Please specify the CUDA SDK version you want to use, '
807 'e.g. 7.0. [Leave empty to default to CUDA %s]: ') % _DEFAULT_CUDA_VERSION
808
809 while True:
810 # Configure the Cuda SDK version to use.
811 tf_cuda_version = get_from_env_or_user_or_default(
812 environ_cp, 'TF_CUDA_VERSION', ask_cuda_version, _DEFAULT_CUDA_VERSION)
813
814 # Find out where the CUDA toolkit is installed
815 default_cuda_path = _DEFAULT_CUDA_PATH
Martin Wicked57572e2017-09-02 19:21:45 -0700816 if is_windows() or is_cygwin():
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700817 default_cuda_path = cygpath(
818 environ_cp.get('CUDA_PATH', _DEFAULT_CUDA_PATH_WIN))
819 elif is_linux():
820 # If the default doesn't exist, try an alternative default.
821 if (not os.path.exists(default_cuda_path)
822 ) and os.path.exists(_DEFAULT_CUDA_PATH_LINUX):
823 default_cuda_path = _DEFAULT_CUDA_PATH_LINUX
824 ask_cuda_path = ('Please specify the location where CUDA %s toolkit is'
825 ' installed. Refer to README.md for more details. '
826 '[Default is %s]: ') % (tf_cuda_version, default_cuda_path)
827 cuda_toolkit_path = get_from_env_or_user_or_default(
828 environ_cp, 'CUDA_TOOLKIT_PATH', ask_cuda_path, default_cuda_path)
829
830 if is_windows():
831 cuda_rt_lib_path = 'lib/x64/cudart.lib'
832 elif is_linux():
833 cuda_rt_lib_path = 'lib64/libcudart.so.%s' % tf_cuda_version
834 elif is_macos():
835 cuda_rt_lib_path = 'lib/libcudart.%s.dylib' % tf_cuda_version
836
837 cuda_toolkit_path_full = os.path.join(cuda_toolkit_path, cuda_rt_lib_path)
838 if os.path.exists(cuda_toolkit_path_full):
839 break
840
841 # Reset and retry
842 print('Invalid path to CUDA %s toolkit. %s cannot be found' %
843 (tf_cuda_version, cuda_toolkit_path_full))
844 environ_cp['TF_CUDA_VERSION'] = ''
845 environ_cp['CUDA_TOOLKIT_PATH'] = ''
846
847 # Set CUDA_TOOLKIT_PATH and TF_CUDA_VERSION
848 environ_cp['CUDA_TOOLKIT_PATH'] = cuda_toolkit_path
849 write_action_env_to_bazelrc('CUDA_TOOLKIT_PATH', cuda_toolkit_path)
850 environ_cp['TF_CUDA_VERSION'] = tf_cuda_version
851 write_action_env_to_bazelrc('TF_CUDA_VERSION', tf_cuda_version)
852
853
Yifei Fengb1d8c592017-11-22 13:42:21 -0800854def set_tf_cudnn_version(environ_cp):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700855 """Set CUDNN_INSTALL_PATH and TF_CUDNN_VERSION."""
856 ask_cudnn_version = (
Jonathan Hseu008910f2017-08-25 14:01:05 -0700857 'Please specify the cuDNN version you want to use. '
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700858 '[Leave empty to default to cuDNN %s.0]: ') % _DEFAULT_CUDNN_VERSION
859
860 while True:
861 tf_cudnn_version = get_from_env_or_user_or_default(
862 environ_cp, 'TF_CUDNN_VERSION', ask_cudnn_version,
863 _DEFAULT_CUDNN_VERSION)
864
865 default_cudnn_path = environ_cp.get('CUDA_TOOLKIT_PATH')
866 ask_cudnn_path = (r'Please specify the location where cuDNN %s library is '
867 'installed. Refer to README.md for more details. [Default'
868 ' is %s]:') % (tf_cudnn_version, default_cudnn_path)
869 cudnn_install_path = get_from_env_or_user_or_default(
870 environ_cp, 'CUDNN_INSTALL_PATH', ask_cudnn_path, default_cudnn_path)
871
872 # Result returned from "read" will be used unexpanded. That make "~"
873 # unusable. Going through one more level of expansion to handle that.
874 cudnn_install_path = os.path.realpath(
875 os.path.expanduser(cudnn_install_path))
Martin Wicked57572e2017-09-02 19:21:45 -0700876 if is_windows() or is_cygwin():
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700877 cudnn_install_path = cygpath(cudnn_install_path)
878
879 if is_windows():
880 cuda_dnn_lib_path = 'lib/x64/cudnn.lib'
881 cuda_dnn_lib_alt_path = 'lib/x64/cudnn.lib'
882 elif is_linux():
883 cuda_dnn_lib_path = 'lib64/libcudnn.so.%s' % tf_cudnn_version
884 cuda_dnn_lib_alt_path = 'libcudnn.so.%s' % tf_cudnn_version
885 elif is_macos():
886 cuda_dnn_lib_path = 'lib/libcudnn.%s.dylib' % tf_cudnn_version
887 cuda_dnn_lib_alt_path = 'libcudnn.%s.dylib' % tf_cudnn_version
888
889 cuda_dnn_lib_path_full = os.path.join(cudnn_install_path, cuda_dnn_lib_path)
890 cuda_dnn_lib_alt_path_full = os.path.join(cudnn_install_path,
891 cuda_dnn_lib_alt_path)
892 if os.path.exists(cuda_dnn_lib_path_full) or os.path.exists(
893 cuda_dnn_lib_alt_path_full):
894 break
895
896 # Try another alternative for Linux
897 if is_linux():
Jonathan Hseu008910f2017-08-25 14:01:05 -0700898 ldconfig_bin = which('ldconfig') or '/sbin/ldconfig'
899 cudnn_path_from_ldconfig = run_shell([ldconfig_bin, '-p'])
900 cudnn_path_from_ldconfig = re.search('.*libcudnn.so .* => (.*)',
A. Unique TensorFlowere7223582017-09-06 17:57:04 -0700901 cudnn_path_from_ldconfig)
902 if cudnn_path_from_ldconfig:
903 cudnn_path_from_ldconfig = cudnn_path_from_ldconfig.group(1)
904 if os.path.exists('%s.%s' % (cudnn_path_from_ldconfig,
905 tf_cudnn_version)):
906 cudnn_install_path = os.path.dirname(cudnn_path_from_ldconfig)
907 break
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700908
909 # Reset and Retry
910 print(
911 'Invalid path to cuDNN %s toolkit. None of the following files can be '
912 'found:' % tf_cudnn_version)
913 print(cuda_dnn_lib_path_full)
914 print(cuda_dnn_lib_alt_path_full)
915 if is_linux():
916 print('%s.%s' % (cudnn_path_from_ldconfig, tf_cudnn_version))
917
918 environ_cp['TF_CUDNN_VERSION'] = ''
919
920 # Set CUDNN_INSTALL_PATH and TF_CUDNN_VERSION
921 environ_cp['CUDNN_INSTALL_PATH'] = cudnn_install_path
922 write_action_env_to_bazelrc('CUDNN_INSTALL_PATH', cudnn_install_path)
923 environ_cp['TF_CUDNN_VERSION'] = tf_cudnn_version
924 write_action_env_to_bazelrc('TF_CUDNN_VERSION', tf_cudnn_version)
925
926
927def get_native_cuda_compute_capabilities(environ_cp):
928 """Get native cuda compute capabilities.
929
930 Args:
931 environ_cp: copy of the os.environ.
932 Returns:
933 string of native cuda compute capabilities, separated by comma.
934 """
935 device_query_bin = os.path.join(
936 environ_cp.get('CUDA_TOOLKIT_PATH'), 'extras/demo_suite/deviceQuery')
Jonathan Hseu008910f2017-08-25 14:01:05 -0700937 if os.path.isfile(device_query_bin) and os.access(device_query_bin, os.X_OK):
938 try:
939 output = run_shell(device_query_bin).split('\n')
940 pattern = re.compile('[0-9]*\\.[0-9]*')
941 output = [pattern.search(x) for x in output if 'Capability' in x]
942 output = ','.join(x.group() for x in output if x is not None)
943 except subprocess.CalledProcessError:
944 output = ''
945 else:
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700946 output = ''
947 return output
948
949
950def set_tf_cuda_compute_capabilities(environ_cp):
951 """Set TF_CUDA_COMPUTE_CAPABILITIES."""
952 while True:
953 native_cuda_compute_capabilities = get_native_cuda_compute_capabilities(
954 environ_cp)
955 if not native_cuda_compute_capabilities:
956 default_cuda_compute_capabilities = _DEFAULT_CUDA_COMPUTE_CAPABILITIES
957 else:
958 default_cuda_compute_capabilities = native_cuda_compute_capabilities
959
960 ask_cuda_compute_capabilities = (
961 'Please specify a list of comma-separated '
962 'Cuda compute capabilities you want to '
963 'build with.\nYou can find the compute '
964 'capability of your device at: '
965 'https://developer.nvidia.com/cuda-gpus.\nPlease'
966 ' note that each additional compute '
967 'capability significantly increases your '
968 'build time and binary size. [Default is: %s]' %
969 default_cuda_compute_capabilities)
970 tf_cuda_compute_capabilities = get_from_env_or_user_or_default(
971 environ_cp, 'TF_CUDA_COMPUTE_CAPABILITIES',
972 ask_cuda_compute_capabilities, default_cuda_compute_capabilities)
973 # Check whether all capabilities from the input is valid
974 all_valid = True
975 for compute_capability in tf_cuda_compute_capabilities.split(','):
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700976 m = re.match('[0-9]+.[0-9]+', compute_capability)
977 if not m:
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700978 print('Invalid compute capability: ' % compute_capability)
979 all_valid = False
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700980 else:
981 ver = int(m.group(0).split('.')[0])
982 if ver < 3:
983 print('Only compute capabilities 3.0 or higher are supported.')
984 all_valid = False
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700985
986 if all_valid:
987 break
988
989 # Reset and Retry
990 environ_cp['TF_CUDA_COMPUTE_CAPABILITIES'] = ''
991
992 # Set TF_CUDA_COMPUTE_CAPABILITIES
993 environ_cp['TF_CUDA_COMPUTE_CAPABILITIES'] = tf_cuda_compute_capabilities
994 write_action_env_to_bazelrc('TF_CUDA_COMPUTE_CAPABILITIES',
995 tf_cuda_compute_capabilities)
996
997
998def set_other_cuda_vars(environ_cp):
999 """Set other CUDA related variables."""
1000 if is_windows():
1001 # The following three variables are needed for MSVC toolchain configuration
1002 # in Bazel
1003 environ_cp['CUDA_PATH'] = environ_cp.get('CUDA_TOOLKIT_PATH')
1004 environ_cp['CUDA_COMPUTE_CAPABILITIES'] = environ_cp.get(
1005 'TF_CUDA_COMPUTE_CAPABILITIES')
1006 environ_cp['NO_WHOLE_ARCHIVE_OPTION'] = 1
1007 write_action_env_to_bazelrc('CUDA_PATH', environ_cp.get('CUDA_PATH'))
1008 write_action_env_to_bazelrc('CUDA_COMPUTE_CAPABILITIE',
1009 environ_cp.get('CUDA_COMPUTE_CAPABILITIE'))
1010 write_action_env_to_bazelrc('NO_WHOLE_ARCHIVE_OPTION',
1011 environ_cp.get('NO_WHOLE_ARCHIVE_OPTION'))
1012 write_to_bazelrc('build --config=win-cuda')
1013 write_to_bazelrc('test --config=win-cuda')
1014 else:
1015 # If CUDA is enabled, always use GPU during build and test.
1016 if environ_cp.get('TF_CUDA_CLANG') == '1':
1017 write_to_bazelrc('build --config=cuda_clang')
1018 write_to_bazelrc('test --config=cuda_clang')
1019 else:
1020 write_to_bazelrc('build --config=cuda')
1021 write_to_bazelrc('test --config=cuda')
1022
1023
1024def set_host_cxx_compiler(environ_cp):
1025 """Set HOST_CXX_COMPILER."""
Jonathan Hseu008910f2017-08-25 14:01:05 -07001026 default_cxx_host_compiler = which('g++') or ''
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001027
Austin Anderson6afface2017-12-05 11:59:17 -08001028 host_cxx_compiler = prompt_loop_or_load_from_env(
1029 environ_cp,
1030 var_name='HOST_CXX_COMPILER',
1031 var_default=default_cxx_host_compiler,
1032 ask_for_var=('Please specify which C++ compiler should be used as the '
1033 'host C++ compiler.'),
1034 check_success=os.path.exists,
1035 error_msg='Invalid C++ compiler path. %s cannot be found.',
1036 )
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001037
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001038 write_action_env_to_bazelrc('HOST_CXX_COMPILER', host_cxx_compiler)
1039
1040
1041def set_host_c_compiler(environ_cp):
1042 """Set HOST_C_COMPILER."""
Jonathan Hseu008910f2017-08-25 14:01:05 -07001043 default_c_host_compiler = which('gcc') or ''
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001044
Austin Anderson6afface2017-12-05 11:59:17 -08001045 host_c_compiler = prompt_loop_or_load_from_env(
1046 environ_cp,
1047 var_name='HOST_C_COMPILER',
1048 var_default=default_c_host_compiler,
1049 ask_for_var=('Please specify which C compiler should be used as the host'
1050 'C compiler.'),
1051 check_success=os.path.exists,
1052 error_msg='Invalid C compiler path. %s cannot be found.',
1053 )
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001054
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001055 write_action_env_to_bazelrc('HOST_C_COMPILER', host_c_compiler)
1056
1057
1058def set_computecpp_toolkit_path(environ_cp):
1059 """Set COMPUTECPP_TOOLKIT_PATH."""
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001060
Austin Anderson6afface2017-12-05 11:59:17 -08001061 def toolkit_exists(toolkit_path):
1062 """Check if a computecpp toolkit path is valid."""
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001063 if is_linux():
1064 sycl_rt_lib_path = 'lib/libComputeCpp.so'
1065 else:
1066 sycl_rt_lib_path = ''
1067
Austin Anderson6afface2017-12-05 11:59:17 -08001068 sycl_rt_lib_path_full = os.path.join(toolkit_path,
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001069 sycl_rt_lib_path)
Austin Anderson6afface2017-12-05 11:59:17 -08001070 exists = os.path.exists(sycl_rt_lib_path_full)
1071 if not exists:
1072 print('Invalid SYCL %s library path. %s cannot be found' %
1073 (_TF_OPENCL_VERSION, sycl_rt_lib_path_full))
1074 return exists
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001075
Austin Anderson6afface2017-12-05 11:59:17 -08001076 computecpp_toolkit_path = prompt_loop_or_load_from_env(
1077 environ_cp,
1078 var_name='COMPUTECPP_TOOLKIT_PATH',
1079 var_default=_DEFAULT_COMPUTECPP_TOOLKIT_PATH,
1080 ask_for_var=(
1081 'Please specify the location where ComputeCpp for SYCL %s is '
1082 'installed.' % _TF_OPENCL_VERSION),
1083 check_success=toolkit_exists,
1084 error_msg='Invalid SYCL compiler path. %s cannot be found.',
1085 suppress_default_error=True)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001086
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001087 write_action_env_to_bazelrc('COMPUTECPP_TOOLKIT_PATH',
1088 computecpp_toolkit_path)
1089
1090
Yifei Fengb1d8c592017-11-22 13:42:21 -08001091def set_trisycl_include_dir(environ_cp):
1092 """Set TRISYCL_INCLUDE_DIR."""
Yifei Fengb1d8c592017-11-22 13:42:21 -08001093
Austin Anderson6afface2017-12-05 11:59:17 -08001094 trisycl_include_dir = prompt_loop_or_load_from_env(
1095 environ_cp,
1096 var_name='TRISYCL_INCLUDE_DIR',
1097 var_default=_DEFAULT_TRISYCL_INCLUDE_DIR,
1098 ask_for_var=('Please specify the location of the triSYCL include '
1099 'directory. (Use --config=sycl_trisycl when building with '
1100 'Bazel)'),
1101 check_success=os.path.exists,
1102 error_msg='Invalid trySYCL include directory. %s cannot be found.',
1103 suppress_default_error=True)
Yifei Fengb1d8c592017-11-22 13:42:21 -08001104
Yifei Fengb1d8c592017-11-22 13:42:21 -08001105 write_action_env_to_bazelrc('TRISYCL_INCLUDE_DIR', trisycl_include_dir)
1106
1107
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001108def set_mpi_home(environ_cp):
1109 """Set MPI_HOME."""
Austin Anderson6afface2017-12-05 11:59:17 -08001110
Jonathan Hseu008910f2017-08-25 14:01:05 -07001111 default_mpi_home = which('mpirun') or which('mpiexec') or ''
1112 default_mpi_home = os.path.dirname(os.path.dirname(default_mpi_home))
1113
Austin Anderson6afface2017-12-05 11:59:17 -08001114 def valid_mpi_path(mpi_home):
1115 exists = (os.path.exists(os.path.join(mpi_home, 'include')) and
1116 os.path.exists(os.path.join(mpi_home, 'lib')))
1117 if not exists:
1118 print('Invalid path to the MPI Toolkit. %s or %s cannot be found' %
1119 (os.path.join(mpi_home, 'include'),
1120 os.path.exists(os.path.join(mpi_home, 'lib'))))
1121 return exists
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001122
Austin Anderson6afface2017-12-05 11:59:17 -08001123 _ = prompt_loop_or_load_from_env(
1124 environ_cp,
1125 var_name='MPI_HOME',
1126 var_default=default_mpi_home,
1127 ask_for_var='Please specify the MPI toolkit folder.',
1128 check_success=valid_mpi_path,
1129 error_msg='',
1130 suppress_default_error=True)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001131
1132
1133def set_other_mpi_vars(environ_cp):
1134 """Set other MPI related variables."""
1135 # Link the MPI header files
1136 mpi_home = environ_cp.get('MPI_HOME')
1137 symlink_force('%s/include/mpi.h' % mpi_home, 'third_party/mpi/mpi.h')
1138
1139 # Determine if we use OpenMPI or MVAPICH, these require different header files
1140 # to be included here to make bazel dependency checker happy
1141 if os.path.exists(os.path.join(mpi_home, 'include/mpi_portable_platform.h')):
1142 symlink_force(
1143 os.path.join(mpi_home, 'include/mpi_portable_platform.h'),
1144 'third_party/mpi/mpi_portable_platform.h')
1145 # TODO(gunan): avoid editing files in configure
1146 sed_in_place('third_party/mpi/mpi.bzl', 'MPI_LIB_IS_OPENMPI=False',
1147 'MPI_LIB_IS_OPENMPI=True')
1148 else:
1149 # MVAPICH / MPICH
1150 symlink_force(
1151 os.path.join(mpi_home, 'include/mpio.h'), 'third_party/mpi/mpio.h')
1152 symlink_force(
1153 os.path.join(mpi_home, 'include/mpicxx.h'), 'third_party/mpi/mpicxx.h')
1154 # TODO(gunan): avoid editing files in configure
1155 sed_in_place('third_party/mpi/mpi.bzl', 'MPI_LIB_IS_OPENMPI=True',
1156 'MPI_LIB_IS_OPENMPI=False')
1157
1158 if os.path.exists(os.path.join(mpi_home, 'lib/libmpi.so')):
1159 symlink_force(
1160 os.path.join(mpi_home, 'lib/libmpi.so'), 'third_party/mpi/libmpi.so')
1161 else:
1162 raise ValueError('Cannot find the MPI library file in %s/lib' % mpi_home)
1163
1164
1165def set_mkl():
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001166 write_to_bazelrc('build:mkl --define using_mkl=true')
1167 write_to_bazelrc('build:mkl -c opt')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001168 print(
1169 'Add "--config=mkl" to your bazel command to build with MKL '
1170 'support.\nPlease note that MKL on MacOS or windows is still not '
1171 'supported.\nIf you would like to use a local MKL instead of '
1172 'downloading, please set the environment variable \"TF_MKL_ROOT\" every '
Austin Anderson6afface2017-12-05 11:59:17 -08001173 'time before build.\n')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001174
1175
Allen Lavoie5c7f9e32017-09-21 11:29:45 -07001176def set_monolithic():
1177 # Add --config=monolithic to your bazel command to use a mostly-static
1178 # build and disable modular op registration support (this will revert to
1179 # loading TensorFlow with RTLD_GLOBAL in Python). By default (without
1180 # --config=monolithic), TensorFlow will build with a dependence on
1181 # //tensorflow:libtensorflow_framework.so.
1182 write_to_bazelrc('build:monolithic --define framework_shared_object=false')
1183 # For projects which use TensorFlow as part of a Bazel build process, putting
1184 # nothing in a bazelrc will default to a monolithic build. The following line
1185 # opts in to modular op registration support by default:
1186 write_to_bazelrc('build --define framework_shared_object=true')
1187
1188
Michael Casef1ecdd62017-10-24 18:07:59 -07001189def create_android_bazelrc_configs():
1190 # Flags for --config=android
1191 write_to_bazelrc('build:android --crosstool_top=//external:android/crosstool')
1192 write_to_bazelrc(
1193 'build:android --host_crosstool_top=@bazel_tools//tools/cpp:toolchain')
1194 # Flags for --config=android_arm
1195 write_to_bazelrc('build:android_arm --config=android')
1196 write_to_bazelrc('build:android_arm --cpu=armeabi-v7a')
1197 # Flags for --config=android_arm64
1198 write_to_bazelrc('build:android_arm64 --config=android')
1199 write_to_bazelrc('build:android_arm64 --cpu=arm64-v8a')
1200
1201
A. Unique TensorFlower061c3592017-11-13 14:21:04 -08001202def set_grpc_build_flags():
1203 write_to_bazelrc('build --define grpc_no_ares=true')
1204
1205
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001206def main():
1207 # Make a copy of os.environ to be clear when functions and getting and setting
1208 # environment variables.
1209 environ_cp = dict(os.environ)
1210
Gunhan Gulsoyed89a2b2017-09-19 18:36:26 -07001211 check_bazel_version('0.5.4')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001212
1213 reset_tf_configure_bazelrc()
1214 cleanup_makefile()
Gunhan Gulsoyed89a2b2017-09-19 18:36:26 -07001215 setup_python(environ_cp)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001216 run_gen_git_source(environ_cp)
1217
1218 if is_windows():
Benoit Steiner355e25e2017-10-24 19:47:46 -07001219 environ_cp['TF_NEED_S3'] = '0'
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001220 environ_cp['TF_NEED_GCP'] = '0'
1221 environ_cp['TF_NEED_HDFS'] = '0'
1222 environ_cp['TF_NEED_JEMALLOC'] = '0'
Yifei Fengb1d8c592017-11-22 13:42:21 -08001223 environ_cp['TF_NEED_OPENCL_SYCL'] = '0'
1224 environ_cp['TF_NEED_COMPUTECPP'] = '0'
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001225 environ_cp['TF_NEED_OPENCL'] = '0'
1226 environ_cp['TF_CUDA_CLANG'] = '0'
1227
1228 if is_macos():
1229 environ_cp['TF_NEED_JEMALLOC'] = '0'
1230
1231 set_build_var(environ_cp, 'TF_NEED_JEMALLOC', 'jemalloc as malloc',
1232 'with_jemalloc', True)
1233 set_build_var(environ_cp, 'TF_NEED_GCP', 'Google Cloud Platform',
Benoit Steiner355e25e2017-10-24 19:47:46 -07001234 'with_gcp_support', True, 'gcp')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001235 set_build_var(environ_cp, 'TF_NEED_HDFS', 'Hadoop File System',
Benoit Steiner355e25e2017-10-24 19:47:46 -07001236 'with_hdfs_support', True, 'hdfs')
Michael Case7e4e3362017-10-09 13:31:15 -07001237 set_build_var(environ_cp, 'TF_NEED_S3', 'Amazon S3 File System',
1238 'with_s3_support', True, 's3')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001239 set_build_var(environ_cp, 'TF_ENABLE_XLA', 'XLA JIT', 'with_xla_support',
Michael Case98850a52017-09-14 13:35:57 -07001240 False, 'xla')
A. Unique TensorFlower28ce1d12017-08-15 12:08:29 -07001241 set_build_var(environ_cp, 'TF_NEED_GDR', 'GDR', 'with_gdr_support',
Michael Case98850a52017-09-14 13:35:57 -07001242 False, 'gdr')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001243 set_build_var(environ_cp, 'TF_NEED_VERBS', 'VERBS', 'with_verbs_support',
Michael Case98850a52017-09-14 13:35:57 -07001244 False, 'verbs')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001245
Yifei Fengb1d8c592017-11-22 13:42:21 -08001246 set_action_env_var(environ_cp, 'TF_NEED_OPENCL_SYCL', 'OpenCL SYCL', False)
1247 if environ_cp.get('TF_NEED_OPENCL_SYCL') == '1':
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001248 set_host_cxx_compiler(environ_cp)
1249 set_host_c_compiler(environ_cp)
Yifei Fengb1d8c592017-11-22 13:42:21 -08001250 set_action_env_var(environ_cp, 'TF_NEED_COMPUTECPP', 'ComputeCPP', True)
1251 if environ_cp.get('TF_NEED_COMPUTECPP') == '1':
1252 set_computecpp_toolkit_path(environ_cp)
1253 else:
1254 set_trisycl_include_dir(environ_cp)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001255
1256 set_action_env_var(environ_cp, 'TF_NEED_CUDA', 'CUDA', False)
A. Unique TensorFlower24cbb2a2017-09-08 07:45:44 -07001257 if (environ_cp.get('TF_NEED_CUDA') == '1' and
1258 'TF_CUDA_CONFIG_REPO' not in environ_cp):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001259 set_tf_cuda_version(environ_cp)
Yifei Fengb1d8c592017-11-22 13:42:21 -08001260 set_tf_cudnn_version(environ_cp)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001261 set_tf_cuda_compute_capabilities(environ_cp)
1262
1263 set_tf_cuda_clang(environ_cp)
1264 if environ_cp.get('TF_CUDA_CLANG') == '1':
1265 # Set up which clang we should use as the cuda / host compiler.
1266 set_clang_cuda_compiler_path(environ_cp)
1267 else:
1268 # Set up which gcc nvcc should use as the host compiler
1269 # No need to set this on Windows
1270 if not is_windows():
1271 set_gcc_host_compiler_path(environ_cp)
1272 set_other_cuda_vars(environ_cp)
1273
1274 set_build_var(environ_cp, 'TF_NEED_MPI', 'MPI', 'with_mpi_support', False)
1275 if environ_cp.get('TF_NEED_MPI') == '1':
1276 set_mpi_home(environ_cp)
1277 set_other_mpi_vars(environ_cp)
1278
A. Unique TensorFlower061c3592017-11-13 14:21:04 -08001279 set_grpc_build_flags()
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001280 set_cc_opt_flags(environ_cp)
1281 set_mkl()
Allen Lavoie5c7f9e32017-09-21 11:29:45 -07001282 set_monolithic()
Michael Casef1ecdd62017-10-24 18:07:59 -07001283 create_android_bazelrc_configs()
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001284
Austin Anderson6afface2017-12-05 11:59:17 -08001285 if workspace_has_any_android_rule():
1286 print('The WORKSPACE file has at least one of ["android_sdk_repository", '
1287 '"android_ndk_repository"] already set. Will not ask to help '
1288 'configure the WORKSPACE. Please delete the existing rules to '
1289 'activate the helper.\n')
1290 else:
1291 if get_var(
1292 environ_cp, 'TF_SET_ANDROID_WORKSPACE', 'android workspace',
1293 False,
1294 ('Would you like to interactively configure ./WORKSPACE for '
1295 'Android builds?'),
1296 'Searching for NDK and SDK installations.',
1297 'Not configuring the WORKSPACE for Android builds.'):
1298 create_android_ndk_rule(environ_cp)
1299 create_android_sdk_rule(environ_cp)
1300
1301
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001302if __name__ == '__main__':
1303 main()