blob: 2908e38ff75e9c0ff9ecf10acc1f836f60389270 [file] [log] [blame]
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001# Copyright 2017 The TensorFlow Authors. All Rights Reserved.
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14# ==============================================================================
15"""configure script to get build parameters from user."""
16
17from __future__ import absolute_import
18from __future__ import division
19from __future__ import print_function
20
Shanqing Cai71445712018-03-12 19:33:52 -070021import argparse
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -070022import errno
23import os
24import platform
25import re
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -070026import subprocess
27import sys
28
Andrew Sellec9885ea2017-11-06 09:37:03 -080029# pylint: disable=g-import-not-at-top
Jonathan Hseu008910f2017-08-25 14:01:05 -070030try:
31 from shutil import which
32except ImportError:
33 from distutils.spawn import find_executable as which
Andrew Sellec9885ea2017-11-06 09:37:03 -080034# pylint: enable=g-import-not-at-top
Jonathan Hseu008910f2017-08-25 14:01:05 -070035
Gunhan Gulsoyc59db932018-12-28 16:32:01 -080036_DEFAULT_CUDA_VERSION = '10.0'
Dandelion Man?90e42f32017-12-15 18:15:07 -080037_DEFAULT_CUDNN_VERSION = '7'
Smit Hinsufe7d1d92018-07-14 13:16:58 -070038_DEFAULT_CUDA_COMPUTE_CAPABILITIES = '3.5,7.0'
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -070039_DEFAULT_CUDA_PATH = '/usr/local/cuda'
40_DEFAULT_CUDA_PATH_LINUX = '/opt/cuda'
41_DEFAULT_CUDA_PATH_WIN = ('C:/Program Files/NVIDIA GPU Computing '
42 'Toolkit/CUDA/v%s' % _DEFAULT_CUDA_VERSION)
43_TF_OPENCL_VERSION = '1.2'
44_DEFAULT_COMPUTECPP_TOOLKIT_PATH = '/usr/local/computecpp'
Yifei Fengb1d8c592017-11-22 13:42:21 -080045_DEFAULT_TRISYCL_INCLUDE_DIR = '/usr/local/triSYCL/include'
A. Unique TensorFlower82820ef2018-11-12 13:22:13 -080046_SUPPORTED_ANDROID_NDK_VERSIONS = [10, 11, 12, 13, 14, 15, 16, 17, 18]
Austin Anderson6afface2017-12-05 11:59:17 -080047
48_DEFAULT_PROMPT_ASK_ATTEMPTS = 10
49
Shanqing Cai71445712018-03-12 19:33:52 -070050_TF_BAZELRC_FILENAME = '.tf_configure.bazelrc'
A. Unique TensorFlower7c5eb352018-10-01 07:15:23 -070051_TF_WORKSPACE_ROOT = ''
52_TF_BAZELRC = ''
A. Unique TensorFlowered297342019-03-15 11:25:28 -070053_TF_CURRENT_BAZEL_VERSION = None
Shanqing Cai71445712018-03-12 19:33:52 -070054
Jason Furmanek7c234152018-09-26 04:44:12 +000055NCCL_LIB_PATHS = [
TensorFlower Gardenerea5c5292018-10-01 17:28:26 -070056 'lib64/', 'lib/powerpc64le-linux-gnu/', 'lib/x86_64-linux-gnu/', ''
Jason Furmanek7c234152018-09-26 04:44:12 +000057]
Austin Anderson6afface2017-12-05 11:59:17 -080058
A. Unique TensorFlower76e879d2019-03-22 00:25:36 -070059# List of files to configure when building Bazel on Apple platforms.
A. Unique TensorFlower93e70732019-02-14 16:45:32 -080060APPLE_BAZEL_FILES = [
61 'tensorflow/lite/experimental/objc/BUILD',
62 'tensorflow/lite/experimental/swift/BUILD'
63]
64
A. Unique TensorFlower76e879d2019-03-22 00:25:36 -070065# List of files to move when building for iOS.
66IOS_FILES = [
67 'tensorflow/lite/experimental/objc/TensorFlowLiteObjC.podspec',
68 'tensorflow/lite/experimental/swift/TensorFlowLiteSwift.podspec',
69]
70
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -070071if platform.machine() == 'ppc64le':
72 _DEFAULT_TENSORRT_PATH_LINUX = '/usr/lib/powerpc64le-linux-gnu/'
73else:
74 _DEFAULT_TENSORRT_PATH_LINUX = '/usr/lib/%s-linux-gnu' % platform.machine()
75
Austin Anderson6afface2017-12-05 11:59:17 -080076
77class UserInputError(Exception):
78 pass
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -070079
80
81def is_windows():
82 return platform.system() == 'Windows'
83
84
85def is_linux():
86 return platform.system() == 'Linux'
87
88
89def is_macos():
90 return platform.system() == 'Darwin'
91
92
93def is_ppc64le():
94 return platform.machine() == 'ppc64le'
95
96
Jonathan Hseu008910f2017-08-25 14:01:05 -070097def is_cygwin():
98 return platform.system().startswith('CYGWIN_NT')
99
100
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700101def get_input(question):
102 try:
103 try:
104 answer = raw_input(question)
105 except NameError:
106 answer = input(question) # pylint: disable=bad-builtin
107 except EOFError:
108 answer = ''
109 return answer
110
111
112def symlink_force(target, link_name):
113 """Force symlink, equivalent of 'ln -sf'.
114
115 Args:
116 target: items to link to.
117 link_name: name of the link.
118 """
119 try:
120 os.symlink(target, link_name)
121 except OSError as e:
122 if e.errno == errno.EEXIST:
123 os.remove(link_name)
124 os.symlink(target, link_name)
125 else:
126 raise e
127
128
129def sed_in_place(filename, old, new):
130 """Replace old string with new string in file.
131
132 Args:
133 filename: string for filename.
134 old: string to replace.
135 new: new string to replace to.
136 """
137 with open(filename, 'r') as f:
138 filedata = f.read()
139 newdata = filedata.replace(old, new)
140 with open(filename, 'w') as f:
141 f.write(newdata)
142
143
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700144def write_to_bazelrc(line):
145 with open(_TF_BAZELRC, 'a') as f:
146 f.write(line + '\n')
147
148
149def write_action_env_to_bazelrc(var_name, var):
150 write_to_bazelrc('build --action_env %s="%s"' % (var_name, str(var)))
151
152
Jonathan Hseu008910f2017-08-25 14:01:05 -0700153def run_shell(cmd, allow_non_zero=False):
154 if allow_non_zero:
155 try:
156 output = subprocess.check_output(cmd)
157 except subprocess.CalledProcessError as e:
158 output = e.output
159 else:
160 output = subprocess.check_output(cmd)
161 return output.decode('UTF-8').strip()
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700162
163
164def cygpath(path):
165 """Convert path from posix to windows."""
Martin Wicked57572e2017-09-02 19:21:45 -0700166 return os.path.abspath(path).replace('\\', '/')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700167
168
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700169def get_python_path(environ_cp, python_bin_path):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700170 """Get the python site package paths."""
171 python_paths = []
172 if environ_cp.get('PYTHONPATH'):
173 python_paths = environ_cp.get('PYTHONPATH').split(':')
174 try:
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700175 library_paths = run_shell([
176 python_bin_path, '-c',
177 'import site; print("\\n".join(site.getsitepackages()))'
178 ]).split('\n')
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700179 except subprocess.CalledProcessError:
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700180 library_paths = [
181 run_shell([
182 python_bin_path, '-c',
183 'from distutils.sysconfig import get_python_lib;'
184 'print(get_python_lib())'
185 ])
186 ]
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700187
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700188 all_paths = set(python_paths + library_paths)
189
190 paths = []
191 for path in all_paths:
192 if os.path.isdir(path):
193 paths.append(path)
194 return paths
195
196
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700197def get_python_major_version(python_bin_path):
198 """Get the python major version."""
Jonathan Hseu008910f2017-08-25 14:01:05 -0700199 return run_shell([python_bin_path, '-c', 'import sys; print(sys.version[0])'])
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700200
201
Gunhan Gulsoyed89a2b2017-09-19 18:36:26 -0700202def setup_python(environ_cp):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700203 """Setup python related env variables."""
204 # Get PYTHON_BIN_PATH, default is the current running python.
205 default_python_bin_path = sys.executable
206 ask_python_bin_path = ('Please specify the location of python. [Default is '
207 '%s]: ') % default_python_bin_path
208 while True:
A. Unique TensorFlower5001ac02019-04-03 11:59:08 -0700209 python_bin_path = get_from_env_or_user_or_default(environ_cp,
210 'PYTHON_BIN_PATH',
211 ask_python_bin_path,
212 default_python_bin_path)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700213 # Check if the path is valid
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700214 if os.path.isfile(python_bin_path) and os.access(python_bin_path, os.X_OK):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700215 break
216 elif not os.path.exists(python_bin_path):
217 print('Invalid python path: %s cannot be found.' % python_bin_path)
218 else:
219 print('%s is not executable. Is it the python binary?' % python_bin_path)
220 environ_cp['PYTHON_BIN_PATH'] = ''
221
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700222 # Convert python path to Windows style before checking lib and version
Martin Wicked57572e2017-09-02 19:21:45 -0700223 if is_windows() or is_cygwin():
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700224 python_bin_path = cygpath(python_bin_path)
225
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700226 # Get PYTHON_LIB_PATH
227 python_lib_path = environ_cp.get('PYTHON_LIB_PATH')
228 if not python_lib_path:
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700229 python_lib_paths = get_python_path(environ_cp, python_bin_path)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700230 if environ_cp.get('USE_DEFAULT_PYTHON_LIB_PATH') == '1':
Vijay Vasudevana1fba7f2017-07-28 10:58:56 -0700231 python_lib_path = python_lib_paths[0]
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700232 else:
Jonathan Hseu008910f2017-08-25 14:01:05 -0700233 print('Found possible Python library paths:\n %s' %
234 '\n '.join(python_lib_paths))
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700235 default_python_lib_path = python_lib_paths[0]
236 python_lib_path = get_input(
Jonathan Hseu008910f2017-08-25 14:01:05 -0700237 'Please input the desired Python library path to use. '
238 'Default is [%s]\n' % python_lib_paths[0])
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700239 if not python_lib_path:
240 python_lib_path = default_python_lib_path
Vijay Vasudevana1fba7f2017-07-28 10:58:56 -0700241 environ_cp['PYTHON_LIB_PATH'] = python_lib_path
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700242
TensorFlower Gardener61a87202018-10-01 12:25:39 -0700243 _ = get_python_major_version(python_bin_path)
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700244
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700245 # Convert python path to Windows style before writing into bazel.rc
Martin Wicked57572e2017-09-02 19:21:45 -0700246 if is_windows() or is_cygwin():
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700247 python_lib_path = cygpath(python_lib_path)
248
249 # Set-up env variables used by python_configure.bzl
250 write_action_env_to_bazelrc('PYTHON_BIN_PATH', python_bin_path)
251 write_action_env_to_bazelrc('PYTHON_LIB_PATH', python_lib_path)
Gunhan Gulsoyed89a2b2017-09-19 18:36:26 -0700252 write_to_bazelrc('build --python_path=\"%s"' % python_bin_path)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700253 environ_cp['PYTHON_BIN_PATH'] = python_bin_path
254
William D. Ironsdcc76a52018-11-20 10:35:18 -0600255 # If choosen python_lib_path is from a path specified in the PYTHONPATH
256 # variable, need to tell bazel to include PYTHONPATH
257 if environ_cp.get('PYTHONPATH'):
258 python_paths = environ_cp.get('PYTHONPATH').split(':')
259 if python_lib_path in python_paths:
TensorFlower Gardener968cd182018-11-28 11:33:16 -0800260 write_action_env_to_bazelrc('PYTHONPATH', environ_cp.get('PYTHONPATH'))
William D. Ironsdcc76a52018-11-20 10:35:18 -0600261
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700262 # Write tools/python_bin_path.sh
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700263 with open(
264 os.path.join(_TF_WORKSPACE_ROOT, 'tools', 'python_bin_path.sh'),
265 'w') as f:
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700266 f.write('export PYTHON_BIN_PATH="%s"' % python_bin_path)
267
268
A. Unique TensorFlower7c5eb352018-10-01 07:15:23 -0700269def reset_tf_configure_bazelrc():
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700270 """Reset file that contains customized config settings."""
271 open(_TF_BAZELRC, 'w').close()
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700272
TensorFlower Gardenerabb763b2019-02-06 16:23:03 -0800273
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700274def cleanup_makefile():
275 """Delete any leftover BUILD files from the Makefile build.
276
277 These files could interfere with Bazel parsing.
278 """
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700279 makefile_download_dir = os.path.join(_TF_WORKSPACE_ROOT, 'tensorflow',
280 'contrib', 'makefile', 'downloads')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700281 if os.path.isdir(makefile_download_dir):
282 for root, _, filenames in os.walk(makefile_download_dir):
283 for f in filenames:
284 if f.endswith('BUILD'):
285 os.remove(os.path.join(root, f))
286
287
288def get_var(environ_cp,
289 var_name,
290 query_item,
291 enabled_by_default,
292 question=None,
293 yes_reply=None,
294 no_reply=None):
295 """Get boolean input from user.
296
297 If var_name is not set in env, ask user to enable query_item or not. If the
298 response is empty, use the default.
299
300 Args:
301 environ_cp: copy of the os.environ.
302 var_name: string for name of environment variable, e.g. "TF_NEED_HDFS".
303 query_item: string for feature related to the variable, e.g. "Hadoop File
304 System".
305 enabled_by_default: boolean for default behavior.
306 question: optional string for how to ask for user input.
Michael Cased90054e2018-02-07 14:36:00 -0800307 yes_reply: optional string for reply when feature is enabled.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700308 no_reply: optional string for reply when feature is disabled.
309
310 Returns:
311 boolean value of the variable.
Frank Chenc4ef9272018-01-10 11:36:52 -0800312
313 Raises:
314 UserInputError: if an environment variable is set, but it cannot be
315 interpreted as a boolean indicator, assume that the user has made a
316 scripting error, and will continue to provide invalid input.
317 Raise the error to avoid infinitely looping.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700318 """
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)
Frank Chenc4ef9272018-01-10 11:36:52 -0800335 if var is not None:
336 var_content = var.strip().lower()
337 true_strings = ('1', 't', 'true', 'y', 'yes')
338 false_strings = ('0', 'f', 'false', 'n', 'no')
339 if var_content in true_strings:
340 var = True
341 elif var_content in false_strings:
342 var = False
343 else:
344 raise UserInputError(
345 'Environment variable %s must be set as a boolean indicator.\n'
346 'The following are accepted as TRUE : %s.\n'
347 'The following are accepted as FALSE: %s.\n'
A. Unique TensorFlowered297342019-03-15 11:25:28 -0700348 'Current value is %s.' %
349 (var_name, ', '.join(true_strings), ', '.join(false_strings), var))
Frank Chenc4ef9272018-01-10 11:36:52 -0800350
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700351 while var is None:
352 user_input_origin = get_input(question)
353 user_input = user_input_origin.strip().lower()
354 if user_input == 'y':
355 print(yes_reply)
356 var = True
357 elif user_input == 'n':
358 print(no_reply)
359 var = False
360 elif not user_input:
361 if enabled_by_default:
362 print(yes_reply)
363 var = True
364 else:
365 print(no_reply)
366 var = False
367 else:
368 print('Invalid selection: %s' % user_input_origin)
369 return var
370
371
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700372def set_build_var(environ_cp,
373 var_name,
374 query_item,
375 option_name,
376 enabled_by_default,
377 bazel_config_name=None):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700378 """Set if query_item will be enabled for the build.
379
380 Ask user if query_item will be enabled. Default is used if no input is given.
381 Set subprocess environment variable and write to .bazelrc if enabled.
382
383 Args:
384 environ_cp: copy of the os.environ.
385 var_name: string for name of environment variable, e.g. "TF_NEED_HDFS".
386 query_item: string for feature related to the variable, e.g. "Hadoop File
387 System".
388 option_name: string for option to define in .bazelrc.
389 enabled_by_default: boolean for default behavior.
Michael Case98850a52017-09-14 13:35:57 -0700390 bazel_config_name: Name for Bazel --config argument to enable build feature.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700391 """
392
393 var = str(int(get_var(environ_cp, var_name, query_item, enabled_by_default)))
394 environ_cp[var_name] = var
395 if var == '1':
A. Unique TensorFlower5001ac02019-04-03 11:59:08 -0700396 write_to_bazelrc('build:%s --define %s=true' %
397 (bazel_config_name, option_name))
Yifei Fengec451f52018-10-05 12:53:50 -0700398 write_to_bazelrc('build --config=%s' % bazel_config_name)
Michael Case98850a52017-09-14 13:35:57 -0700399 elif bazel_config_name is not None:
400 # TODO(mikecase): Migrate all users of configure.py to use --config Bazel
401 # options and not to set build configs through environment variables.
A. Unique TensorFlower5001ac02019-04-03 11:59:08 -0700402 write_to_bazelrc('build:%s --define %s=true' %
403 (bazel_config_name, option_name))
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700404
405
406def set_action_env_var(environ_cp,
407 var_name,
408 query_item,
409 enabled_by_default,
410 question=None,
411 yes_reply=None,
412 no_reply=None):
413 """Set boolean action_env variable.
414
415 Ask user if query_item will be enabled. Default is used if no input is given.
416 Set environment variable and write to .bazelrc.
417
418 Args:
419 environ_cp: copy of the os.environ.
420 var_name: string for name of environment variable, e.g. "TF_NEED_HDFS".
421 query_item: string for feature related to the variable, e.g. "Hadoop File
422 System".
423 enabled_by_default: boolean for default behavior.
424 question: optional string for how to ask for user input.
Michael Cased90054e2018-02-07 14:36:00 -0800425 yes_reply: optional string for reply when feature is enabled.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700426 no_reply: optional string for reply when feature is disabled.
427 """
428 var = int(
429 get_var(environ_cp, var_name, query_item, enabled_by_default, question,
430 yes_reply, no_reply))
431
432 write_action_env_to_bazelrc(var_name, var)
433 environ_cp[var_name] = str(var)
434
435
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700436def convert_version_to_int(version):
437 """Convert a version number to a integer that can be used to compare.
438
A. Unique TensorFlower28ce1d12017-08-15 12:08:29 -0700439 Version strings of the form X.YZ and X.Y.Z-xxxxx are supported. The
440 'xxxxx' part, for instance 'homebrew' on OS/X, is ignored.
441
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700442 Args:
A. Unique TensorFlower28ce1d12017-08-15 12:08:29 -0700443 version: a version to be converted
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700444
445 Returns:
446 An integer if converted successfully, otherwise return None.
447 """
A. Unique TensorFlower28ce1d12017-08-15 12:08:29 -0700448 version = version.split('-')[0]
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700449 version_segments = version.split('.')
Austin Anderson87ea41d2019-04-04 10:03:50 -0700450 # Treat "0.24" as "0.24.0"
451 if len(version_segments) == 2:
452 version_segments.append('0')
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700453 for seg in version_segments:
454 if not seg.isdigit():
455 return None
456
457 version_str = ''.join(['%03d' % int(seg) for seg in version_segments])
458 return int(version_str)
459
460
Mihai Maruseace7a123f2018-11-30 13:33:25 -0800461def check_bazel_version(min_version, max_version):
462 """Check installed bazel version is between min_version and max_version.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700463
464 Args:
465 min_version: string for minimum bazel version.
Mihai Maruseace7a123f2018-11-30 13:33:25 -0800466 max_version: string for maximum bazel version.
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700467
468 Returns:
469 The bazel version detected.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700470 """
Jonathan Hseu008910f2017-08-25 14:01:05 -0700471 if which('bazel') is None:
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700472 print('Cannot find bazel. Please install bazel.')
473 sys.exit(0)
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700474 curr_version = run_shell(
475 ['bazel', '--batch', '--bazelrc=/dev/null', 'version'])
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700476
477 for line in curr_version.split('\n'):
478 if 'Build label: ' in line:
479 curr_version = line.split('Build label: ')[1]
480 break
481
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700482 min_version_int = convert_version_to_int(min_version)
483 curr_version_int = convert_version_to_int(curr_version)
Mihai Maruseace7a123f2018-11-30 13:33:25 -0800484 max_version_int = convert_version_to_int(max_version)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700485
486 # Check if current bazel version can be detected properly.
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700487 if not curr_version_int:
488 print('WARNING: current bazel installation is not a release version.')
489 print('Make sure you are running at least bazel %s' % min_version)
490 return curr_version
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700491
Michael Cased94271a2017-08-22 17:26:52 -0700492 print('You have bazel %s installed.' % curr_version)
A. Unique TensorFlower28ce1d12017-08-15 12:08:29 -0700493
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700494 if curr_version_int < min_version_int:
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700495 print('Please upgrade your bazel installation to version %s or higher to '
496 'build TensorFlow!' % min_version)
Jason Zamanb41761c2018-10-14 11:28:53 +0800497 sys.exit(1)
TensorFlower Gardener78c246b2018-12-13 12:37:42 -0800498 if (curr_version_int > max_version_int and
499 'TF_IGNORE_MAX_BAZEL_VERSION' not in os.environ):
Mihai Maruseace7a123f2018-11-30 13:33:25 -0800500 print('Please downgrade your bazel installation to version %s or lower to '
Mihai Maruseace0963c42018-12-20 14:27:40 -0800501 'build TensorFlow! To downgrade: download the installer for the old '
502 'version (from https://github.com/bazelbuild/bazel/releases) then '
503 'run the installer.' % max_version)
Jason Zamanb41761c2018-10-14 11:28:53 +0800504 sys.exit(1)
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700505 return curr_version
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700506
507
508def set_cc_opt_flags(environ_cp):
509 """Set up architecture-dependent optimization flags.
510
511 Also append CC optimization flags to bazel.rc..
512
513 Args:
514 environ_cp: copy of the os.environ.
515 """
516 if is_ppc64le():
517 # gcc on ppc64le does not support -march, use mcpu instead
518 default_cc_opt_flags = '-mcpu=native'
A. Unique TensorFlower1bba94a2018-04-04 15:45:20 -0700519 elif is_windows():
520 default_cc_opt_flags = '/arch:AVX'
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700521 else:
Justin Lebar9ef04f52018-10-10 18:52:45 -0700522 default_cc_opt_flags = '-march=native -Wno-sign-compare'
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700523 question = ('Please specify optimization flags to use during compilation when'
524 ' bazel option "--config=opt" is specified [Default is %s]: '
525 ) % default_cc_opt_flags
526 cc_opt_flags = get_from_env_or_user_or_default(environ_cp, 'CC_OPT_FLAGS',
527 question, default_cc_opt_flags)
528 for opt in cc_opt_flags.split():
Michael Case00177422017-11-10 13:14:03 -0800529 write_to_bazelrc('build:opt --copt=%s' % opt)
530 # It should be safe on the same build host.
A. Unique TensorFlower1bba94a2018-04-04 15:45:20 -0700531 if not is_ppc64le() and not is_windows():
Shanqing Cai71445712018-03-12 19:33:52 -0700532 write_to_bazelrc('build:opt --host_copt=-march=native')
Michael Casebb3355d2017-11-09 08:46:31 -0800533 write_to_bazelrc('build:opt --define with_default_optimizations=true')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700534
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700535
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700536def set_tf_cuda_clang(environ_cp):
537 """set TF_CUDA_CLANG action_env.
538
539 Args:
540 environ_cp: copy of the os.environ.
541 """
542 question = 'Do you want to use clang as CUDA compiler?'
543 yes_reply = 'Clang will be used as CUDA compiler.'
544 no_reply = 'nvcc will be used as CUDA compiler.'
545 set_action_env_var(
546 environ_cp,
547 'TF_CUDA_CLANG',
548 None,
549 False,
550 question=question,
551 yes_reply=yes_reply,
552 no_reply=no_reply)
553
554
A. Unique TensorFlowerfd29e952017-12-22 03:07:51 -0800555def set_tf_download_clang(environ_cp):
556 """Set TF_DOWNLOAD_CLANG action_env."""
Ilya Biryukov9e651e42018-03-22 05:33:42 -0700557 question = 'Do you wish to download a fresh release of clang? (Experimental)'
A. Unique TensorFlowerfd29e952017-12-22 03:07:51 -0800558 yes_reply = 'Clang will be downloaded and used to compile tensorflow.'
559 no_reply = 'Clang will not be downloaded.'
560 set_action_env_var(
561 environ_cp,
562 'TF_DOWNLOAD_CLANG',
563 None,
564 False,
565 question=question,
566 yes_reply=yes_reply,
567 no_reply=no_reply)
568
569
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700570def get_from_env_or_user_or_default(environ_cp, var_name, ask_for_var,
571 var_default):
572 """Get var_name either from env, or user or default.
573
574 If var_name has been set as environment variable, use the preset value, else
575 ask for user input. If no input is provided, the default is used.
576
577 Args:
578 environ_cp: copy of the os.environ.
579 var_name: string for name of environment variable, e.g. "TF_NEED_HDFS".
580 ask_for_var: string for how to ask for user input.
581 var_default: default value string.
582
583 Returns:
584 string value for var_name
585 """
586 var = environ_cp.get(var_name)
587 if not var:
588 var = get_input(ask_for_var)
Michael Cased94271a2017-08-22 17:26:52 -0700589 print('\n')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700590 if not var:
591 var = var_default
592 return var
593
594
595def set_clang_cuda_compiler_path(environ_cp):
596 """Set CLANG_CUDA_COMPILER_PATH."""
Jonathan Hseu008910f2017-08-25 14:01:05 -0700597 default_clang_path = which('clang') or ''
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700598 ask_clang_path = ('Please specify which clang should be used as device and '
599 'host compiler. [Default is %s]: ') % default_clang_path
600
601 while True:
602 clang_cuda_compiler_path = get_from_env_or_user_or_default(
603 environ_cp, 'CLANG_CUDA_COMPILER_PATH', ask_clang_path,
604 default_clang_path)
605 if os.path.exists(clang_cuda_compiler_path):
606 break
607
608 # Reset and retry
609 print('Invalid clang path: %s cannot be found.' % clang_cuda_compiler_path)
610 environ_cp['CLANG_CUDA_COMPILER_PATH'] = ''
611
612 # Set CLANG_CUDA_COMPILER_PATH
613 environ_cp['CLANG_CUDA_COMPILER_PATH'] = clang_cuda_compiler_path
614 write_action_env_to_bazelrc('CLANG_CUDA_COMPILER_PATH',
615 clang_cuda_compiler_path)
616
617
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700618def prompt_loop_or_load_from_env(environ_cp,
619 var_name,
620 var_default,
621 ask_for_var,
622 check_success,
623 error_msg,
624 suppress_default_error=False,
625 n_ask_attempts=_DEFAULT_PROMPT_ASK_ATTEMPTS):
Austin Anderson6afface2017-12-05 11:59:17 -0800626 """Loop over user prompts for an ENV param until receiving a valid response.
627
628 For the env param var_name, read from the environment or verify user input
629 until receiving valid input. When done, set var_name in the environ_cp to its
630 new value.
631
632 Args:
633 environ_cp: (Dict) copy of the os.environ.
634 var_name: (String) string for name of environment variable, e.g. "TF_MYVAR".
635 var_default: (String) default value string.
636 ask_for_var: (String) string for how to ask for user input.
637 check_success: (Function) function that takes one argument and returns a
638 boolean. Should return True if the value provided is considered valid. May
639 contain a complex error message if error_msg does not provide enough
640 information. In that case, set suppress_default_error to True.
641 error_msg: (String) String with one and only one '%s'. Formatted with each
642 invalid response upon check_success(input) failure.
643 suppress_default_error: (Bool) Suppress the above error message in favor of
644 one from the check_success function.
645 n_ask_attempts: (Integer) Number of times to query for valid input before
646 raising an error and quitting.
647
648 Returns:
649 [String] The value of var_name after querying for input.
650
651 Raises:
652 UserInputError: if a query has been attempted n_ask_attempts times without
Frank Chenc4ef9272018-01-10 11:36:52 -0800653 success, assume that the user has made a scripting error, and will
654 continue to provide invalid input. Raise the error to avoid infinitely
655 looping.
Austin Anderson6afface2017-12-05 11:59:17 -0800656 """
657 default = environ_cp.get(var_name) or var_default
658 full_query = '%s [Default is %s]: ' % (
659 ask_for_var,
660 default,
661 )
662
663 for _ in range(n_ask_attempts):
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700664 val = get_from_env_or_user_or_default(environ_cp, var_name, full_query,
Austin Anderson6afface2017-12-05 11:59:17 -0800665 default)
666 if check_success(val):
667 break
668 if not suppress_default_error:
669 print(error_msg % val)
670 environ_cp[var_name] = ''
671 else:
A. Unique TensorFlower5001ac02019-04-03 11:59:08 -0700672 raise UserInputError('Invalid %s setting was provided %d times in a row. '
673 'Assuming to be a scripting mistake.' %
674 (var_name, n_ask_attempts))
Austin Anderson6afface2017-12-05 11:59:17 -0800675
676 environ_cp[var_name] = val
677 return val
678
679
680def create_android_ndk_rule(environ_cp):
681 """Set ANDROID_NDK_HOME and write Android NDK WORKSPACE rule."""
682 if is_windows() or is_cygwin():
A. Unique TensorFlower5001ac02019-04-03 11:59:08 -0700683 default_ndk_path = cygpath('%s/Android/Sdk/ndk-bundle' %
684 environ_cp['APPDATA'])
Austin Anderson6afface2017-12-05 11:59:17 -0800685 elif is_macos():
686 default_ndk_path = '%s/library/Android/Sdk/ndk-bundle' % environ_cp['HOME']
687 else:
688 default_ndk_path = '%s/Android/Sdk/ndk-bundle' % environ_cp['HOME']
689
690 def valid_ndk_path(path):
691 return (os.path.exists(path) and
692 os.path.exists(os.path.join(path, 'source.properties')))
693
694 android_ndk_home_path = prompt_loop_or_load_from_env(
695 environ_cp,
696 var_name='ANDROID_NDK_HOME',
697 var_default=default_ndk_path,
698 ask_for_var='Please specify the home path of the Android NDK to use.',
699 check_success=valid_ndk_path,
700 error_msg=('The path %s or its child file "source.properties" '
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700701 'does not exist.'))
Michael Case51053502018-06-05 17:47:19 -0700702 write_action_env_to_bazelrc('ANDROID_NDK_HOME', android_ndk_home_path)
Jared Dukea0104b72019-04-04 12:23:58 -0700703 write_action_env_to_bazelrc(
704 'ANDROID_NDK_API_LEVEL',
705 get_ndk_api_level(environ_cp, android_ndk_home_path))
Austin Anderson6afface2017-12-05 11:59:17 -0800706
707
708def create_android_sdk_rule(environ_cp):
709 """Set Android variables and write Android SDK WORKSPACE rule."""
710 if is_windows() or is_cygwin():
711 default_sdk_path = cygpath('%s/Android/Sdk' % environ_cp['APPDATA'])
712 elif is_macos():
Shashi Shekharc0ff0cc2018-07-17 09:00:24 -0700713 default_sdk_path = '%s/library/Android/Sdk' % environ_cp['HOME']
Austin Anderson6afface2017-12-05 11:59:17 -0800714 else:
715 default_sdk_path = '%s/Android/Sdk' % environ_cp['HOME']
716
717 def valid_sdk_path(path):
718 return (os.path.exists(path) and
719 os.path.exists(os.path.join(path, 'platforms')) and
720 os.path.exists(os.path.join(path, 'build-tools')))
721
722 android_sdk_home_path = prompt_loop_or_load_from_env(
723 environ_cp,
724 var_name='ANDROID_SDK_HOME',
725 var_default=default_sdk_path,
726 ask_for_var='Please specify the home path of the Android SDK to use.',
727 check_success=valid_sdk_path,
728 error_msg=('Either %s does not exist, or it does not contain the '
729 'subdirectories "platforms" and "build-tools".'))
730
731 platforms = os.path.join(android_sdk_home_path, 'platforms')
732 api_levels = sorted(os.listdir(platforms))
733 api_levels = [x.replace('android-', '') for x in api_levels]
734
735 def valid_api_level(api_level):
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700736 return os.path.exists(
737 os.path.join(android_sdk_home_path, 'platforms',
738 'android-' + api_level))
Austin Anderson6afface2017-12-05 11:59:17 -0800739
740 android_api_level = prompt_loop_or_load_from_env(
741 environ_cp,
742 var_name='ANDROID_API_LEVEL',
743 var_default=api_levels[-1],
744 ask_for_var=('Please specify the Android SDK API level to use. '
745 '[Available levels: %s]') % api_levels,
746 check_success=valid_api_level,
747 error_msg='Android-%s is not present in the SDK path.')
748
749 build_tools = os.path.join(android_sdk_home_path, 'build-tools')
750 versions = sorted(os.listdir(build_tools))
751
752 def valid_build_tools(version):
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700753 return os.path.exists(
754 os.path.join(android_sdk_home_path, 'build-tools', version))
Austin Anderson6afface2017-12-05 11:59:17 -0800755
756 android_build_tools_version = prompt_loop_or_load_from_env(
757 environ_cp,
758 var_name='ANDROID_BUILD_TOOLS_VERSION',
759 var_default=versions[-1],
760 ask_for_var=('Please specify an Android build tools version to use. '
761 '[Available versions: %s]') % versions,
762 check_success=valid_build_tools,
763 error_msg=('The selected SDK does not have build-tools version %s '
764 'available.'))
765
Michael Case51053502018-06-05 17:47:19 -0700766 write_action_env_to_bazelrc('ANDROID_BUILD_TOOLS_VERSION',
767 android_build_tools_version)
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700768 write_action_env_to_bazelrc('ANDROID_SDK_API_LEVEL', android_api_level)
769 write_action_env_to_bazelrc('ANDROID_SDK_HOME', android_sdk_home_path)
Austin Anderson6afface2017-12-05 11:59:17 -0800770
771
Jared Dukea0104b72019-04-04 12:23:58 -0700772def get_ndk_api_level(environ_cp, android_ndk_home_path):
773 """Gets the appropriate NDK API level to use for the provided Android NDK path."""
774
775 # First check to see if we're using a blessed version of the NDK.
Austin Anderson6afface2017-12-05 11:59:17 -0800776 properties_path = '%s/source.properties' % android_ndk_home_path
777 if is_windows() or is_cygwin():
778 properties_path = cygpath(properties_path)
779 with open(properties_path, 'r') as f:
780 filedata = f.read()
781
782 revision = re.search(r'Pkg.Revision = (\d+)', filedata)
783 if revision:
Jared Dukea0104b72019-04-04 12:23:58 -0700784 ndk_version = revision.group(1)
Michael Case51053502018-06-05 17:47:19 -0700785 else:
786 raise Exception('Unable to parse NDK revision.')
Jared Dukea0104b72019-04-04 12:23:58 -0700787 if int(ndk_version) not in _SUPPORTED_ANDROID_NDK_VERSIONS:
788 print('WARNING: The NDK version in %s is %s, which is not '
789 'supported by Bazel (officially supported versions: %s). Please use '
790 'another version. Compiling Android targets may result in confusing '
791 'errors.\n' % (android_ndk_home_path, ndk_version,
792 _SUPPORTED_ANDROID_NDK_VERSIONS))
793
794 # Now grab the NDK API level to use. Note that this is different from the
795 # SDK API level, as the NDK API level is effectively the *min* target SDK
796 # version.
797 platforms = os.path.join(android_ndk_home_path, 'platforms')
798 api_levels = sorted(os.listdir(platforms))
799 api_levels = [
800 x.replace('android-', '') for x in api_levels if 'android-' in x
801 ]
802
803 def valid_api_level(api_level):
804 return os.path.exists(
805 os.path.join(android_ndk_home_path, 'platforms',
806 'android-' + api_level))
807
808 android_ndk_api_level = prompt_loop_or_load_from_env(
809 environ_cp,
810 var_name='ANDROID_NDK_API_LEVEL',
811 var_default='18', # 18 is required for GPU acceleration.
812 ask_for_var=('Please specify the (min) Android NDK API level to use. '
813 '[Available levels: %s]') % api_levels,
814 check_success=valid_api_level,
815 error_msg='Android-%s is not present in the NDK path.')
816
817 return android_ndk_api_level
Austin Anderson6afface2017-12-05 11:59:17 -0800818
819
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700820def set_gcc_host_compiler_path(environ_cp):
821 """Set GCC_HOST_COMPILER_PATH."""
Jonathan Hseu008910f2017-08-25 14:01:05 -0700822 default_gcc_host_compiler_path = which('gcc') or ''
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700823 cuda_bin_symlink = '%s/bin/gcc' % environ_cp.get('CUDA_TOOLKIT_PATH')
824
825 if os.path.islink(cuda_bin_symlink):
826 # os.readlink is only available in linux
Jonathan Hseu008910f2017-08-25 14:01:05 -0700827 default_gcc_host_compiler_path = os.path.realpath(cuda_bin_symlink)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700828
Austin Anderson6afface2017-12-05 11:59:17 -0800829 gcc_host_compiler_path = prompt_loop_or_load_from_env(
830 environ_cp,
831 var_name='GCC_HOST_COMPILER_PATH',
832 var_default=default_gcc_host_compiler_path,
TensorFlower Gardenerabb763b2019-02-06 16:23:03 -0800833 ask_for_var='Please specify which gcc should be used by nvcc as the host compiler.',
Austin Anderson6afface2017-12-05 11:59:17 -0800834 check_success=os.path.exists,
835 error_msg='Invalid gcc path. %s cannot be found.',
836 )
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700837
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700838 write_action_env_to_bazelrc('GCC_HOST_COMPILER_PATH', gcc_host_compiler_path)
839
840
Ankur Taly0e6f39d2018-02-16 18:22:55 -0800841def reformat_version_sequence(version_str, sequence_count):
842 """Reformat the version string to have the given number of sequences.
843
844 For example:
845 Given (7, 2) -> 7.0
846 (7.0.1, 2) -> 7.0
847 (5, 1) -> 5
848 (5.0.3.2, 1) -> 5
849
850 Args:
851 version_str: String, the version string.
852 sequence_count: int, an integer.
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700853
Ankur Taly0e6f39d2018-02-16 18:22:55 -0800854 Returns:
855 string, reformatted version string.
856 """
857 v = version_str.split('.')
858 if len(v) < sequence_count:
859 v = v + (['0'] * (sequence_count - len(v)))
860
861 return '.'.join(v[:sequence_count])
862
863
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700864def set_tf_cuda_version(environ_cp):
865 """Set CUDA_TOOLKIT_PATH and TF_CUDA_VERSION."""
866 ask_cuda_version = (
A. Unique TensorFlowerb15500b2018-05-08 12:04:38 -0700867 'Please specify the CUDA SDK version you want to use. '
868 '[Leave empty to default to CUDA %s]: ') % _DEFAULT_CUDA_VERSION
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700869
Austin Andersonf9a88f82017-12-13 11:49:40 -0800870 for _ in range(_DEFAULT_PROMPT_ASK_ATTEMPTS):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700871 # Configure the Cuda SDK version to use.
A. Unique TensorFlower5001ac02019-04-03 11:59:08 -0700872 tf_cuda_version = get_from_env_or_user_or_default(environ_cp,
873 'TF_CUDA_VERSION',
874 ask_cuda_version,
875 _DEFAULT_CUDA_VERSION)
Ankur Taly0e6f39d2018-02-16 18:22:55 -0800876 tf_cuda_version = reformat_version_sequence(str(tf_cuda_version), 2)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700877
878 # Find out where the CUDA toolkit is installed
879 default_cuda_path = _DEFAULT_CUDA_PATH
Martin Wicked57572e2017-09-02 19:21:45 -0700880 if is_windows() or is_cygwin():
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700881 default_cuda_path = cygpath(
882 environ_cp.get('CUDA_PATH', _DEFAULT_CUDA_PATH_WIN))
883 elif is_linux():
884 # If the default doesn't exist, try an alternative default.
885 if (not os.path.exists(default_cuda_path)
886 ) and os.path.exists(_DEFAULT_CUDA_PATH_LINUX):
887 default_cuda_path = _DEFAULT_CUDA_PATH_LINUX
888 ask_cuda_path = ('Please specify the location where CUDA %s toolkit is'
889 ' installed. Refer to README.md for more details. '
890 '[Default is %s]: ') % (tf_cuda_version, default_cuda_path)
A. Unique TensorFlower5001ac02019-04-03 11:59:08 -0700891 cuda_toolkit_path = get_from_env_or_user_or_default(environ_cp,
892 'CUDA_TOOLKIT_PATH',
893 ask_cuda_path,
894 default_cuda_path)
A. Unique TensorFlower02f17fe2018-07-07 06:59:19 -0700895 if is_windows() or is_cygwin():
896 cuda_toolkit_path = cygpath(cuda_toolkit_path)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700897
898 if is_windows():
Niall Moranb7d97e82018-08-09 00:29:49 +0100899 cuda_rt_lib_paths = ['lib/x64/cudart.lib']
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700900 elif is_linux():
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700901 cuda_rt_lib_paths = [
902 '%s/libcudart.so.%s' % (x, tf_cuda_version) for x in [
903 'lib64',
904 'lib/powerpc64le-linux-gnu',
905 'lib/x86_64-linux-gnu',
906 ]
907 ]
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700908 elif is_macos():
Niall Moranb7d97e82018-08-09 00:29:49 +0100909 cuda_rt_lib_paths = ['lib/libcudart.%s.dylib' % tf_cuda_version]
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700910
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700911 cuda_toolkit_paths_full = [
912 os.path.join(cuda_toolkit_path, x) for x in cuda_rt_lib_paths
913 ]
Sergei Lebedev95d7bbb2018-11-21 10:40:10 -0800914 if any(os.path.exists(x) for x in cuda_toolkit_paths_full):
Yifei Feng5198cb82018-08-17 13:53:06 -0700915 break
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700916
917 # Reset and retry
918 print('Invalid path to CUDA %s toolkit. %s cannot be found' %
hellcom9a13fc32018-09-12 10:58:24 +0300919 (tf_cuda_version, cuda_toolkit_paths_full))
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700920 environ_cp['TF_CUDA_VERSION'] = ''
921 environ_cp['CUDA_TOOLKIT_PATH'] = ''
922
Austin Andersonf9a88f82017-12-13 11:49:40 -0800923 else:
924 raise UserInputError('Invalid TF_CUDA_SETTING setting was provided %d '
925 'times in a row. Assuming to be a scripting mistake.' %
926 _DEFAULT_PROMPT_ASK_ATTEMPTS)
927
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700928 # Set CUDA_TOOLKIT_PATH and TF_CUDA_VERSION
929 environ_cp['CUDA_TOOLKIT_PATH'] = cuda_toolkit_path
930 write_action_env_to_bazelrc('CUDA_TOOLKIT_PATH', cuda_toolkit_path)
931 environ_cp['TF_CUDA_VERSION'] = tf_cuda_version
932 write_action_env_to_bazelrc('TF_CUDA_VERSION', tf_cuda_version)
933
934
Yifei Fengb1d8c592017-11-22 13:42:21 -0800935def set_tf_cudnn_version(environ_cp):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700936 """Set CUDNN_INSTALL_PATH and TF_CUDNN_VERSION."""
937 ask_cudnn_version = (
Jonathan Hseu008910f2017-08-25 14:01:05 -0700938 'Please specify the cuDNN version you want to use. '
A. Unique TensorFlower44acd832018-10-01 13:42:40 -0700939 '[Leave empty to default to cuDNN %s]: ') % _DEFAULT_CUDNN_VERSION
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700940
Austin Andersonf9a88f82017-12-13 11:49:40 -0800941 for _ in range(_DEFAULT_PROMPT_ASK_ATTEMPTS):
A. Unique TensorFlower5001ac02019-04-03 11:59:08 -0700942 tf_cudnn_version = get_from_env_or_user_or_default(environ_cp,
943 'TF_CUDNN_VERSION',
944 ask_cudnn_version,
945 _DEFAULT_CUDNN_VERSION)
Ankur Taly0e6f39d2018-02-16 18:22:55 -0800946 tf_cudnn_version = reformat_version_sequence(str(tf_cudnn_version), 1)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700947
948 default_cudnn_path = environ_cp.get('CUDA_TOOLKIT_PATH')
949 ask_cudnn_path = (r'Please specify the location where cuDNN %s library is '
950 'installed. Refer to README.md for more details. [Default'
A. Unique TensorFlower1b212352018-07-19 13:48:50 -0700951 ' is %s]: ') % (tf_cudnn_version, default_cudnn_path)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700952 cudnn_install_path = get_from_env_or_user_or_default(
953 environ_cp, 'CUDNN_INSTALL_PATH', ask_cudnn_path, default_cudnn_path)
954
955 # Result returned from "read" will be used unexpanded. That make "~"
956 # unusable. Going through one more level of expansion to handle that.
957 cudnn_install_path = os.path.realpath(
958 os.path.expanduser(cudnn_install_path))
Martin Wicked57572e2017-09-02 19:21:45 -0700959 if is_windows() or is_cygwin():
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700960 cudnn_install_path = cygpath(cudnn_install_path)
961
962 if is_windows():
963 cuda_dnn_lib_path = 'lib/x64/cudnn.lib'
964 cuda_dnn_lib_alt_path = 'lib/x64/cudnn.lib'
965 elif is_linux():
966 cuda_dnn_lib_path = 'lib64/libcudnn.so.%s' % tf_cudnn_version
967 cuda_dnn_lib_alt_path = 'libcudnn.so.%s' % tf_cudnn_version
968 elif is_macos():
969 cuda_dnn_lib_path = 'lib/libcudnn.%s.dylib' % tf_cudnn_version
970 cuda_dnn_lib_alt_path = 'libcudnn.%s.dylib' % tf_cudnn_version
971
972 cuda_dnn_lib_path_full = os.path.join(cudnn_install_path, cuda_dnn_lib_path)
973 cuda_dnn_lib_alt_path_full = os.path.join(cudnn_install_path,
974 cuda_dnn_lib_alt_path)
975 if os.path.exists(cuda_dnn_lib_path_full) or os.path.exists(
976 cuda_dnn_lib_alt_path_full):
977 break
978
979 # Try another alternative for Linux
980 if is_linux():
Jonathan Hseu008910f2017-08-25 14:01:05 -0700981 ldconfig_bin = which('ldconfig') or '/sbin/ldconfig'
982 cudnn_path_from_ldconfig = run_shell([ldconfig_bin, '-p'])
983 cudnn_path_from_ldconfig = re.search('.*libcudnn.so .* => (.*)',
A. Unique TensorFlowere7223582017-09-06 17:57:04 -0700984 cudnn_path_from_ldconfig)
985 if cudnn_path_from_ldconfig:
986 cudnn_path_from_ldconfig = cudnn_path_from_ldconfig.group(1)
A. Unique TensorFlower5001ac02019-04-03 11:59:08 -0700987 if os.path.exists('%s.%s' %
988 (cudnn_path_from_ldconfig, tf_cudnn_version)):
A. Unique TensorFlowere7223582017-09-06 17:57:04 -0700989 cudnn_install_path = os.path.dirname(cudnn_path_from_ldconfig)
990 break
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700991
992 # Reset and Retry
993 print(
994 'Invalid path to cuDNN %s toolkit. None of the following files can be '
995 'found:' % tf_cudnn_version)
996 print(cuda_dnn_lib_path_full)
997 print(cuda_dnn_lib_alt_path_full)
998 if is_linux():
999 print('%s.%s' % (cudnn_path_from_ldconfig, tf_cudnn_version))
1000
1001 environ_cp['TF_CUDNN_VERSION'] = ''
Austin Andersonf9a88f82017-12-13 11:49:40 -08001002 else:
1003 raise UserInputError('Invalid TF_CUDNN setting was provided %d '
1004 'times in a row. Assuming to be a scripting mistake.' %
1005 _DEFAULT_PROMPT_ASK_ATTEMPTS)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001006
1007 # Set CUDNN_INSTALL_PATH and TF_CUDNN_VERSION
1008 environ_cp['CUDNN_INSTALL_PATH'] = cudnn_install_path
1009 write_action_env_to_bazelrc('CUDNN_INSTALL_PATH', cudnn_install_path)
1010 environ_cp['TF_CUDNN_VERSION'] = tf_cudnn_version
1011 write_action_env_to_bazelrc('TF_CUDNN_VERSION', tf_cudnn_version)
1012
1013
Mingxing Tan1e7b0e42018-06-28 19:13:20 -07001014def is_cuda_compatible(lib, cuda_ver, cudnn_ver):
1015 """Check compatibility between given library and cudnn/cudart libraries."""
1016 ldd_bin = which('ldd') or '/usr/bin/ldd'
1017 ldd_out = run_shell([ldd_bin, lib], True)
1018 ldd_out = ldd_out.split(os.linesep)
1019 cudnn_pattern = re.compile('.*libcudnn.so\\.?(.*) =>.*$')
1020 cuda_pattern = re.compile('.*libcudart.so\\.?(.*) =>.*$')
1021 cudnn = None
1022 cudart = None
1023 cudnn_ok = True # assume no cudnn dependency by default
1024 cuda_ok = True # assume no cuda dependency by default
1025 for line in ldd_out:
1026 if 'libcudnn.so' in line:
1027 cudnn = cudnn_pattern.search(line)
1028 cudnn_ok = False
1029 elif 'libcudart.so' in line:
1030 cudart = cuda_pattern.search(line)
1031 cuda_ok = False
1032 if cudnn and len(cudnn.group(1)):
1033 cudnn = convert_version_to_int(cudnn.group(1))
1034 if cudart and len(cudart.group(1)):
1035 cudart = convert_version_to_int(cudart.group(1))
1036 if cudnn is not None:
1037 cudnn_ok = (cudnn == cudnn_ver)
1038 if cudart is not None:
1039 cuda_ok = (cudart == cuda_ver)
1040 return cudnn_ok and cuda_ok
1041
1042
Guangda Lai76f69382018-01-25 23:59:19 -08001043def set_tf_tensorrt_install_path(environ_cp):
1044 """Set TENSORRT_INSTALL_PATH and TF_TENSORRT_VERSION.
1045
1046 Adapted from code contributed by Sami Kama (https://github.com/samikama).
1047
1048 Args:
1049 environ_cp: copy of the os.environ.
1050
1051 Raises:
1052 ValueError: if this method was called under non-Linux platform.
1053 UserInputError: if user has provided invalid input multiple times.
1054 """
1055 if not is_linux():
1056 raise ValueError('Currently TensorRT is only supported on Linux platform.')
1057
1058 # Ask user whether to add TensorRT support.
Mingxing Tan1e7b0e42018-06-28 19:13:20 -07001059 if str(int(get_var(environ_cp, 'TF_NEED_TENSORRT', 'TensorRT',
1060 False))) != '1':
Guangda Lai76f69382018-01-25 23:59:19 -08001061 return
1062
1063 for _ in range(_DEFAULT_PROMPT_ASK_ATTEMPTS):
1064 ask_tensorrt_path = (r'Please specify the location where TensorRT is '
1065 'installed. [Default is %s]:') % (
1066 _DEFAULT_TENSORRT_PATH_LINUX)
1067 trt_install_path = get_from_env_or_user_or_default(
1068 environ_cp, 'TENSORRT_INSTALL_PATH', ask_tensorrt_path,
1069 _DEFAULT_TENSORRT_PATH_LINUX)
1070
1071 # Result returned from "read" will be used unexpanded. That make "~"
1072 # unusable. Going through one more level of expansion to handle that.
Mingxing Tan1e7b0e42018-06-28 19:13:20 -07001073 trt_install_path = os.path.realpath(os.path.expanduser(trt_install_path))
Guangda Lai76f69382018-01-25 23:59:19 -08001074
1075 def find_libs(search_path):
1076 """Search for libnvinfer.so in "search_path"."""
1077 fl = set()
1078 if os.path.exists(search_path) and os.path.isdir(search_path):
Mingxing Tan1e7b0e42018-06-28 19:13:20 -07001079 fl.update([
1080 os.path.realpath(os.path.join(search_path, x))
1081 for x in os.listdir(search_path)
1082 if 'libnvinfer.so' in x
1083 ])
Guangda Lai76f69382018-01-25 23:59:19 -08001084 return fl
1085
1086 possible_files = find_libs(trt_install_path)
1087 possible_files.update(find_libs(os.path.join(trt_install_path, 'lib')))
1088 possible_files.update(find_libs(os.path.join(trt_install_path, 'lib64')))
Guangda Lai76f69382018-01-25 23:59:19 -08001089 cuda_ver = convert_version_to_int(environ_cp['TF_CUDA_VERSION'])
1090 cudnn_ver = convert_version_to_int(environ_cp['TF_CUDNN_VERSION'])
1091 nvinfer_pattern = re.compile('.*libnvinfer.so.?(.*)$')
1092 highest_ver = [0, None, None]
1093
1094 for lib_file in possible_files:
Mingxing Tan1e7b0e42018-06-28 19:13:20 -07001095 if is_cuda_compatible(lib_file, cuda_ver, cudnn_ver):
Jacques Pienaar2d0531d2018-03-21 12:07:51 -07001096 matches = nvinfer_pattern.search(lib_file)
TensorFlower Gardener61a87202018-10-01 12:25:39 -07001097 if not matches.groups():
Jacques Pienaar2d0531d2018-03-21 12:07:51 -07001098 continue
1099 ver_str = matches.group(1)
Guangda Lai76f69382018-01-25 23:59:19 -08001100 ver = convert_version_to_int(ver_str) if len(ver_str) else 0
1101 if ver > highest_ver[0]:
1102 highest_ver = [ver, ver_str, lib_file]
1103 if highest_ver[1] is not None:
1104 trt_install_path = os.path.dirname(highest_ver[2])
1105 tf_tensorrt_version = highest_ver[1]
1106 break
1107
1108 # Try another alternative from ldconfig.
1109 ldconfig_bin = which('ldconfig') or '/sbin/ldconfig'
1110 ldconfig_output = run_shell([ldconfig_bin, '-p'])
Mingxing Tan1e7b0e42018-06-28 19:13:20 -07001111 search_result = re.search('.*libnvinfer.so\\.?([0-9.]*).* => (.*)',
1112 ldconfig_output)
Guangda Lai76f69382018-01-25 23:59:19 -08001113 if search_result:
1114 libnvinfer_path_from_ldconfig = search_result.group(2)
1115 if os.path.exists(libnvinfer_path_from_ldconfig):
Mingxing Tan1e7b0e42018-06-28 19:13:20 -07001116 if is_cuda_compatible(libnvinfer_path_from_ldconfig, cuda_ver,
1117 cudnn_ver):
Guangda Lai76f69382018-01-25 23:59:19 -08001118 trt_install_path = os.path.dirname(libnvinfer_path_from_ldconfig)
1119 tf_tensorrt_version = search_result.group(1)
1120 break
1121
1122 # Reset and Retry
Yifei Fengdce9a492018-02-22 14:24:57 -08001123 if possible_files:
1124 print('TensorRT libraries found in one the following directories',
1125 'are not compatible with selected cuda and cudnn installations')
1126 print(trt_install_path)
1127 print(os.path.join(trt_install_path, 'lib'))
1128 print(os.path.join(trt_install_path, 'lib64'))
1129 if search_result:
1130 print(libnvinfer_path_from_ldconfig)
1131 else:
1132 print(
1133 'Invalid path to TensorRT. None of the following files can be found:')
1134 print(trt_install_path)
1135 print(os.path.join(trt_install_path, 'lib'))
1136 print(os.path.join(trt_install_path, 'lib64'))
1137 if search_result:
1138 print(libnvinfer_path_from_ldconfig)
Guangda Lai76f69382018-01-25 23:59:19 -08001139
1140 else:
1141 raise UserInputError('Invalid TF_TENSORRT setting was provided %d '
1142 'times in a row. Assuming to be a scripting mistake.' %
1143 _DEFAULT_PROMPT_ASK_ATTEMPTS)
1144
1145 # Set TENSORRT_INSTALL_PATH and TF_TENSORRT_VERSION
1146 environ_cp['TENSORRT_INSTALL_PATH'] = trt_install_path
1147 write_action_env_to_bazelrc('TENSORRT_INSTALL_PATH', trt_install_path)
1148 environ_cp['TF_TENSORRT_VERSION'] = tf_tensorrt_version
1149 write_action_env_to_bazelrc('TF_TENSORRT_VERSION', tf_tensorrt_version)
1150
1151
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001152def set_tf_nccl_install_path(environ_cp):
Jason Furmanek7c234152018-09-26 04:44:12 +00001153 """Set NCCL_INSTALL_PATH, NCCL_HDR_PATH and TF_NCCL_VERSION.
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001154
1155 Args:
1156 environ_cp: copy of the os.environ.
1157
1158 Raises:
1159 ValueError: if this method was called under non-Linux platform.
1160 UserInputError: if user has provided invalid input multiple times.
1161 """
1162 if not is_linux():
1163 raise ValueError('Currently NCCL is only supported on Linux platforms.')
1164
1165 ask_nccl_version = (
A. Unique TensorFlower53faa312018-10-05 08:46:54 -07001166 'Please specify the locally installed NCCL version you want to use. '
1167 '[Default is to use https://github.com/nvidia/nccl]: ')
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001168
1169 for _ in range(_DEFAULT_PROMPT_ASK_ATTEMPTS):
A. Unique TensorFlower5001ac02019-04-03 11:59:08 -07001170 tf_nccl_version = get_from_env_or_user_or_default(environ_cp,
1171 'TF_NCCL_VERSION',
1172 ask_nccl_version, '')
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001173
A. Unique TensorFlower53faa312018-10-05 08:46:54 -07001174 if not tf_nccl_version:
1175 break # No need to get install path, building the open source code.
1176
1177 tf_nccl_version = reformat_version_sequence(str(tf_nccl_version), 1)
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001178
Jason Furmanek7c234152018-09-26 04:44:12 +00001179 # Look with ldconfig first if we can find the library in paths
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001180 # like /usr/lib/x86_64-linux-gnu and the header file in the corresponding
1181 # include directory. This is where the NCCL .deb packages install them.
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001182
Jason Furmanek7c234152018-09-26 04:44:12 +00001183 # First check to see if NCCL is in the ldconfig.
1184 # If its found, use that location.
1185 if is_linux():
1186 ldconfig_bin = which('ldconfig') or '/sbin/ldconfig'
1187 nccl2_path_from_ldconfig = run_shell([ldconfig_bin, '-p'])
1188 nccl2_path_from_ldconfig = re.search('.*libnccl.so .* => (.*)',
1189 nccl2_path_from_ldconfig)
1190 if nccl2_path_from_ldconfig:
1191 nccl2_path_from_ldconfig = nccl2_path_from_ldconfig.group(1)
1192 if os.path.exists('%s.%s' % (nccl2_path_from_ldconfig, tf_nccl_version)):
1193 nccl_install_path = os.path.dirname(nccl2_path_from_ldconfig)
1194 print('NCCL libraries found in ' + nccl2_path_from_ldconfig)
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001195
Jason Furmanek7c234152018-09-26 04:44:12 +00001196 # Check if this is the main system lib location
1197 if re.search('.*linux-gnu', nccl_install_path):
TensorFlower Gardenerea5c5292018-10-01 17:28:26 -07001198 trunc_nccl_install_path = '/usr'
1199 print('This looks like a system path.')
Jason Furmanek7c234152018-09-26 04:44:12 +00001200 else:
TensorFlower Gardenerea5c5292018-10-01 17:28:26 -07001201 trunc_nccl_install_path = nccl_install_path + '/..'
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001202
Jason Furmanek7c234152018-09-26 04:44:12 +00001203 # Look for header
TensorFlower Gardenerea5c5292018-10-01 17:28:26 -07001204 nccl_hdr_path = trunc_nccl_install_path + '/include'
1205 print('Assuming NCCL header path is ' + nccl_hdr_path)
1206 if os.path.exists(nccl_hdr_path + '/nccl.h'):
Jason Furmanek7c234152018-09-26 04:44:12 +00001207 # Set NCCL_INSTALL_PATH
1208 environ_cp['NCCL_INSTALL_PATH'] = nccl_install_path
1209 write_action_env_to_bazelrc('NCCL_INSTALL_PATH', nccl_install_path)
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001210
Jason Furmanek7c234152018-09-26 04:44:12 +00001211 # Set NCCL_HDR_PATH
1212 environ_cp['NCCL_HDR_PATH'] = nccl_hdr_path
1213 write_action_env_to_bazelrc('NCCL_HDR_PATH', nccl_hdr_path)
1214 break
1215 else:
TensorFlower Gardenerea5c5292018-10-01 17:28:26 -07001216 print(
1217 'The header for NCCL2 cannot be found. Please install the libnccl-dev package.'
1218 )
Jason Furmanek7c234152018-09-26 04:44:12 +00001219 else:
TensorFlower Gardenerea5c5292018-10-01 17:28:26 -07001220 print('NCCL2 is listed by ldconfig but the library is not found. '
1221 'Your ldconfig is out of date. Please run sudo ldconfig.')
Jason Furmanek7c234152018-09-26 04:44:12 +00001222 else:
1223 # NCCL is not found in ldconfig. Ask the user for the location.
1224 default_nccl_path = environ_cp.get('CUDA_TOOLKIT_PATH')
TensorFlower Gardenerea5c5292018-10-01 17:28:26 -07001225 ask_nccl_path = (
1226 r'Please specify the location where NCCL %s library is '
1227 'installed. Refer to README.md for more details. [Default '
1228 'is %s]:') % (tf_nccl_version, default_nccl_path)
Jason Furmanek7c234152018-09-26 04:44:12 +00001229 nccl_install_path = get_from_env_or_user_or_default(
TensorFlower Gardenerea5c5292018-10-01 17:28:26 -07001230 environ_cp, 'NCCL_INSTALL_PATH', ask_nccl_path, default_nccl_path)
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001231
Jason Furmanek7c234152018-09-26 04:44:12 +00001232 # Result returned from "read" will be used unexpanded. That make "~"
1233 # unusable. Going through one more level of expansion to handle that.
TensorFlower Gardenerea5c5292018-10-01 17:28:26 -07001234 nccl_install_path = os.path.realpath(
1235 os.path.expanduser(nccl_install_path))
Jason Furmanek7c234152018-09-26 04:44:12 +00001236 if is_windows() or is_cygwin():
1237 nccl_install_path = cygpath(nccl_install_path)
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001238
Guangda Lai62ebf622018-10-23 07:44:13 -07001239 nccl_lib_path = ''
Jason Furmanek7c234152018-09-26 04:44:12 +00001240 if is_windows():
1241 nccl_lib_path = 'lib/x64/nccl.lib'
1242 elif is_linux():
1243 nccl_lib_filename = 'libnccl.so.%s' % tf_nccl_version
1244 nccl_lpath = '%s/lib/%s' % (nccl_install_path, nccl_lib_filename)
1245 if not os.path.exists(nccl_lpath):
1246 for relative_path in NCCL_LIB_PATHS:
TensorFlower Gardenerea5c5292018-10-01 17:28:26 -07001247 path = '%s/%s%s' % (nccl_install_path, relative_path,
1248 nccl_lib_filename)
Jason Furmanek7c234152018-09-26 04:44:12 +00001249 if os.path.exists(path):
TensorFlower Gardenerea5c5292018-10-01 17:28:26 -07001250 print('NCCL found at ' + path)
Jason Furmanek7c234152018-09-26 04:44:12 +00001251 nccl_lib_path = path
1252 break
1253 else:
1254 nccl_lib_path = nccl_lpath
1255 elif is_macos():
1256 nccl_lib_path = 'lib/libnccl.%s.dylib' % tf_nccl_version
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001257
Jason Furmanek7c234152018-09-26 04:44:12 +00001258 nccl_lib_path = os.path.join(nccl_install_path, nccl_lib_path)
TensorFlower Gardenerea5c5292018-10-01 17:28:26 -07001259 nccl_hdr_path = os.path.join(
1260 os.path.dirname(nccl_lib_path), '../include/nccl.h')
1261 print('Assuming NCCL header path is ' + nccl_hdr_path)
Jason Furmanek7c234152018-09-26 04:44:12 +00001262 if os.path.exists(nccl_lib_path) and os.path.exists(nccl_hdr_path):
1263 # Set NCCL_INSTALL_PATH
1264 environ_cp['NCCL_INSTALL_PATH'] = os.path.dirname(nccl_lib_path)
TensorFlower Gardenerea5c5292018-10-01 17:28:26 -07001265 write_action_env_to_bazelrc('NCCL_INSTALL_PATH',
1266 os.path.dirname(nccl_lib_path))
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001267
Jason Furmanek7c234152018-09-26 04:44:12 +00001268 # Set NCCL_HDR_PATH
1269 environ_cp['NCCL_HDR_PATH'] = os.path.dirname(nccl_hdr_path)
TensorFlower Gardenerea5c5292018-10-01 17:28:26 -07001270 write_action_env_to_bazelrc('NCCL_HDR_PATH',
1271 os.path.dirname(nccl_hdr_path))
Jason Furmanek7c234152018-09-26 04:44:12 +00001272 break
1273
1274 # Reset and Retry
TensorFlower Gardenerea5c5292018-10-01 17:28:26 -07001275 print(
1276 'Invalid path to NCCL %s toolkit, %s or %s not found. Please use the '
A. Unique TensorFlowered297342019-03-15 11:25:28 -07001277 'O/S agnostic package of NCCL 2' %
1278 (tf_nccl_version, nccl_lib_path, nccl_hdr_path))
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001279
Jason Furmanek7c234152018-09-26 04:44:12 +00001280 environ_cp['TF_NCCL_VERSION'] = ''
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001281 else:
1282 raise UserInputError('Invalid TF_NCCL setting was provided %d '
1283 'times in a row. Assuming to be a scripting mistake.' %
1284 _DEFAULT_PROMPT_ASK_ATTEMPTS)
1285
1286 # Set TF_NCCL_VERSION
1287 environ_cp['TF_NCCL_VERSION'] = tf_nccl_version
1288 write_action_env_to_bazelrc('TF_NCCL_VERSION', tf_nccl_version)
1289
TensorFlower Gardenerabb763b2019-02-06 16:23:03 -08001290
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001291def get_native_cuda_compute_capabilities(environ_cp):
1292 """Get native cuda compute capabilities.
1293
1294 Args:
1295 environ_cp: copy of the os.environ.
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -07001296
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001297 Returns:
1298 string of native cuda compute capabilities, separated by comma.
1299 """
1300 device_query_bin = os.path.join(
1301 environ_cp.get('CUDA_TOOLKIT_PATH'), 'extras/demo_suite/deviceQuery')
Jonathan Hseu008910f2017-08-25 14:01:05 -07001302 if os.path.isfile(device_query_bin) and os.access(device_query_bin, os.X_OK):
1303 try:
1304 output = run_shell(device_query_bin).split('\n')
1305 pattern = re.compile('[0-9]*\\.[0-9]*')
1306 output = [pattern.search(x) for x in output if 'Capability' in x]
1307 output = ','.join(x.group() for x in output if x is not None)
1308 except subprocess.CalledProcessError:
1309 output = ''
1310 else:
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001311 output = ''
1312 return output
1313
1314
1315def set_tf_cuda_compute_capabilities(environ_cp):
1316 """Set TF_CUDA_COMPUTE_CAPABILITIES."""
1317 while True:
1318 native_cuda_compute_capabilities = get_native_cuda_compute_capabilities(
1319 environ_cp)
1320 if not native_cuda_compute_capabilities:
1321 default_cuda_compute_capabilities = _DEFAULT_CUDA_COMPUTE_CAPABILITIES
1322 else:
1323 default_cuda_compute_capabilities = native_cuda_compute_capabilities
1324
1325 ask_cuda_compute_capabilities = (
1326 'Please specify a list of comma-separated '
P Sudeepam52093562019-02-17 17:34:01 +05301327 'CUDA compute capabilities you want to '
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001328 'build with.\nYou can find the compute '
1329 'capability of your device at: '
1330 'https://developer.nvidia.com/cuda-gpus.\nPlease'
1331 ' note that each additional compute '
1332 'capability significantly increases your '
P Sudeepam52093562019-02-17 17:34:01 +05301333 'build time and binary size, and that '
1334 'TensorFlow only supports compute '
P Sudeepam765ceda2019-02-17 17:39:08 +05301335 'capabilities >= 3.5 [Default is: %s]: ' %
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001336 default_cuda_compute_capabilities)
1337 tf_cuda_compute_capabilities = get_from_env_or_user_or_default(
1338 environ_cp, 'TF_CUDA_COMPUTE_CAPABILITIES',
1339 ask_cuda_compute_capabilities, default_cuda_compute_capabilities)
1340 # Check whether all capabilities from the input is valid
1341 all_valid = True
Maciejd0f5bc12018-04-30 22:30:58 -05001342 # Remove all whitespace characters before splitting the string
Michael Case51053502018-06-05 17:47:19 -07001343 # that users may insert by accident, as this will result in error
Maciejd0f5bc12018-04-30 22:30:58 -05001344 tf_cuda_compute_capabilities = ''.join(tf_cuda_compute_capabilities.split())
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001345 for compute_capability in tf_cuda_compute_capabilities.split(','):
Andrew Harp6e3e7d12017-08-21 12:10:44 -07001346 m = re.match('[0-9]+.[0-9]+', compute_capability)
1347 if not m:
Austin Anderson32202dc2019-02-19 10:46:27 -08001348 print('Invalid compute capability: %s' % compute_capability)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001349 all_valid = False
Andrew Harp6e3e7d12017-08-21 12:10:44 -07001350 else:
P Sudeepam52093562019-02-17 17:34:01 +05301351 ver = float(m.group(0))
A. Unique TensorFlower8dc2d0e2019-03-12 01:41:05 -07001352 if ver < 3.0:
1353 print('ERROR: TensorFlow only supports CUDA compute capabilities 3.0 '
Austin Anderson32202dc2019-02-19 10:46:27 -08001354 'and higher. Please re-specify the list of compute '
1355 'capabilities excluding version %s.' % ver)
Andrew Harp6e3e7d12017-08-21 12:10:44 -07001356 all_valid = False
A. Unique TensorFlower8dc2d0e2019-03-12 01:41:05 -07001357 if ver < 3.5:
1358 print('WARNING: XLA does not support CUDA compute capabilities '
1359 'lower than 3.5. Disable XLA when running on older GPUs.')
P Sudeepam765ceda2019-02-17 17:39:08 +05301360
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001361 if all_valid:
1362 break
1363
1364 # Reset and Retry
1365 environ_cp['TF_CUDA_COMPUTE_CAPABILITIES'] = ''
1366
1367 # Set TF_CUDA_COMPUTE_CAPABILITIES
1368 environ_cp['TF_CUDA_COMPUTE_CAPABILITIES'] = tf_cuda_compute_capabilities
1369 write_action_env_to_bazelrc('TF_CUDA_COMPUTE_CAPABILITIES',
1370 tf_cuda_compute_capabilities)
1371
1372
1373def set_other_cuda_vars(environ_cp):
1374 """Set other CUDA related variables."""
A. Unique TensorFlowerab391982018-07-11 04:52:49 -07001375 # If CUDA is enabled, always use GPU during build and test.
1376 if environ_cp.get('TF_CUDA_CLANG') == '1':
1377 write_to_bazelrc('build --config=cuda_clang')
1378 write_to_bazelrc('test --config=cuda_clang')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001379 else:
A. Unique TensorFlowerab391982018-07-11 04:52:49 -07001380 write_to_bazelrc('build --config=cuda')
1381 write_to_bazelrc('test --config=cuda')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001382
1383
1384def set_host_cxx_compiler(environ_cp):
1385 """Set HOST_CXX_COMPILER."""
Jonathan Hseu008910f2017-08-25 14:01:05 -07001386 default_cxx_host_compiler = which('g++') or ''
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001387
Austin Anderson6afface2017-12-05 11:59:17 -08001388 host_cxx_compiler = prompt_loop_or_load_from_env(
1389 environ_cp,
1390 var_name='HOST_CXX_COMPILER',
1391 var_default=default_cxx_host_compiler,
1392 ask_for_var=('Please specify which C++ compiler should be used as the '
1393 'host C++ compiler.'),
1394 check_success=os.path.exists,
1395 error_msg='Invalid C++ compiler path. %s cannot be found.',
1396 )
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001397
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001398 write_action_env_to_bazelrc('HOST_CXX_COMPILER', host_cxx_compiler)
1399
1400
1401def set_host_c_compiler(environ_cp):
1402 """Set HOST_C_COMPILER."""
Jonathan Hseu008910f2017-08-25 14:01:05 -07001403 default_c_host_compiler = which('gcc') or ''
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001404
Austin Anderson6afface2017-12-05 11:59:17 -08001405 host_c_compiler = prompt_loop_or_load_from_env(
1406 environ_cp,
1407 var_name='HOST_C_COMPILER',
1408 var_default=default_c_host_compiler,
Shanqing Cai71445712018-03-12 19:33:52 -07001409 ask_for_var=('Please specify which C compiler should be used as the host '
Austin Anderson6afface2017-12-05 11:59:17 -08001410 'C compiler.'),
1411 check_success=os.path.exists,
1412 error_msg='Invalid C compiler path. %s cannot be found.',
1413 )
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001414
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001415 write_action_env_to_bazelrc('HOST_C_COMPILER', host_c_compiler)
1416
1417
1418def set_computecpp_toolkit_path(environ_cp):
1419 """Set COMPUTECPP_TOOLKIT_PATH."""
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001420
Austin Anderson6afface2017-12-05 11:59:17 -08001421 def toolkit_exists(toolkit_path):
1422 """Check if a computecpp toolkit path is valid."""
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001423 if is_linux():
1424 sycl_rt_lib_path = 'lib/libComputeCpp.so'
1425 else:
1426 sycl_rt_lib_path = ''
1427
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -07001428 sycl_rt_lib_path_full = os.path.join(toolkit_path, sycl_rt_lib_path)
Austin Anderson6afface2017-12-05 11:59:17 -08001429 exists = os.path.exists(sycl_rt_lib_path_full)
1430 if not exists:
1431 print('Invalid SYCL %s library path. %s cannot be found' %
1432 (_TF_OPENCL_VERSION, sycl_rt_lib_path_full))
1433 return exists
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001434
Austin Anderson6afface2017-12-05 11:59:17 -08001435 computecpp_toolkit_path = prompt_loop_or_load_from_env(
1436 environ_cp,
1437 var_name='COMPUTECPP_TOOLKIT_PATH',
1438 var_default=_DEFAULT_COMPUTECPP_TOOLKIT_PATH,
1439 ask_for_var=(
1440 'Please specify the location where ComputeCpp for SYCL %s is '
1441 'installed.' % _TF_OPENCL_VERSION),
1442 check_success=toolkit_exists,
1443 error_msg='Invalid SYCL compiler path. %s cannot be found.',
1444 suppress_default_error=True)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001445
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001446 write_action_env_to_bazelrc('COMPUTECPP_TOOLKIT_PATH',
1447 computecpp_toolkit_path)
1448
Michael Cased31531a2018-01-05 14:09:41 -08001449
Dandelion Man?90e42f32017-12-15 18:15:07 -08001450def set_trisycl_include_dir(environ_cp):
Michael Cased31531a2018-01-05 14:09:41 -08001451 """Set TRISYCL_INCLUDE_DIR."""
Frank Chenc4ef9272018-01-10 11:36:52 -08001452
Dandelion Man?90e42f32017-12-15 18:15:07 -08001453 ask_trisycl_include_dir = ('Please specify the location of the triSYCL '
1454 'include directory. (Use --config=sycl_trisycl '
1455 'when building with Bazel) '
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -07001456 '[Default is %s]: ') % (
1457 _DEFAULT_TRISYCL_INCLUDE_DIR)
Frank Chenc4ef9272018-01-10 11:36:52 -08001458
Dandelion Man?90e42f32017-12-15 18:15:07 -08001459 while True:
1460 trisycl_include_dir = get_from_env_or_user_or_default(
Michael Cased31531a2018-01-05 14:09:41 -08001461 environ_cp, 'TRISYCL_INCLUDE_DIR', ask_trisycl_include_dir,
1462 _DEFAULT_TRISYCL_INCLUDE_DIR)
Dandelion Man?90e42f32017-12-15 18:15:07 -08001463 if os.path.exists(trisycl_include_dir):
1464 break
1465
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -07001466 print('Invalid triSYCL include directory, %s cannot be found' %
1467 (trisycl_include_dir))
Dandelion Man?90e42f32017-12-15 18:15:07 -08001468
1469 # Set TRISYCL_INCLUDE_DIR
1470 environ_cp['TRISYCL_INCLUDE_DIR'] = trisycl_include_dir
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -07001471 write_action_env_to_bazelrc('TRISYCL_INCLUDE_DIR', trisycl_include_dir)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001472
Yifei Fengb1d8c592017-11-22 13:42:21 -08001473
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001474def set_mpi_home(environ_cp):
1475 """Set MPI_HOME."""
Austin Anderson6afface2017-12-05 11:59:17 -08001476
Jonathan Hseu008910f2017-08-25 14:01:05 -07001477 default_mpi_home = which('mpirun') or which('mpiexec') or ''
1478 default_mpi_home = os.path.dirname(os.path.dirname(default_mpi_home))
1479
Austin Anderson6afface2017-12-05 11:59:17 -08001480 def valid_mpi_path(mpi_home):
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -07001481 exists = (
1482 os.path.exists(os.path.join(mpi_home, 'include')) and
TensorFlower Gardenerf7c861f2018-11-01 11:29:40 -07001483 (os.path.exists(os.path.join(mpi_home, 'lib')) or
1484 os.path.exists(os.path.join(mpi_home, 'lib64')) or
1485 os.path.exists(os.path.join(mpi_home, 'lib32'))))
Austin Anderson6afface2017-12-05 11:59:17 -08001486 if not exists:
TensorFlower Gardenerf7c861f2018-11-01 11:29:40 -07001487 print(
1488 'Invalid path to the MPI Toolkit. %s or %s or %s or %s cannot be found'
1489 % (os.path.join(mpi_home, 'include'),
Christian Gollba95d092018-10-04 17:06:23 +02001490 os.path.exists(os.path.join(mpi_home, 'lib')),
1491 os.path.exists(os.path.join(mpi_home, 'lib64')),
1492 os.path.exists(os.path.join(mpi_home, 'lib32'))))
Austin Anderson6afface2017-12-05 11:59:17 -08001493 return exists
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001494
Austin Anderson6afface2017-12-05 11:59:17 -08001495 _ = prompt_loop_or_load_from_env(
1496 environ_cp,
1497 var_name='MPI_HOME',
1498 var_default=default_mpi_home,
1499 ask_for_var='Please specify the MPI toolkit folder.',
1500 check_success=valid_mpi_path,
1501 error_msg='',
1502 suppress_default_error=True)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001503
1504
1505def set_other_mpi_vars(environ_cp):
1506 """Set other MPI related variables."""
1507 # Link the MPI header files
1508 mpi_home = environ_cp.get('MPI_HOME')
1509 symlink_force('%s/include/mpi.h' % mpi_home, 'third_party/mpi/mpi.h')
1510
1511 # Determine if we use OpenMPI or MVAPICH, these require different header files
1512 # to be included here to make bazel dependency checker happy
1513 if os.path.exists(os.path.join(mpi_home, 'include/mpi_portable_platform.h')):
1514 symlink_force(
1515 os.path.join(mpi_home, 'include/mpi_portable_platform.h'),
1516 'third_party/mpi/mpi_portable_platform.h')
1517 # TODO(gunan): avoid editing files in configure
1518 sed_in_place('third_party/mpi/mpi.bzl', 'MPI_LIB_IS_OPENMPI=False',
1519 'MPI_LIB_IS_OPENMPI=True')
1520 else:
1521 # MVAPICH / MPICH
1522 symlink_force(
1523 os.path.join(mpi_home, 'include/mpio.h'), 'third_party/mpi/mpio.h')
1524 symlink_force(
1525 os.path.join(mpi_home, 'include/mpicxx.h'), 'third_party/mpi/mpicxx.h')
1526 # TODO(gunan): avoid editing files in configure
1527 sed_in_place('third_party/mpi/mpi.bzl', 'MPI_LIB_IS_OPENMPI=True',
1528 'MPI_LIB_IS_OPENMPI=False')
1529
1530 if os.path.exists(os.path.join(mpi_home, 'lib/libmpi.so')):
1531 symlink_force(
1532 os.path.join(mpi_home, 'lib/libmpi.so'), 'third_party/mpi/libmpi.so')
Christian Gollba95d092018-10-04 17:06:23 +02001533 elif os.path.exists(os.path.join(mpi_home, 'lib64/libmpi.so')):
1534 symlink_force(
1535 os.path.join(mpi_home, 'lib64/libmpi.so'), 'third_party/mpi/libmpi.so')
1536 elif os.path.exists(os.path.join(mpi_home, 'lib32/libmpi.so')):
1537 symlink_force(
1538 os.path.join(mpi_home, 'lib32/libmpi.so'), 'third_party/mpi/libmpi.so')
1539
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001540 else:
TensorFlower Gardenerf7c861f2018-11-01 11:29:40 -07001541 raise ValueError(
1542 'Cannot find the MPI library file in %s/lib or %s/lib64 or %s/lib32' %
Mihai Maruseac91ebeec2019-01-29 17:07:38 -08001543 (mpi_home, mpi_home, mpi_home))
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001544
A. Unique TensorFlowered297342019-03-15 11:25:28 -07001545
A. Unique TensorFlowere9797fd2019-03-22 11:02:40 -07001546def system_specific_test_config(env):
A. Unique TensorFlower7bd86372019-03-21 15:19:30 -07001547 """Add default build and test flags required for TF tests to bazelrc."""
Gunhan Gulsoyfff66962019-02-20 15:28:43 -08001548 write_to_bazelrc('test --flaky_test_attempts=3')
1549 write_to_bazelrc('test --test_size_filters=small,medium')
1550 write_to_bazelrc(
1551 'test --test_tag_filters=-benchmark-test,-no_oss,-oss_serial')
1552 write_to_bazelrc('test --build_tag_filters=-benchmark-test,-no_oss')
1553 if is_windows():
Guangda Laibcd701a2019-03-12 21:04:51 -07001554 if env.get('TF_NEED_CUDA', None) == '1':
Gunhan Gulsoyfff66962019-02-20 15:28:43 -08001555 write_to_bazelrc(
1556 'test --test_tag_filters=-no_windows,-no_windows_gpu,-no_gpu')
1557 write_to_bazelrc(
1558 'test --build_tag_filters=-no_windows,-no_windows_gpu,-no_gpu')
1559 else:
1560 write_to_bazelrc('test --test_tag_filters=-no_windows,-gpu')
1561 write_to_bazelrc('test --build_tag_filters=-no_windows,-gpu')
1562 elif is_macos():
1563 write_to_bazelrc('test --test_tag_filters=-gpu,-nomac,-no_mac')
1564 write_to_bazelrc('test --build_tag_filters=-gpu,-nomac,-no_mac')
1565 elif is_linux():
Guangda Laibcd701a2019-03-12 21:04:51 -07001566 if env.get('TF_NEED_CUDA', None) == '1':
Gunhan Gulsoyfff66962019-02-20 15:28:43 -08001567 write_to_bazelrc('test --test_tag_filters=-no_gpu')
1568 write_to_bazelrc('test --build_tag_filters=-no_gpu')
1569 write_to_bazelrc('test --test_env=LD_LIBRARY_PATH')
1570 else:
1571 write_to_bazelrc('test --test_tag_filters=-gpu')
1572 write_to_bazelrc('test --build_tag_filters=-gpu')
1573
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001574
Yifei Feng5198cb82018-08-17 13:53:06 -07001575def set_system_libs_flag(environ_cp):
1576 syslibs = environ_cp.get('TF_SYSTEM_LIBS', '')
TensorFlower Gardener61a87202018-10-01 12:25:39 -07001577 if syslibs:
Jason Zaman5fc39bd2018-09-16 01:38:55 +08001578 if ',' in syslibs:
1579 syslibs = ','.join(sorted(syslibs.split(',')))
1580 else:
1581 syslibs = ','.join(sorted(syslibs.split()))
Yifei Feng5198cb82018-08-17 13:53:06 -07001582 write_action_env_to_bazelrc('TF_SYSTEM_LIBS', syslibs)
1583
Jason Zaman5fc39bd2018-09-16 01:38:55 +08001584 if 'PREFIX' in environ_cp:
1585 write_to_bazelrc('build --define=PREFIX=%s' % environ_cp['PREFIX'])
1586 if 'LIBDIR' in environ_cp:
1587 write_to_bazelrc('build --define=LIBDIR=%s' % environ_cp['LIBDIR'])
1588 if 'INCLUDEDIR' in environ_cp:
1589 write_to_bazelrc('build --define=INCLUDEDIR=%s' % environ_cp['INCLUDEDIR'])
1590
Yifei Feng5198cb82018-08-17 13:53:06 -07001591
A. Unique TensorFlower1b212352018-07-19 13:48:50 -07001592def set_windows_build_flags(environ_cp):
1593 """Set Windows specific build options."""
1594 # The non-monolithic build is not supported yet
1595 write_to_bazelrc('build --config monolithic')
1596 # Suppress warning messages
1597 write_to_bazelrc('build --copt=-w --host_copt=-w')
Loo Rong Jie31f10d22019-02-02 10:03:20 +08001598 # Fix winsock2.h conflicts
TensorFlower Gardener345cccf2019-02-28 15:22:59 -08001599 write_to_bazelrc(
1600 'build --copt=-DWIN32_LEAN_AND_MEAN --host_copt=-DWIN32_LEAN_AND_MEAN')
A. Unique TensorFlower1b212352018-07-19 13:48:50 -07001601 # Output more verbose information when something goes wrong
1602 write_to_bazelrc('build --verbose_failures')
1603 # The host and target platforms are the same in Windows build. So we don't
1604 # have to distinct them. This avoids building the same targets twice.
1605 write_to_bazelrc('build --distinct_host_configuration=false')
A. Unique TensorFlower1b212352018-07-19 13:48:50 -07001606
1607 if get_var(
1608 environ_cp, 'TF_OVERRIDE_EIGEN_STRONG_INLINE', 'Eigen strong inline',
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -07001609 True, ('Would you like to override eigen strong inline for some C++ '
1610 'compilation to reduce the compilation time?'),
1611 'Eigen strong inline overridden.', 'Not overriding eigen strong inline, '
A. Unique TensorFlower1b212352018-07-19 13:48:50 -07001612 'some compilations could take more than 20 mins.'):
1613 # Due to a known MSVC compiler issue
1614 # https://github.com/tensorflow/tensorflow/issues/10521
1615 # Overriding eigen strong inline speeds up the compiling of
1616 # conv_grad_ops_3d.cc and conv_ops_3d.cc by 20 minutes,
1617 # but this also hurts the performance. Let users decide what they want.
1618 write_to_bazelrc('build --define=override_eigen_strong_inline=true')
Dandelion Man?90e42f32017-12-15 18:15:07 -08001619
A. Unique TensorFlower061c3592017-11-13 14:21:04 -08001620
Michael Cased31531a2018-01-05 14:09:41 -08001621def config_info_line(name, help_text):
1622 """Helper function to print formatted help text for Bazel config options."""
1623 print('\t--config=%-12s\t# %s' % (name, help_text))
1624
1625
A. Unique TensorFlower76e879d2019-03-22 00:25:36 -07001626def configure_ios():
1627 """Configures TensorFlow for iOS builds.
A. Unique TensorFlower93e70732019-02-14 16:45:32 -08001628
A. Unique TensorFlower76e879d2019-03-22 00:25:36 -07001629 This function will only be executed if `is_macos()` is true.
A. Unique TensorFlower93e70732019-02-14 16:45:32 -08001630 """
1631 if not is_macos():
1632 return
A. Unique TensorFlowered297342019-03-15 11:25:28 -07001633 if _TF_CURRENT_BAZEL_VERSION is None or _TF_CURRENT_BAZEL_VERSION < 23000:
1634 print(
1635 'Building Bazel rules on Apple platforms requires Bazel 0.23 or later.')
A. Unique TensorFlower76e879d2019-03-22 00:25:36 -07001636 for filepath in APPLE_BAZEL_FILES:
1637 existing_filepath = os.path.join(_TF_WORKSPACE_ROOT, filepath + '.apple')
1638 renamed_filepath = os.path.join(_TF_WORKSPACE_ROOT, filepath)
1639 symlink_force(existing_filepath, renamed_filepath)
1640 for filepath in IOS_FILES:
1641 filename = os.path.basename(filepath)
1642 new_filepath = os.path.join(_TF_WORKSPACE_ROOT, filename)
1643 symlink_force(filepath, new_filepath)
A. Unique TensorFlower93e70732019-02-14 16:45:32 -08001644
1645
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001646def main():
A. Unique TensorFlower7c5eb352018-10-01 07:15:23 -07001647 global _TF_WORKSPACE_ROOT
1648 global _TF_BAZELRC
A. Unique TensorFlowered297342019-03-15 11:25:28 -07001649 global _TF_CURRENT_BAZEL_VERSION
A. Unique TensorFlower7c5eb352018-10-01 07:15:23 -07001650
Shanqing Cai71445712018-03-12 19:33:52 -07001651 parser = argparse.ArgumentParser()
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -07001652 parser.add_argument(
1653 '--workspace',
1654 type=str,
A. Unique TensorFlower7c5eb352018-10-01 07:15:23 -07001655 default=os.path.abspath(os.path.dirname(__file__)),
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -07001656 help='The absolute path to your active Bazel workspace.')
Shanqing Cai71445712018-03-12 19:33:52 -07001657 args = parser.parse_args()
1658
A. Unique TensorFlower7c5eb352018-10-01 07:15:23 -07001659 _TF_WORKSPACE_ROOT = args.workspace
1660 _TF_BAZELRC = os.path.join(_TF_WORKSPACE_ROOT, _TF_BAZELRC_FILENAME)
1661
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001662 # Make a copy of os.environ to be clear when functions and getting and setting
1663 # environment variables.
1664 environ_cp = dict(os.environ)
1665
A. Unique TensorFlower2b9c2992019-04-04 10:30:19 -07001666 current_bazel_version = check_bazel_version('0.22.0', '0.24.1')
A. Unique TensorFlowered297342019-03-15 11:25:28 -07001667 _TF_CURRENT_BAZEL_VERSION = convert_version_to_int(current_bazel_version)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001668
A. Unique TensorFlower7c5eb352018-10-01 07:15:23 -07001669 reset_tf_configure_bazelrc()
Yun Peng03e63a22018-11-07 11:18:53 +01001670
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001671 cleanup_makefile()
Gunhan Gulsoyed89a2b2017-09-19 18:36:26 -07001672 setup_python(environ_cp)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001673
1674 if is_windows():
Yifei Fengb1d8c592017-11-22 13:42:21 -08001675 environ_cp['TF_NEED_OPENCL_SYCL'] = '0'
1676 environ_cp['TF_NEED_COMPUTECPP'] = '0'
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001677 environ_cp['TF_NEED_OPENCL'] = '0'
1678 environ_cp['TF_CUDA_CLANG'] = '0'
Guangda Lai76f69382018-01-25 23:59:19 -08001679 environ_cp['TF_NEED_TENSORRT'] = '0'
Ilya Biryukov9e651e42018-03-22 05:33:42 -07001680 # TODO(ibiryukov): Investigate using clang as a cpu or cuda compiler on
1681 # Windows.
1682 environ_cp['TF_DOWNLOAD_CLANG'] = '0'
A. Unique TensorFlower6e97fb32018-07-16 14:07:29 -07001683 environ_cp['TF_NEED_MPI'] = '0'
1684 environ_cp['TF_SET_ANDROID_WORKSPACE'] = '0'
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001685
1686 if is_macos():
Guangda Lai76f69382018-01-25 23:59:19 -08001687 environ_cp['TF_NEED_TENSORRT'] = '0'
A. Unique TensorFlower93e70732019-02-14 16:45:32 -08001688 else:
A. Unique TensorFlower76e879d2019-03-22 00:25:36 -07001689 environ_cp['TF_CONFIGURE_IOS'] = '0'
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001690
Jon Triebenbach6896a742018-06-27 13:29:53 -05001691 # The numpy package on ppc64le uses OpenBLAS which has multi-threading
1692 # issues that lead to incorrect answers. Set OMP_NUM_THREADS=1 at
1693 # runtime to allow the Tensorflow testcases which compare numpy
1694 # results to Tensorflow results to succeed.
1695 if is_ppc64le():
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -07001696 write_action_env_to_bazelrc('OMP_NUM_THREADS', 1)
Jon Triebenbach6896a742018-06-27 13:29:53 -05001697
Grzegorz Pawelczakec82efd2018-10-09 15:03:46 +01001698 xla_enabled_by_default = is_linux()
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001699 set_build_var(environ_cp, 'TF_ENABLE_XLA', 'XLA JIT', 'with_xla_support',
Grzegorz Pawelczakec82efd2018-10-09 15:03:46 +01001700 xla_enabled_by_default, 'xla')
Gunhan Gulsoy3da0dff2018-09-26 11:55:50 -07001701
Yifei Fengb1d8c592017-11-22 13:42:21 -08001702 set_action_env_var(environ_cp, 'TF_NEED_OPENCL_SYCL', 'OpenCL SYCL', False)
1703 if environ_cp.get('TF_NEED_OPENCL_SYCL') == '1':
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001704 set_host_cxx_compiler(environ_cp)
1705 set_host_c_compiler(environ_cp)
Yifei Fengb1d8c592017-11-22 13:42:21 -08001706 set_action_env_var(environ_cp, 'TF_NEED_COMPUTECPP', 'ComputeCPP', True)
1707 if environ_cp.get('TF_NEED_COMPUTECPP') == '1':
1708 set_computecpp_toolkit_path(environ_cp)
1709 else:
1710 set_trisycl_include_dir(environ_cp)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001711
Wen-Heng (Jack) Chung69d3b8f2018-06-22 23:09:43 -05001712 set_action_env_var(environ_cp, 'TF_NEED_ROCM', 'ROCm', False)
1713 if (environ_cp.get('TF_NEED_ROCM') == '1' and
TensorFlower Gardener62e60162018-09-27 10:22:55 -07001714 'LD_LIBRARY_PATH' in environ_cp and
1715 environ_cp.get('LD_LIBRARY_PATH') != '1'):
1716 write_action_env_to_bazelrc('LD_LIBRARY_PATH',
1717 environ_cp.get('LD_LIBRARY_PATH'))
Wen-Heng (Jack) Chung69d3b8f2018-06-22 23:09:43 -05001718
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001719 set_action_env_var(environ_cp, 'TF_NEED_CUDA', 'CUDA', False)
A. Unique TensorFlower24cbb2a2017-09-08 07:45:44 -07001720 if (environ_cp.get('TF_NEED_CUDA') == '1' and
1721 'TF_CUDA_CONFIG_REPO' not in environ_cp):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001722 set_tf_cuda_version(environ_cp)
Yifei Fengb1d8c592017-11-22 13:42:21 -08001723 set_tf_cudnn_version(environ_cp)
Guangda Lai76f69382018-01-25 23:59:19 -08001724 if is_linux():
1725 set_tf_tensorrt_install_path(environ_cp)
Michael Case0073d132018-04-11 09:34:44 -07001726 set_tf_nccl_install_path(environ_cp)
1727
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001728 set_tf_cuda_compute_capabilities(environ_cp)
Ankur Taly0e6f39d2018-02-16 18:22:55 -08001729 if 'LD_LIBRARY_PATH' in environ_cp and environ_cp.get(
1730 'LD_LIBRARY_PATH') != '1':
1731 write_action_env_to_bazelrc('LD_LIBRARY_PATH',
1732 environ_cp.get('LD_LIBRARY_PATH'))
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001733
1734 set_tf_cuda_clang(environ_cp)
1735 if environ_cp.get('TF_CUDA_CLANG') == '1':
Ilya Biryukov9e651e42018-03-22 05:33:42 -07001736 # Ask whether we should download the clang toolchain.
1737 set_tf_download_clang(environ_cp)
A. Unique TensorFlowerfd29e952017-12-22 03:07:51 -08001738 if environ_cp.get('TF_DOWNLOAD_CLANG') != '1':
1739 # Set up which clang we should use as the cuda / host compiler.
1740 set_clang_cuda_compiler_path(environ_cp)
Ilya Biryukov1c3d02e2018-09-04 03:09:52 -07001741 else:
1742 # Use downloaded LLD for linking.
1743 write_to_bazelrc('build:cuda_clang --config=download_clang_use_lld')
1744 write_to_bazelrc('test:cuda_clang --config=download_clang_use_lld')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001745 else:
1746 # Set up which gcc nvcc should use as the host compiler
1747 # No need to set this on Windows
1748 if not is_windows():
1749 set_gcc_host_compiler_path(environ_cp)
1750 set_other_cuda_vars(environ_cp)
Ilya Biryukov9e651e42018-03-22 05:33:42 -07001751 else:
1752 # CUDA not required. Ask whether we should download the clang toolchain and
1753 # use it for the CPU build.
1754 set_tf_download_clang(environ_cp)
1755 if environ_cp.get('TF_DOWNLOAD_CLANG') == '1':
1756 write_to_bazelrc('build --config=download_clang')
1757 write_to_bazelrc('test --config=download_clang')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001758
Wen-Heng (Jack) Chung69d3b8f2018-06-22 23:09:43 -05001759 # SYCL / ROCm / CUDA are mutually exclusive.
1760 # At most 1 GPU platform can be configured.
1761 gpu_platform_count = 0
1762 if environ_cp.get('TF_NEED_OPENCL_SYCL') == '1':
1763 gpu_platform_count += 1
1764 if environ_cp.get('TF_NEED_ROCM') == '1':
1765 gpu_platform_count += 1
1766 if environ_cp.get('TF_NEED_CUDA') == '1':
1767 gpu_platform_count += 1
1768 if gpu_platform_count >= 2:
1769 raise UserInputError('SYCL / CUDA / ROCm are mututally exclusive. '
1770 'At most 1 GPU platform can be configured.')
1771
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001772 set_build_var(environ_cp, 'TF_NEED_MPI', 'MPI', 'with_mpi_support', False)
1773 if environ_cp.get('TF_NEED_MPI') == '1':
1774 set_mpi_home(environ_cp)
1775 set_other_mpi_vars(environ_cp)
1776
1777 set_cc_opt_flags(environ_cp)
Yifei Feng5198cb82018-08-17 13:53:06 -07001778 set_system_libs_flag(environ_cp)
A. Unique TensorFlower1b212352018-07-19 13:48:50 -07001779 if is_windows():
1780 set_windows_build_flags(environ_cp)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001781
Anna Ra9a1d5a2018-09-14 12:44:31 -07001782 # Add a config option to build TensorFlow 2.0 API.
1783 write_to_bazelrc('build:v2 --define=tf_api_version=2')
1784
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -07001785 if get_var(environ_cp, 'TF_SET_ANDROID_WORKSPACE', 'android workspace', False,
1786 ('Would you like to interactively configure ./WORKSPACE for '
1787 'Android builds?'), 'Searching for NDK and SDK installations.',
1788 'Not configuring the WORKSPACE for Android builds.'):
Michael Case51053502018-06-05 17:47:19 -07001789 create_android_ndk_rule(environ_cp)
1790 create_android_sdk_rule(environ_cp)
Austin Anderson6afface2017-12-05 11:59:17 -08001791
A. Unique TensorFlowere9797fd2019-03-22 11:02:40 -07001792 system_specific_test_config(os.environ)
Gunhan Gulsoyfff66962019-02-20 15:28:43 -08001793
A. Unique TensorFlower5001ac02019-04-03 11:59:08 -07001794 set_action_env_var(environ_cp, 'TF_CONFIGURE_IOS', 'iOS', False)
1795 if environ_cp.get('TF_CONFIGURE_IOS') == '1':
A. Unique TensorFlower76e879d2019-03-22 00:25:36 -07001796 configure_ios()
A. Unique TensorFlowere9797fd2019-03-22 11:02:40 -07001797 else:
1798 # TODO(pcloudy): Remove BAZEL_USE_CPP_ONLY_TOOLCHAIN after Bazel is upgraded
1799 # to 0.24.0.
1800 # For working around https://github.com/bazelbuild/bazel/issues/7607
1801 if is_macos():
1802 write_to_bazelrc('build --action_env=BAZEL_USE_CPP_ONLY_TOOLCHAIN=1')
A. Unique TensorFlower93e70732019-02-14 16:45:32 -08001803
Gunhan Gulsoy34370982018-10-12 15:26:01 -07001804 print('Preconfigured Bazel build configs. You can use any of the below by '
1805 'adding "--config=<>" to your build command. See .bazelrc for more '
1806 'details.')
1807 config_info_line('mkl', 'Build with MKL support.')
1808 config_info_line('monolithic', 'Config for mostly static monolithic build.')
1809 config_info_line('gdr', 'Build with GDR support.')
1810 config_info_line('verbs', 'Build with libverbs support.')
1811 config_info_line('ngraph', 'Build with Intel nGraph support.')
A. Unique TensorFlowera6bf9c82019-02-26 10:08:35 -08001812 config_info_line('numa', 'Build with NUMA support.')
TensorFlower Gardenerabb763b2019-02-06 16:23:03 -08001813 config_info_line(
1814 'dynamic_kernels',
1815 '(Experimental) Build kernels into separate shared objects.')
Gunhan Gulsoy34370982018-10-12 15:26:01 -07001816
1817 print('Preconfigured Bazel build configs to DISABLE default on features:')
1818 config_info_line('noaws', 'Disable AWS S3 filesystem support.')
1819 config_info_line('nogcp', 'Disable GCP support.')
1820 config_info_line('nohdfs', 'Disable HDFS support.')
Penporn Koanantakool489f1dc2019-01-10 22:07:22 -08001821 config_info_line('noignite', 'Disable Apache Ignite support.')
Gunhan Gulsoy34370982018-10-12 15:26:01 -07001822 config_info_line('nokafka', 'Disable Apache Kafka support.')
Gunhan Gulsoyeea81682018-11-26 16:51:23 -08001823 config_info_line('nonccl', 'Disable NVIDIA NCCL support.')
Austin Anderson6afface2017-12-05 11:59:17 -08001824
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -07001825
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001826if __name__ == '__main__':
1827 main()