blob: 2d919d8d5a2329c24ecd653dc3ee27e0f093ed60 [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 = [
A. Unique TensorFlower6a059c02019-04-05 14:28:27 -070061 'tensorflow/lite/experimental/ios/BUILD',
A. Unique TensorFlower93e70732019-02-14 16:45:32 -080062 'tensorflow/lite/experimental/objc/BUILD',
63 'tensorflow/lite/experimental/swift/BUILD'
64]
65
A. Unique TensorFlower76e879d2019-03-22 00:25:36 -070066# List of files to move when building for iOS.
67IOS_FILES = [
68 'tensorflow/lite/experimental/objc/TensorFlowLiteObjC.podspec',
69 'tensorflow/lite/experimental/swift/TensorFlowLiteSwift.podspec',
70]
71
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -070072if platform.machine() == 'ppc64le':
73 _DEFAULT_TENSORRT_PATH_LINUX = '/usr/lib/powerpc64le-linux-gnu/'
74else:
75 _DEFAULT_TENSORRT_PATH_LINUX = '/usr/lib/%s-linux-gnu' % platform.machine()
76
Austin Anderson6afface2017-12-05 11:59:17 -080077
78class UserInputError(Exception):
79 pass
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -070080
81
82def is_windows():
83 return platform.system() == 'Windows'
84
85
86def is_linux():
87 return platform.system() == 'Linux'
88
89
90def is_macos():
91 return platform.system() == 'Darwin'
92
93
94def is_ppc64le():
95 return platform.machine() == 'ppc64le'
96
97
Jonathan Hseu008910f2017-08-25 14:01:05 -070098def is_cygwin():
99 return platform.system().startswith('CYGWIN_NT')
100
101
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700102def get_input(question):
103 try:
104 try:
105 answer = raw_input(question)
106 except NameError:
107 answer = input(question) # pylint: disable=bad-builtin
108 except EOFError:
109 answer = ''
110 return answer
111
112
113def symlink_force(target, link_name):
114 """Force symlink, equivalent of 'ln -sf'.
115
116 Args:
117 target: items to link to.
118 link_name: name of the link.
119 """
120 try:
121 os.symlink(target, link_name)
122 except OSError as e:
123 if e.errno == errno.EEXIST:
124 os.remove(link_name)
125 os.symlink(target, link_name)
126 else:
127 raise e
128
129
130def sed_in_place(filename, old, new):
131 """Replace old string with new string in file.
132
133 Args:
134 filename: string for filename.
135 old: string to replace.
136 new: new string to replace to.
137 """
138 with open(filename, 'r') as f:
139 filedata = f.read()
140 newdata = filedata.replace(old, new)
141 with open(filename, 'w') as f:
142 f.write(newdata)
143
144
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700145def write_to_bazelrc(line):
146 with open(_TF_BAZELRC, 'a') as f:
147 f.write(line + '\n')
148
149
150def write_action_env_to_bazelrc(var_name, var):
151 write_to_bazelrc('build --action_env %s="%s"' % (var_name, str(var)))
152
153
Jonathan Hseu008910f2017-08-25 14:01:05 -0700154def run_shell(cmd, allow_non_zero=False):
155 if allow_non_zero:
156 try:
157 output = subprocess.check_output(cmd)
158 except subprocess.CalledProcessError as e:
159 output = e.output
160 else:
161 output = subprocess.check_output(cmd)
162 return output.decode('UTF-8').strip()
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700163
164
165def cygpath(path):
166 """Convert path from posix to windows."""
Martin Wicked57572e2017-09-02 19:21:45 -0700167 return os.path.abspath(path).replace('\\', '/')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700168
169
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700170def get_python_path(environ_cp, python_bin_path):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700171 """Get the python site package paths."""
172 python_paths = []
173 if environ_cp.get('PYTHONPATH'):
174 python_paths = environ_cp.get('PYTHONPATH').split(':')
175 try:
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700176 library_paths = run_shell([
177 python_bin_path, '-c',
178 'import site; print("\\n".join(site.getsitepackages()))'
179 ]).split('\n')
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700180 except subprocess.CalledProcessError:
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700181 library_paths = [
182 run_shell([
183 python_bin_path, '-c',
184 'from distutils.sysconfig import get_python_lib;'
185 'print(get_python_lib())'
186 ])
187 ]
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700188
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700189 all_paths = set(python_paths + library_paths)
190
191 paths = []
192 for path in all_paths:
193 if os.path.isdir(path):
194 paths.append(path)
195 return paths
196
197
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700198def get_python_major_version(python_bin_path):
199 """Get the python major version."""
Jonathan Hseu008910f2017-08-25 14:01:05 -0700200 return run_shell([python_bin_path, '-c', 'import sys; print(sys.version[0])'])
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700201
202
Gunhan Gulsoyed89a2b2017-09-19 18:36:26 -0700203def setup_python(environ_cp):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700204 """Setup python related env variables."""
205 # Get PYTHON_BIN_PATH, default is the current running python.
206 default_python_bin_path = sys.executable
207 ask_python_bin_path = ('Please specify the location of python. [Default is '
208 '%s]: ') % default_python_bin_path
209 while True:
A. Unique TensorFlower5001ac02019-04-03 11:59:08 -0700210 python_bin_path = get_from_env_or_user_or_default(environ_cp,
211 'PYTHON_BIN_PATH',
212 ask_python_bin_path,
213 default_python_bin_path)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700214 # Check if the path is valid
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700215 if os.path.isfile(python_bin_path) and os.access(python_bin_path, os.X_OK):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700216 break
217 elif not os.path.exists(python_bin_path):
218 print('Invalid python path: %s cannot be found.' % python_bin_path)
219 else:
220 print('%s is not executable. Is it the python binary?' % python_bin_path)
221 environ_cp['PYTHON_BIN_PATH'] = ''
222
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700223 # Convert python path to Windows style before checking lib and version
Martin Wicked57572e2017-09-02 19:21:45 -0700224 if is_windows() or is_cygwin():
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700225 python_bin_path = cygpath(python_bin_path)
226
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700227 # Get PYTHON_LIB_PATH
228 python_lib_path = environ_cp.get('PYTHON_LIB_PATH')
229 if not python_lib_path:
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700230 python_lib_paths = get_python_path(environ_cp, python_bin_path)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700231 if environ_cp.get('USE_DEFAULT_PYTHON_LIB_PATH') == '1':
Vijay Vasudevana1fba7f2017-07-28 10:58:56 -0700232 python_lib_path = python_lib_paths[0]
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700233 else:
Jonathan Hseu008910f2017-08-25 14:01:05 -0700234 print('Found possible Python library paths:\n %s' %
235 '\n '.join(python_lib_paths))
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700236 default_python_lib_path = python_lib_paths[0]
237 python_lib_path = get_input(
Jonathan Hseu008910f2017-08-25 14:01:05 -0700238 'Please input the desired Python library path to use. '
239 'Default is [%s]\n' % python_lib_paths[0])
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700240 if not python_lib_path:
241 python_lib_path = default_python_lib_path
Vijay Vasudevana1fba7f2017-07-28 10:58:56 -0700242 environ_cp['PYTHON_LIB_PATH'] = python_lib_path
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700243
TensorFlower Gardener61a87202018-10-01 12:25:39 -0700244 _ = get_python_major_version(python_bin_path)
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700245
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700246 # Convert python path to Windows style before writing into bazel.rc
Martin Wicked57572e2017-09-02 19:21:45 -0700247 if is_windows() or is_cygwin():
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700248 python_lib_path = cygpath(python_lib_path)
249
250 # Set-up env variables used by python_configure.bzl
251 write_action_env_to_bazelrc('PYTHON_BIN_PATH', python_bin_path)
252 write_action_env_to_bazelrc('PYTHON_LIB_PATH', python_lib_path)
Gunhan Gulsoyed89a2b2017-09-19 18:36:26 -0700253 write_to_bazelrc('build --python_path=\"%s"' % python_bin_path)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700254 environ_cp['PYTHON_BIN_PATH'] = python_bin_path
255
William D. Ironsdcc76a52018-11-20 10:35:18 -0600256 # If choosen python_lib_path is from a path specified in the PYTHONPATH
257 # variable, need to tell bazel to include PYTHONPATH
258 if environ_cp.get('PYTHONPATH'):
259 python_paths = environ_cp.get('PYTHONPATH').split(':')
260 if python_lib_path in python_paths:
TensorFlower Gardener968cd182018-11-28 11:33:16 -0800261 write_action_env_to_bazelrc('PYTHONPATH', environ_cp.get('PYTHONPATH'))
William D. Ironsdcc76a52018-11-20 10:35:18 -0600262
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700263 # Write tools/python_bin_path.sh
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700264 with open(
265 os.path.join(_TF_WORKSPACE_ROOT, 'tools', 'python_bin_path.sh'),
266 'w') as f:
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700267 f.write('export PYTHON_BIN_PATH="%s"' % python_bin_path)
268
269
A. Unique TensorFlower7c5eb352018-10-01 07:15:23 -0700270def reset_tf_configure_bazelrc():
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700271 """Reset file that contains customized config settings."""
272 open(_TF_BAZELRC, 'w').close()
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700273
TensorFlower Gardenerabb763b2019-02-06 16:23:03 -0800274
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700275def cleanup_makefile():
276 """Delete any leftover BUILD files from the Makefile build.
277
278 These files could interfere with Bazel parsing.
279 """
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700280 makefile_download_dir = os.path.join(_TF_WORKSPACE_ROOT, 'tensorflow',
281 'contrib', 'makefile', 'downloads')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700282 if os.path.isdir(makefile_download_dir):
283 for root, _, filenames in os.walk(makefile_download_dir):
284 for f in filenames:
285 if f.endswith('BUILD'):
286 os.remove(os.path.join(root, f))
287
288
289def get_var(environ_cp,
290 var_name,
291 query_item,
292 enabled_by_default,
293 question=None,
294 yes_reply=None,
295 no_reply=None):
296 """Get boolean input from user.
297
298 If var_name is not set in env, ask user to enable query_item or not. If the
299 response is empty, use the default.
300
301 Args:
302 environ_cp: copy of the os.environ.
303 var_name: string for name of environment variable, e.g. "TF_NEED_HDFS".
304 query_item: string for feature related to the variable, e.g. "Hadoop File
305 System".
306 enabled_by_default: boolean for default behavior.
307 question: optional string for how to ask for user input.
Michael Cased90054e2018-02-07 14:36:00 -0800308 yes_reply: optional string for reply when feature is enabled.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700309 no_reply: optional string for reply when feature is disabled.
310
311 Returns:
312 boolean value of the variable.
Frank Chenc4ef9272018-01-10 11:36:52 -0800313
314 Raises:
315 UserInputError: if an environment variable is set, but it cannot be
316 interpreted as a boolean indicator, assume that the user has made a
317 scripting error, and will continue to provide invalid input.
318 Raise the error to avoid infinitely looping.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700319 """
320 if not question:
321 question = 'Do you wish to build TensorFlow with %s support?' % query_item
322 if not yes_reply:
323 yes_reply = '%s support will be enabled for TensorFlow.' % query_item
324 if not no_reply:
325 no_reply = 'No %s' % yes_reply
326
327 yes_reply += '\n'
328 no_reply += '\n'
329
330 if enabled_by_default:
331 question += ' [Y/n]: '
332 else:
333 question += ' [y/N]: '
334
335 var = environ_cp.get(var_name)
Frank Chenc4ef9272018-01-10 11:36:52 -0800336 if var is not None:
337 var_content = var.strip().lower()
338 true_strings = ('1', 't', 'true', 'y', 'yes')
339 false_strings = ('0', 'f', 'false', 'n', 'no')
340 if var_content in true_strings:
341 var = True
342 elif var_content in false_strings:
343 var = False
344 else:
345 raise UserInputError(
346 'Environment variable %s must be set as a boolean indicator.\n'
347 'The following are accepted as TRUE : %s.\n'
348 'The following are accepted as FALSE: %s.\n'
A. Unique TensorFlowered297342019-03-15 11:25:28 -0700349 'Current value is %s.' %
350 (var_name, ', '.join(true_strings), ', '.join(false_strings), var))
Frank Chenc4ef9272018-01-10 11:36:52 -0800351
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700352 while var is None:
353 user_input_origin = get_input(question)
354 user_input = user_input_origin.strip().lower()
355 if user_input == 'y':
356 print(yes_reply)
357 var = True
358 elif user_input == 'n':
359 print(no_reply)
360 var = False
361 elif not user_input:
362 if enabled_by_default:
363 print(yes_reply)
364 var = True
365 else:
366 print(no_reply)
367 var = False
368 else:
369 print('Invalid selection: %s' % user_input_origin)
370 return var
371
372
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700373def set_build_var(environ_cp,
374 var_name,
375 query_item,
376 option_name,
377 enabled_by_default,
378 bazel_config_name=None):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700379 """Set if query_item will be enabled for the build.
380
381 Ask user if query_item will be enabled. Default is used if no input is given.
382 Set subprocess environment variable and write to .bazelrc if enabled.
383
384 Args:
385 environ_cp: copy of the os.environ.
386 var_name: string for name of environment variable, e.g. "TF_NEED_HDFS".
387 query_item: string for feature related to the variable, e.g. "Hadoop File
388 System".
389 option_name: string for option to define in .bazelrc.
390 enabled_by_default: boolean for default behavior.
Michael Case98850a52017-09-14 13:35:57 -0700391 bazel_config_name: Name for Bazel --config argument to enable build feature.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700392 """
393
394 var = str(int(get_var(environ_cp, var_name, query_item, enabled_by_default)))
395 environ_cp[var_name] = var
396 if var == '1':
A. Unique TensorFlower5001ac02019-04-03 11:59:08 -0700397 write_to_bazelrc('build:%s --define %s=true' %
398 (bazel_config_name, option_name))
Yifei Fengec451f52018-10-05 12:53:50 -0700399 write_to_bazelrc('build --config=%s' % bazel_config_name)
Michael Case98850a52017-09-14 13:35:57 -0700400 elif bazel_config_name is not None:
401 # TODO(mikecase): Migrate all users of configure.py to use --config Bazel
402 # options and not to set build configs through environment variables.
A. Unique TensorFlower5001ac02019-04-03 11:59:08 -0700403 write_to_bazelrc('build:%s --define %s=true' %
404 (bazel_config_name, option_name))
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700405
406
407def set_action_env_var(environ_cp,
408 var_name,
409 query_item,
410 enabled_by_default,
411 question=None,
412 yes_reply=None,
413 no_reply=None):
414 """Set boolean action_env variable.
415
416 Ask user if query_item will be enabled. Default is used if no input is given.
417 Set environment variable and write to .bazelrc.
418
419 Args:
420 environ_cp: copy of the os.environ.
421 var_name: string for name of environment variable, e.g. "TF_NEED_HDFS".
422 query_item: string for feature related to the variable, e.g. "Hadoop File
423 System".
424 enabled_by_default: boolean for default behavior.
425 question: optional string for how to ask for user input.
Michael Cased90054e2018-02-07 14:36:00 -0800426 yes_reply: optional string for reply when feature is enabled.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700427 no_reply: optional string for reply when feature is disabled.
428 """
429 var = int(
430 get_var(environ_cp, var_name, query_item, enabled_by_default, question,
431 yes_reply, no_reply))
432
433 write_action_env_to_bazelrc(var_name, var)
434 environ_cp[var_name] = str(var)
435
436
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700437def convert_version_to_int(version):
438 """Convert a version number to a integer that can be used to compare.
439
A. Unique TensorFlower28ce1d12017-08-15 12:08:29 -0700440 Version strings of the form X.YZ and X.Y.Z-xxxxx are supported. The
441 'xxxxx' part, for instance 'homebrew' on OS/X, is ignored.
442
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700443 Args:
A. Unique TensorFlower28ce1d12017-08-15 12:08:29 -0700444 version: a version to be converted
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700445
446 Returns:
447 An integer if converted successfully, otherwise return None.
448 """
A. Unique TensorFlower28ce1d12017-08-15 12:08:29 -0700449 version = version.split('-')[0]
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700450 version_segments = version.split('.')
Austin Anderson87ea41d2019-04-04 10:03:50 -0700451 # Treat "0.24" as "0.24.0"
452 if len(version_segments) == 2:
453 version_segments.append('0')
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700454 for seg in version_segments:
455 if not seg.isdigit():
456 return None
457
458 version_str = ''.join(['%03d' % int(seg) for seg in version_segments])
459 return int(version_str)
460
461
Mihai Maruseace7a123f2018-11-30 13:33:25 -0800462def check_bazel_version(min_version, max_version):
463 """Check installed bazel version is between min_version and max_version.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700464
465 Args:
466 min_version: string for minimum bazel version.
Mihai Maruseace7a123f2018-11-30 13:33:25 -0800467 max_version: string for maximum bazel version.
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700468
469 Returns:
470 The bazel version detected.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700471 """
Jonathan Hseu008910f2017-08-25 14:01:05 -0700472 if which('bazel') is None:
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700473 print('Cannot find bazel. Please install bazel.')
474 sys.exit(0)
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700475 curr_version = run_shell(
476 ['bazel', '--batch', '--bazelrc=/dev/null', 'version'])
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700477
478 for line in curr_version.split('\n'):
479 if 'Build label: ' in line:
480 curr_version = line.split('Build label: ')[1]
481 break
482
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700483 min_version_int = convert_version_to_int(min_version)
484 curr_version_int = convert_version_to_int(curr_version)
Mihai Maruseace7a123f2018-11-30 13:33:25 -0800485 max_version_int = convert_version_to_int(max_version)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700486
487 # Check if current bazel version can be detected properly.
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700488 if not curr_version_int:
489 print('WARNING: current bazel installation is not a release version.')
490 print('Make sure you are running at least bazel %s' % min_version)
491 return curr_version
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700492
Michael Cased94271a2017-08-22 17:26:52 -0700493 print('You have bazel %s installed.' % curr_version)
A. Unique TensorFlower28ce1d12017-08-15 12:08:29 -0700494
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700495 if curr_version_int < min_version_int:
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700496 print('Please upgrade your bazel installation to version %s or higher to '
497 'build TensorFlow!' % min_version)
Jason Zamanb41761c2018-10-14 11:28:53 +0800498 sys.exit(1)
TensorFlower Gardener78c246b2018-12-13 12:37:42 -0800499 if (curr_version_int > max_version_int and
500 'TF_IGNORE_MAX_BAZEL_VERSION' not in os.environ):
Mihai Maruseace7a123f2018-11-30 13:33:25 -0800501 print('Please downgrade your bazel installation to version %s or lower to '
Mihai Maruseace0963c42018-12-20 14:27:40 -0800502 'build TensorFlow! To downgrade: download the installer for the old '
503 'version (from https://github.com/bazelbuild/bazel/releases) then '
504 'run the installer.' % max_version)
Jason Zamanb41761c2018-10-14 11:28:53 +0800505 sys.exit(1)
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700506 return curr_version
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700507
508
509def set_cc_opt_flags(environ_cp):
510 """Set up architecture-dependent optimization flags.
511
512 Also append CC optimization flags to bazel.rc..
513
514 Args:
515 environ_cp: copy of the os.environ.
516 """
517 if is_ppc64le():
518 # gcc on ppc64le does not support -march, use mcpu instead
519 default_cc_opt_flags = '-mcpu=native'
A. Unique TensorFlower1bba94a2018-04-04 15:45:20 -0700520 elif is_windows():
521 default_cc_opt_flags = '/arch:AVX'
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700522 else:
Justin Lebar9ef04f52018-10-10 18:52:45 -0700523 default_cc_opt_flags = '-march=native -Wno-sign-compare'
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700524 question = ('Please specify optimization flags to use during compilation when'
525 ' bazel option "--config=opt" is specified [Default is %s]: '
526 ) % default_cc_opt_flags
527 cc_opt_flags = get_from_env_or_user_or_default(environ_cp, 'CC_OPT_FLAGS',
528 question, default_cc_opt_flags)
529 for opt in cc_opt_flags.split():
Michael Case00177422017-11-10 13:14:03 -0800530 write_to_bazelrc('build:opt --copt=%s' % opt)
531 # It should be safe on the same build host.
A. Unique TensorFlower1bba94a2018-04-04 15:45:20 -0700532 if not is_ppc64le() and not is_windows():
Shanqing Cai71445712018-03-12 19:33:52 -0700533 write_to_bazelrc('build:opt --host_copt=-march=native')
Michael Casebb3355d2017-11-09 08:46:31 -0800534 write_to_bazelrc('build:opt --define with_default_optimizations=true')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700535
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700536
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700537def set_tf_cuda_clang(environ_cp):
538 """set TF_CUDA_CLANG action_env.
539
540 Args:
541 environ_cp: copy of the os.environ.
542 """
543 question = 'Do you want to use clang as CUDA compiler?'
544 yes_reply = 'Clang will be used as CUDA compiler.'
545 no_reply = 'nvcc will be used as CUDA compiler.'
546 set_action_env_var(
547 environ_cp,
548 'TF_CUDA_CLANG',
549 None,
550 False,
551 question=question,
552 yes_reply=yes_reply,
553 no_reply=no_reply)
554
555
A. Unique TensorFlowerfd29e952017-12-22 03:07:51 -0800556def set_tf_download_clang(environ_cp):
557 """Set TF_DOWNLOAD_CLANG action_env."""
Ilya Biryukov9e651e42018-03-22 05:33:42 -0700558 question = 'Do you wish to download a fresh release of clang? (Experimental)'
A. Unique TensorFlowerfd29e952017-12-22 03:07:51 -0800559 yes_reply = 'Clang will be downloaded and used to compile tensorflow.'
560 no_reply = 'Clang will not be downloaded.'
561 set_action_env_var(
562 environ_cp,
563 'TF_DOWNLOAD_CLANG',
564 None,
565 False,
566 question=question,
567 yes_reply=yes_reply,
568 no_reply=no_reply)
569
570
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700571def get_from_env_or_user_or_default(environ_cp, var_name, ask_for_var,
572 var_default):
573 """Get var_name either from env, or user or default.
574
575 If var_name has been set as environment variable, use the preset value, else
576 ask for user input. If no input is provided, the default is used.
577
578 Args:
579 environ_cp: copy of the os.environ.
580 var_name: string for name of environment variable, e.g. "TF_NEED_HDFS".
581 ask_for_var: string for how to ask for user input.
582 var_default: default value string.
583
584 Returns:
585 string value for var_name
586 """
587 var = environ_cp.get(var_name)
588 if not var:
589 var = get_input(ask_for_var)
Michael Cased94271a2017-08-22 17:26:52 -0700590 print('\n')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700591 if not var:
592 var = var_default
593 return var
594
595
596def set_clang_cuda_compiler_path(environ_cp):
597 """Set CLANG_CUDA_COMPILER_PATH."""
Jonathan Hseu008910f2017-08-25 14:01:05 -0700598 default_clang_path = which('clang') or ''
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700599 ask_clang_path = ('Please specify which clang should be used as device and '
600 'host compiler. [Default is %s]: ') % default_clang_path
601
602 while True:
603 clang_cuda_compiler_path = get_from_env_or_user_or_default(
604 environ_cp, 'CLANG_CUDA_COMPILER_PATH', ask_clang_path,
605 default_clang_path)
606 if os.path.exists(clang_cuda_compiler_path):
607 break
608
609 # Reset and retry
610 print('Invalid clang path: %s cannot be found.' % clang_cuda_compiler_path)
611 environ_cp['CLANG_CUDA_COMPILER_PATH'] = ''
612
613 # Set CLANG_CUDA_COMPILER_PATH
614 environ_cp['CLANG_CUDA_COMPILER_PATH'] = clang_cuda_compiler_path
615 write_action_env_to_bazelrc('CLANG_CUDA_COMPILER_PATH',
616 clang_cuda_compiler_path)
617
618
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700619def prompt_loop_or_load_from_env(environ_cp,
620 var_name,
621 var_default,
622 ask_for_var,
623 check_success,
624 error_msg,
625 suppress_default_error=False,
626 n_ask_attempts=_DEFAULT_PROMPT_ASK_ATTEMPTS):
Austin Anderson6afface2017-12-05 11:59:17 -0800627 """Loop over user prompts for an ENV param until receiving a valid response.
628
629 For the env param var_name, read from the environment or verify user input
630 until receiving valid input. When done, set var_name in the environ_cp to its
631 new value.
632
633 Args:
634 environ_cp: (Dict) copy of the os.environ.
635 var_name: (String) string for name of environment variable, e.g. "TF_MYVAR".
636 var_default: (String) default value string.
637 ask_for_var: (String) string for how to ask for user input.
638 check_success: (Function) function that takes one argument and returns a
639 boolean. Should return True if the value provided is considered valid. May
640 contain a complex error message if error_msg does not provide enough
641 information. In that case, set suppress_default_error to True.
642 error_msg: (String) String with one and only one '%s'. Formatted with each
643 invalid response upon check_success(input) failure.
644 suppress_default_error: (Bool) Suppress the above error message in favor of
645 one from the check_success function.
646 n_ask_attempts: (Integer) Number of times to query for valid input before
647 raising an error and quitting.
648
649 Returns:
650 [String] The value of var_name after querying for input.
651
652 Raises:
653 UserInputError: if a query has been attempted n_ask_attempts times without
Frank Chenc4ef9272018-01-10 11:36:52 -0800654 success, assume that the user has made a scripting error, and will
655 continue to provide invalid input. Raise the error to avoid infinitely
656 looping.
Austin Anderson6afface2017-12-05 11:59:17 -0800657 """
658 default = environ_cp.get(var_name) or var_default
659 full_query = '%s [Default is %s]: ' % (
660 ask_for_var,
661 default,
662 )
663
664 for _ in range(n_ask_attempts):
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700665 val = get_from_env_or_user_or_default(environ_cp, var_name, full_query,
Austin Anderson6afface2017-12-05 11:59:17 -0800666 default)
667 if check_success(val):
668 break
669 if not suppress_default_error:
670 print(error_msg % val)
671 environ_cp[var_name] = ''
672 else:
A. Unique TensorFlower5001ac02019-04-03 11:59:08 -0700673 raise UserInputError('Invalid %s setting was provided %d times in a row. '
674 'Assuming to be a scripting mistake.' %
675 (var_name, n_ask_attempts))
Austin Anderson6afface2017-12-05 11:59:17 -0800676
677 environ_cp[var_name] = val
678 return val
679
680
681def create_android_ndk_rule(environ_cp):
682 """Set ANDROID_NDK_HOME and write Android NDK WORKSPACE rule."""
683 if is_windows() or is_cygwin():
A. Unique TensorFlower5001ac02019-04-03 11:59:08 -0700684 default_ndk_path = cygpath('%s/Android/Sdk/ndk-bundle' %
685 environ_cp['APPDATA'])
Austin Anderson6afface2017-12-05 11:59:17 -0800686 elif is_macos():
687 default_ndk_path = '%s/library/Android/Sdk/ndk-bundle' % environ_cp['HOME']
688 else:
689 default_ndk_path = '%s/Android/Sdk/ndk-bundle' % environ_cp['HOME']
690
691 def valid_ndk_path(path):
692 return (os.path.exists(path) and
693 os.path.exists(os.path.join(path, 'source.properties')))
694
695 android_ndk_home_path = prompt_loop_or_load_from_env(
696 environ_cp,
697 var_name='ANDROID_NDK_HOME',
698 var_default=default_ndk_path,
699 ask_for_var='Please specify the home path of the Android NDK to use.',
700 check_success=valid_ndk_path,
701 error_msg=('The path %s or its child file "source.properties" '
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700702 'does not exist.'))
Michael Case51053502018-06-05 17:47:19 -0700703 write_action_env_to_bazelrc('ANDROID_NDK_HOME', android_ndk_home_path)
Jared Dukea0104b72019-04-04 12:23:58 -0700704 write_action_env_to_bazelrc(
705 'ANDROID_NDK_API_LEVEL',
706 get_ndk_api_level(environ_cp, android_ndk_home_path))
Austin Anderson6afface2017-12-05 11:59:17 -0800707
708
709def create_android_sdk_rule(environ_cp):
710 """Set Android variables and write Android SDK WORKSPACE rule."""
711 if is_windows() or is_cygwin():
712 default_sdk_path = cygpath('%s/Android/Sdk' % environ_cp['APPDATA'])
713 elif is_macos():
Shashi Shekharc0ff0cc2018-07-17 09:00:24 -0700714 default_sdk_path = '%s/library/Android/Sdk' % environ_cp['HOME']
Austin Anderson6afface2017-12-05 11:59:17 -0800715 else:
716 default_sdk_path = '%s/Android/Sdk' % environ_cp['HOME']
717
718 def valid_sdk_path(path):
719 return (os.path.exists(path) and
720 os.path.exists(os.path.join(path, 'platforms')) and
721 os.path.exists(os.path.join(path, 'build-tools')))
722
723 android_sdk_home_path = prompt_loop_or_load_from_env(
724 environ_cp,
725 var_name='ANDROID_SDK_HOME',
726 var_default=default_sdk_path,
727 ask_for_var='Please specify the home path of the Android SDK to use.',
728 check_success=valid_sdk_path,
729 error_msg=('Either %s does not exist, or it does not contain the '
730 'subdirectories "platforms" and "build-tools".'))
731
732 platforms = os.path.join(android_sdk_home_path, 'platforms')
733 api_levels = sorted(os.listdir(platforms))
734 api_levels = [x.replace('android-', '') for x in api_levels]
735
736 def valid_api_level(api_level):
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700737 return os.path.exists(
738 os.path.join(android_sdk_home_path, 'platforms',
739 'android-' + api_level))
Austin Anderson6afface2017-12-05 11:59:17 -0800740
741 android_api_level = prompt_loop_or_load_from_env(
742 environ_cp,
743 var_name='ANDROID_API_LEVEL',
744 var_default=api_levels[-1],
745 ask_for_var=('Please specify the Android SDK API level to use. '
746 '[Available levels: %s]') % api_levels,
747 check_success=valid_api_level,
748 error_msg='Android-%s is not present in the SDK path.')
749
750 build_tools = os.path.join(android_sdk_home_path, 'build-tools')
751 versions = sorted(os.listdir(build_tools))
752
753 def valid_build_tools(version):
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700754 return os.path.exists(
755 os.path.join(android_sdk_home_path, 'build-tools', version))
Austin Anderson6afface2017-12-05 11:59:17 -0800756
757 android_build_tools_version = prompt_loop_or_load_from_env(
758 environ_cp,
759 var_name='ANDROID_BUILD_TOOLS_VERSION',
760 var_default=versions[-1],
761 ask_for_var=('Please specify an Android build tools version to use. '
762 '[Available versions: %s]') % versions,
763 check_success=valid_build_tools,
764 error_msg=('The selected SDK does not have build-tools version %s '
765 'available.'))
766
Michael Case51053502018-06-05 17:47:19 -0700767 write_action_env_to_bazelrc('ANDROID_BUILD_TOOLS_VERSION',
768 android_build_tools_version)
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700769 write_action_env_to_bazelrc('ANDROID_SDK_API_LEVEL', android_api_level)
770 write_action_env_to_bazelrc('ANDROID_SDK_HOME', android_sdk_home_path)
Austin Anderson6afface2017-12-05 11:59:17 -0800771
772
Jared Dukea0104b72019-04-04 12:23:58 -0700773def get_ndk_api_level(environ_cp, android_ndk_home_path):
774 """Gets the appropriate NDK API level to use for the provided Android NDK path."""
775
776 # First check to see if we're using a blessed version of the NDK.
Austin Anderson6afface2017-12-05 11:59:17 -0800777 properties_path = '%s/source.properties' % android_ndk_home_path
778 if is_windows() or is_cygwin():
779 properties_path = cygpath(properties_path)
780 with open(properties_path, 'r') as f:
781 filedata = f.read()
782
783 revision = re.search(r'Pkg.Revision = (\d+)', filedata)
784 if revision:
Jared Dukea0104b72019-04-04 12:23:58 -0700785 ndk_version = revision.group(1)
Michael Case51053502018-06-05 17:47:19 -0700786 else:
787 raise Exception('Unable to parse NDK revision.')
Jared Dukea0104b72019-04-04 12:23:58 -0700788 if int(ndk_version) not in _SUPPORTED_ANDROID_NDK_VERSIONS:
789 print('WARNING: The NDK version in %s is %s, which is not '
790 'supported by Bazel (officially supported versions: %s). Please use '
791 'another version. Compiling Android targets may result in confusing '
792 'errors.\n' % (android_ndk_home_path, ndk_version,
793 _SUPPORTED_ANDROID_NDK_VERSIONS))
794
795 # Now grab the NDK API level to use. Note that this is different from the
796 # SDK API level, as the NDK API level is effectively the *min* target SDK
797 # version.
798 platforms = os.path.join(android_ndk_home_path, 'platforms')
799 api_levels = sorted(os.listdir(platforms))
800 api_levels = [
801 x.replace('android-', '') for x in api_levels if 'android-' in x
802 ]
803
804 def valid_api_level(api_level):
805 return os.path.exists(
806 os.path.join(android_ndk_home_path, 'platforms',
807 'android-' + api_level))
808
809 android_ndk_api_level = prompt_loop_or_load_from_env(
810 environ_cp,
811 var_name='ANDROID_NDK_API_LEVEL',
812 var_default='18', # 18 is required for GPU acceleration.
813 ask_for_var=('Please specify the (min) Android NDK API level to use. '
814 '[Available levels: %s]') % api_levels,
815 check_success=valid_api_level,
816 error_msg='Android-%s is not present in the NDK path.')
817
818 return android_ndk_api_level
Austin Anderson6afface2017-12-05 11:59:17 -0800819
820
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700821def set_gcc_host_compiler_path(environ_cp):
822 """Set GCC_HOST_COMPILER_PATH."""
Jonathan Hseu008910f2017-08-25 14:01:05 -0700823 default_gcc_host_compiler_path = which('gcc') or ''
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700824 cuda_bin_symlink = '%s/bin/gcc' % environ_cp.get('CUDA_TOOLKIT_PATH')
825
826 if os.path.islink(cuda_bin_symlink):
827 # os.readlink is only available in linux
Jonathan Hseu008910f2017-08-25 14:01:05 -0700828 default_gcc_host_compiler_path = os.path.realpath(cuda_bin_symlink)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700829
Austin Anderson6afface2017-12-05 11:59:17 -0800830 gcc_host_compiler_path = prompt_loop_or_load_from_env(
831 environ_cp,
832 var_name='GCC_HOST_COMPILER_PATH',
833 var_default=default_gcc_host_compiler_path,
TensorFlower Gardenerabb763b2019-02-06 16:23:03 -0800834 ask_for_var='Please specify which gcc should be used by nvcc as the host compiler.',
Austin Anderson6afface2017-12-05 11:59:17 -0800835 check_success=os.path.exists,
836 error_msg='Invalid gcc path. %s cannot be found.',
837 )
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700838
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700839 write_action_env_to_bazelrc('GCC_HOST_COMPILER_PATH', gcc_host_compiler_path)
840
841
Ankur Taly0e6f39d2018-02-16 18:22:55 -0800842def reformat_version_sequence(version_str, sequence_count):
843 """Reformat the version string to have the given number of sequences.
844
845 For example:
846 Given (7, 2) -> 7.0
847 (7.0.1, 2) -> 7.0
848 (5, 1) -> 5
849 (5.0.3.2, 1) -> 5
850
851 Args:
852 version_str: String, the version string.
853 sequence_count: int, an integer.
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700854
Ankur Taly0e6f39d2018-02-16 18:22:55 -0800855 Returns:
856 string, reformatted version string.
857 """
858 v = version_str.split('.')
859 if len(v) < sequence_count:
860 v = v + (['0'] * (sequence_count - len(v)))
861
862 return '.'.join(v[:sequence_count])
863
864
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700865def set_tf_cuda_version(environ_cp):
866 """Set CUDA_TOOLKIT_PATH and TF_CUDA_VERSION."""
867 ask_cuda_version = (
A. Unique TensorFlowerb15500b2018-05-08 12:04:38 -0700868 'Please specify the CUDA SDK version you want to use. '
869 '[Leave empty to default to CUDA %s]: ') % _DEFAULT_CUDA_VERSION
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700870
Austin Andersonf9a88f82017-12-13 11:49:40 -0800871 for _ in range(_DEFAULT_PROMPT_ASK_ATTEMPTS):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700872 # Configure the Cuda SDK version to use.
A. Unique TensorFlower5001ac02019-04-03 11:59:08 -0700873 tf_cuda_version = get_from_env_or_user_or_default(environ_cp,
874 'TF_CUDA_VERSION',
875 ask_cuda_version,
876 _DEFAULT_CUDA_VERSION)
Ankur Taly0e6f39d2018-02-16 18:22:55 -0800877 tf_cuda_version = reformat_version_sequence(str(tf_cuda_version), 2)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700878
879 # Find out where the CUDA toolkit is installed
880 default_cuda_path = _DEFAULT_CUDA_PATH
Martin Wicked57572e2017-09-02 19:21:45 -0700881 if is_windows() or is_cygwin():
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700882 default_cuda_path = cygpath(
883 environ_cp.get('CUDA_PATH', _DEFAULT_CUDA_PATH_WIN))
884 elif is_linux():
885 # If the default doesn't exist, try an alternative default.
886 if (not os.path.exists(default_cuda_path)
887 ) and os.path.exists(_DEFAULT_CUDA_PATH_LINUX):
888 default_cuda_path = _DEFAULT_CUDA_PATH_LINUX
889 ask_cuda_path = ('Please specify the location where CUDA %s toolkit is'
890 ' installed. Refer to README.md for more details. '
891 '[Default is %s]: ') % (tf_cuda_version, default_cuda_path)
A. Unique TensorFlower5001ac02019-04-03 11:59:08 -0700892 cuda_toolkit_path = get_from_env_or_user_or_default(environ_cp,
893 'CUDA_TOOLKIT_PATH',
894 ask_cuda_path,
895 default_cuda_path)
A. Unique TensorFlower02f17fe2018-07-07 06:59:19 -0700896 if is_windows() or is_cygwin():
897 cuda_toolkit_path = cygpath(cuda_toolkit_path)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700898
899 if is_windows():
Niall Moranb7d97e82018-08-09 00:29:49 +0100900 cuda_rt_lib_paths = ['lib/x64/cudart.lib']
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700901 elif is_linux():
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700902 cuda_rt_lib_paths = [
903 '%s/libcudart.so.%s' % (x, tf_cuda_version) for x in [
904 'lib64',
905 'lib/powerpc64le-linux-gnu',
906 'lib/x86_64-linux-gnu',
907 ]
908 ]
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700909 elif is_macos():
Niall Moranb7d97e82018-08-09 00:29:49 +0100910 cuda_rt_lib_paths = ['lib/libcudart.%s.dylib' % tf_cuda_version]
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700911
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700912 cuda_toolkit_paths_full = [
913 os.path.join(cuda_toolkit_path, x) for x in cuda_rt_lib_paths
914 ]
Sergei Lebedev95d7bbb2018-11-21 10:40:10 -0800915 if any(os.path.exists(x) for x in cuda_toolkit_paths_full):
Yifei Feng5198cb82018-08-17 13:53:06 -0700916 break
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700917
918 # Reset and retry
919 print('Invalid path to CUDA %s toolkit. %s cannot be found' %
hellcom9a13fc32018-09-12 10:58:24 +0300920 (tf_cuda_version, cuda_toolkit_paths_full))
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700921 environ_cp['TF_CUDA_VERSION'] = ''
922 environ_cp['CUDA_TOOLKIT_PATH'] = ''
923
Austin Andersonf9a88f82017-12-13 11:49:40 -0800924 else:
925 raise UserInputError('Invalid TF_CUDA_SETTING setting was provided %d '
926 'times in a row. Assuming to be a scripting mistake.' %
927 _DEFAULT_PROMPT_ASK_ATTEMPTS)
928
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700929 # Set CUDA_TOOLKIT_PATH and TF_CUDA_VERSION
930 environ_cp['CUDA_TOOLKIT_PATH'] = cuda_toolkit_path
931 write_action_env_to_bazelrc('CUDA_TOOLKIT_PATH', cuda_toolkit_path)
932 environ_cp['TF_CUDA_VERSION'] = tf_cuda_version
933 write_action_env_to_bazelrc('TF_CUDA_VERSION', tf_cuda_version)
934
935
Yifei Fengb1d8c592017-11-22 13:42:21 -0800936def set_tf_cudnn_version(environ_cp):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700937 """Set CUDNN_INSTALL_PATH and TF_CUDNN_VERSION."""
938 ask_cudnn_version = (
Jonathan Hseu008910f2017-08-25 14:01:05 -0700939 'Please specify the cuDNN version you want to use. '
A. Unique TensorFlower44acd832018-10-01 13:42:40 -0700940 '[Leave empty to default to cuDNN %s]: ') % _DEFAULT_CUDNN_VERSION
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700941
Austin Andersonf9a88f82017-12-13 11:49:40 -0800942 for _ in range(_DEFAULT_PROMPT_ASK_ATTEMPTS):
A. Unique TensorFlower5001ac02019-04-03 11:59:08 -0700943 tf_cudnn_version = get_from_env_or_user_or_default(environ_cp,
944 'TF_CUDNN_VERSION',
945 ask_cudnn_version,
946 _DEFAULT_CUDNN_VERSION)
Ankur Taly0e6f39d2018-02-16 18:22:55 -0800947 tf_cudnn_version = reformat_version_sequence(str(tf_cudnn_version), 1)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700948
949 default_cudnn_path = environ_cp.get('CUDA_TOOLKIT_PATH')
950 ask_cudnn_path = (r'Please specify the location where cuDNN %s library is '
951 'installed. Refer to README.md for more details. [Default'
A. Unique TensorFlower1b212352018-07-19 13:48:50 -0700952 ' is %s]: ') % (tf_cudnn_version, default_cudnn_path)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700953 cudnn_install_path = get_from_env_or_user_or_default(
954 environ_cp, 'CUDNN_INSTALL_PATH', ask_cudnn_path, default_cudnn_path)
955
956 # Result returned from "read" will be used unexpanded. That make "~"
957 # unusable. Going through one more level of expansion to handle that.
958 cudnn_install_path = os.path.realpath(
959 os.path.expanduser(cudnn_install_path))
Martin Wicked57572e2017-09-02 19:21:45 -0700960 if is_windows() or is_cygwin():
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700961 cudnn_install_path = cygpath(cudnn_install_path)
962
963 if is_windows():
964 cuda_dnn_lib_path = 'lib/x64/cudnn.lib'
965 cuda_dnn_lib_alt_path = 'lib/x64/cudnn.lib'
966 elif is_linux():
967 cuda_dnn_lib_path = 'lib64/libcudnn.so.%s' % tf_cudnn_version
968 cuda_dnn_lib_alt_path = 'libcudnn.so.%s' % tf_cudnn_version
969 elif is_macos():
970 cuda_dnn_lib_path = 'lib/libcudnn.%s.dylib' % tf_cudnn_version
971 cuda_dnn_lib_alt_path = 'libcudnn.%s.dylib' % tf_cudnn_version
972
973 cuda_dnn_lib_path_full = os.path.join(cudnn_install_path, cuda_dnn_lib_path)
974 cuda_dnn_lib_alt_path_full = os.path.join(cudnn_install_path,
975 cuda_dnn_lib_alt_path)
976 if os.path.exists(cuda_dnn_lib_path_full) or os.path.exists(
977 cuda_dnn_lib_alt_path_full):
978 break
979
980 # Try another alternative for Linux
981 if is_linux():
Jonathan Hseu008910f2017-08-25 14:01:05 -0700982 ldconfig_bin = which('ldconfig') or '/sbin/ldconfig'
983 cudnn_path_from_ldconfig = run_shell([ldconfig_bin, '-p'])
984 cudnn_path_from_ldconfig = re.search('.*libcudnn.so .* => (.*)',
A. Unique TensorFlowere7223582017-09-06 17:57:04 -0700985 cudnn_path_from_ldconfig)
986 if cudnn_path_from_ldconfig:
987 cudnn_path_from_ldconfig = cudnn_path_from_ldconfig.group(1)
A. Unique TensorFlower5001ac02019-04-03 11:59:08 -0700988 if os.path.exists('%s.%s' %
989 (cudnn_path_from_ldconfig, tf_cudnn_version)):
A. Unique TensorFlowere7223582017-09-06 17:57:04 -0700990 cudnn_install_path = os.path.dirname(cudnn_path_from_ldconfig)
991 break
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700992
993 # Reset and Retry
994 print(
995 'Invalid path to cuDNN %s toolkit. None of the following files can be '
996 'found:' % tf_cudnn_version)
997 print(cuda_dnn_lib_path_full)
998 print(cuda_dnn_lib_alt_path_full)
999 if is_linux():
1000 print('%s.%s' % (cudnn_path_from_ldconfig, tf_cudnn_version))
1001
1002 environ_cp['TF_CUDNN_VERSION'] = ''
Austin Andersonf9a88f82017-12-13 11:49:40 -08001003 else:
1004 raise UserInputError('Invalid TF_CUDNN setting was provided %d '
1005 'times in a row. Assuming to be a scripting mistake.' %
1006 _DEFAULT_PROMPT_ASK_ATTEMPTS)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001007
1008 # Set CUDNN_INSTALL_PATH and TF_CUDNN_VERSION
1009 environ_cp['CUDNN_INSTALL_PATH'] = cudnn_install_path
1010 write_action_env_to_bazelrc('CUDNN_INSTALL_PATH', cudnn_install_path)
1011 environ_cp['TF_CUDNN_VERSION'] = tf_cudnn_version
1012 write_action_env_to_bazelrc('TF_CUDNN_VERSION', tf_cudnn_version)
1013
1014
Mingxing Tan1e7b0e42018-06-28 19:13:20 -07001015def is_cuda_compatible(lib, cuda_ver, cudnn_ver):
1016 """Check compatibility between given library and cudnn/cudart libraries."""
1017 ldd_bin = which('ldd') or '/usr/bin/ldd'
1018 ldd_out = run_shell([ldd_bin, lib], True)
1019 ldd_out = ldd_out.split(os.linesep)
1020 cudnn_pattern = re.compile('.*libcudnn.so\\.?(.*) =>.*$')
1021 cuda_pattern = re.compile('.*libcudart.so\\.?(.*) =>.*$')
1022 cudnn = None
1023 cudart = None
1024 cudnn_ok = True # assume no cudnn dependency by default
1025 cuda_ok = True # assume no cuda dependency by default
1026 for line in ldd_out:
1027 if 'libcudnn.so' in line:
1028 cudnn = cudnn_pattern.search(line)
1029 cudnn_ok = False
1030 elif 'libcudart.so' in line:
1031 cudart = cuda_pattern.search(line)
1032 cuda_ok = False
1033 if cudnn and len(cudnn.group(1)):
1034 cudnn = convert_version_to_int(cudnn.group(1))
1035 if cudart and len(cudart.group(1)):
1036 cudart = convert_version_to_int(cudart.group(1))
1037 if cudnn is not None:
1038 cudnn_ok = (cudnn == cudnn_ver)
1039 if cudart is not None:
1040 cuda_ok = (cudart == cuda_ver)
1041 return cudnn_ok and cuda_ok
1042
1043
Guangda Lai76f69382018-01-25 23:59:19 -08001044def set_tf_tensorrt_install_path(environ_cp):
1045 """Set TENSORRT_INSTALL_PATH and TF_TENSORRT_VERSION.
1046
1047 Adapted from code contributed by Sami Kama (https://github.com/samikama).
1048
1049 Args:
1050 environ_cp: copy of the os.environ.
1051
1052 Raises:
1053 ValueError: if this method was called under non-Linux platform.
1054 UserInputError: if user has provided invalid input multiple times.
1055 """
1056 if not is_linux():
1057 raise ValueError('Currently TensorRT is only supported on Linux platform.')
1058
1059 # Ask user whether to add TensorRT support.
Mingxing Tan1e7b0e42018-06-28 19:13:20 -07001060 if str(int(get_var(environ_cp, 'TF_NEED_TENSORRT', 'TensorRT',
1061 False))) != '1':
Guangda Lai76f69382018-01-25 23:59:19 -08001062 return
1063
1064 for _ in range(_DEFAULT_PROMPT_ASK_ATTEMPTS):
1065 ask_tensorrt_path = (r'Please specify the location where TensorRT is '
1066 'installed. [Default is %s]:') % (
1067 _DEFAULT_TENSORRT_PATH_LINUX)
1068 trt_install_path = get_from_env_or_user_or_default(
1069 environ_cp, 'TENSORRT_INSTALL_PATH', ask_tensorrt_path,
1070 _DEFAULT_TENSORRT_PATH_LINUX)
1071
1072 # Result returned from "read" will be used unexpanded. That make "~"
1073 # unusable. Going through one more level of expansion to handle that.
Mingxing Tan1e7b0e42018-06-28 19:13:20 -07001074 trt_install_path = os.path.realpath(os.path.expanduser(trt_install_path))
Guangda Lai76f69382018-01-25 23:59:19 -08001075
1076 def find_libs(search_path):
1077 """Search for libnvinfer.so in "search_path"."""
1078 fl = set()
1079 if os.path.exists(search_path) and os.path.isdir(search_path):
Mingxing Tan1e7b0e42018-06-28 19:13:20 -07001080 fl.update([
1081 os.path.realpath(os.path.join(search_path, x))
1082 for x in os.listdir(search_path)
1083 if 'libnvinfer.so' in x
1084 ])
Guangda Lai76f69382018-01-25 23:59:19 -08001085 return fl
1086
1087 possible_files = find_libs(trt_install_path)
1088 possible_files.update(find_libs(os.path.join(trt_install_path, 'lib')))
1089 possible_files.update(find_libs(os.path.join(trt_install_path, 'lib64')))
Guangda Lai76f69382018-01-25 23:59:19 -08001090 cuda_ver = convert_version_to_int(environ_cp['TF_CUDA_VERSION'])
1091 cudnn_ver = convert_version_to_int(environ_cp['TF_CUDNN_VERSION'])
1092 nvinfer_pattern = re.compile('.*libnvinfer.so.?(.*)$')
1093 highest_ver = [0, None, None]
1094
1095 for lib_file in possible_files:
Mingxing Tan1e7b0e42018-06-28 19:13:20 -07001096 if is_cuda_compatible(lib_file, cuda_ver, cudnn_ver):
Jacques Pienaar2d0531d2018-03-21 12:07:51 -07001097 matches = nvinfer_pattern.search(lib_file)
TensorFlower Gardener61a87202018-10-01 12:25:39 -07001098 if not matches.groups():
Jacques Pienaar2d0531d2018-03-21 12:07:51 -07001099 continue
1100 ver_str = matches.group(1)
Guangda Lai76f69382018-01-25 23:59:19 -08001101 ver = convert_version_to_int(ver_str) if len(ver_str) else 0
1102 if ver > highest_ver[0]:
1103 highest_ver = [ver, ver_str, lib_file]
1104 if highest_ver[1] is not None:
1105 trt_install_path = os.path.dirname(highest_ver[2])
1106 tf_tensorrt_version = highest_ver[1]
1107 break
1108
1109 # Try another alternative from ldconfig.
1110 ldconfig_bin = which('ldconfig') or '/sbin/ldconfig'
1111 ldconfig_output = run_shell([ldconfig_bin, '-p'])
Mingxing Tan1e7b0e42018-06-28 19:13:20 -07001112 search_result = re.search('.*libnvinfer.so\\.?([0-9.]*).* => (.*)',
1113 ldconfig_output)
Guangda Lai76f69382018-01-25 23:59:19 -08001114 if search_result:
1115 libnvinfer_path_from_ldconfig = search_result.group(2)
1116 if os.path.exists(libnvinfer_path_from_ldconfig):
Mingxing Tan1e7b0e42018-06-28 19:13:20 -07001117 if is_cuda_compatible(libnvinfer_path_from_ldconfig, cuda_ver,
1118 cudnn_ver):
Guangda Lai76f69382018-01-25 23:59:19 -08001119 trt_install_path = os.path.dirname(libnvinfer_path_from_ldconfig)
1120 tf_tensorrt_version = search_result.group(1)
1121 break
1122
1123 # Reset and Retry
Yifei Fengdce9a492018-02-22 14:24:57 -08001124 if possible_files:
1125 print('TensorRT libraries found in one the following directories',
1126 'are not compatible with selected cuda and cudnn installations')
1127 print(trt_install_path)
1128 print(os.path.join(trt_install_path, 'lib'))
1129 print(os.path.join(trt_install_path, 'lib64'))
1130 if search_result:
1131 print(libnvinfer_path_from_ldconfig)
1132 else:
1133 print(
1134 'Invalid path to TensorRT. None of the following files can be found:')
1135 print(trt_install_path)
1136 print(os.path.join(trt_install_path, 'lib'))
1137 print(os.path.join(trt_install_path, 'lib64'))
1138 if search_result:
1139 print(libnvinfer_path_from_ldconfig)
Guangda Lai76f69382018-01-25 23:59:19 -08001140
1141 else:
1142 raise UserInputError('Invalid TF_TENSORRT setting was provided %d '
1143 'times in a row. Assuming to be a scripting mistake.' %
1144 _DEFAULT_PROMPT_ASK_ATTEMPTS)
1145
1146 # Set TENSORRT_INSTALL_PATH and TF_TENSORRT_VERSION
1147 environ_cp['TENSORRT_INSTALL_PATH'] = trt_install_path
1148 write_action_env_to_bazelrc('TENSORRT_INSTALL_PATH', trt_install_path)
1149 environ_cp['TF_TENSORRT_VERSION'] = tf_tensorrt_version
1150 write_action_env_to_bazelrc('TF_TENSORRT_VERSION', tf_tensorrt_version)
1151
1152
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001153def set_tf_nccl_install_path(environ_cp):
Jason Furmanek7c234152018-09-26 04:44:12 +00001154 """Set NCCL_INSTALL_PATH, NCCL_HDR_PATH and TF_NCCL_VERSION.
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001155
1156 Args:
1157 environ_cp: copy of the os.environ.
1158
1159 Raises:
1160 ValueError: if this method was called under non-Linux platform.
1161 UserInputError: if user has provided invalid input multiple times.
1162 """
1163 if not is_linux():
1164 raise ValueError('Currently NCCL is only supported on Linux platforms.')
1165
1166 ask_nccl_version = (
A. Unique TensorFlower53faa312018-10-05 08:46:54 -07001167 'Please specify the locally installed NCCL version you want to use. '
1168 '[Default is to use https://github.com/nvidia/nccl]: ')
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001169
1170 for _ in range(_DEFAULT_PROMPT_ASK_ATTEMPTS):
A. Unique TensorFlower5001ac02019-04-03 11:59:08 -07001171 tf_nccl_version = get_from_env_or_user_or_default(environ_cp,
1172 'TF_NCCL_VERSION',
1173 ask_nccl_version, '')
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001174
A. Unique TensorFlower53faa312018-10-05 08:46:54 -07001175 if not tf_nccl_version:
1176 break # No need to get install path, building the open source code.
1177
1178 tf_nccl_version = reformat_version_sequence(str(tf_nccl_version), 1)
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001179
Jason Furmanek7c234152018-09-26 04:44:12 +00001180 # Look with ldconfig first if we can find the library in paths
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001181 # like /usr/lib/x86_64-linux-gnu and the header file in the corresponding
1182 # include directory. This is where the NCCL .deb packages install them.
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001183
Jason Furmanek7c234152018-09-26 04:44:12 +00001184 # First check to see if NCCL is in the ldconfig.
1185 # If its found, use that location.
1186 if is_linux():
1187 ldconfig_bin = which('ldconfig') or '/sbin/ldconfig'
1188 nccl2_path_from_ldconfig = run_shell([ldconfig_bin, '-p'])
1189 nccl2_path_from_ldconfig = re.search('.*libnccl.so .* => (.*)',
1190 nccl2_path_from_ldconfig)
1191 if nccl2_path_from_ldconfig:
1192 nccl2_path_from_ldconfig = nccl2_path_from_ldconfig.group(1)
1193 if os.path.exists('%s.%s' % (nccl2_path_from_ldconfig, tf_nccl_version)):
1194 nccl_install_path = os.path.dirname(nccl2_path_from_ldconfig)
1195 print('NCCL libraries found in ' + nccl2_path_from_ldconfig)
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001196
Jason Furmanek7c234152018-09-26 04:44:12 +00001197 # Check if this is the main system lib location
1198 if re.search('.*linux-gnu', nccl_install_path):
TensorFlower Gardenerea5c5292018-10-01 17:28:26 -07001199 trunc_nccl_install_path = '/usr'
1200 print('This looks like a system path.')
Jason Furmanek7c234152018-09-26 04:44:12 +00001201 else:
TensorFlower Gardenerea5c5292018-10-01 17:28:26 -07001202 trunc_nccl_install_path = nccl_install_path + '/..'
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001203
Jason Furmanek7c234152018-09-26 04:44:12 +00001204 # Look for header
TensorFlower Gardenerea5c5292018-10-01 17:28:26 -07001205 nccl_hdr_path = trunc_nccl_install_path + '/include'
1206 print('Assuming NCCL header path is ' + nccl_hdr_path)
1207 if os.path.exists(nccl_hdr_path + '/nccl.h'):
Jason Furmanek7c234152018-09-26 04:44:12 +00001208 # Set NCCL_INSTALL_PATH
1209 environ_cp['NCCL_INSTALL_PATH'] = nccl_install_path
1210 write_action_env_to_bazelrc('NCCL_INSTALL_PATH', nccl_install_path)
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001211
Jason Furmanek7c234152018-09-26 04:44:12 +00001212 # Set NCCL_HDR_PATH
1213 environ_cp['NCCL_HDR_PATH'] = nccl_hdr_path
1214 write_action_env_to_bazelrc('NCCL_HDR_PATH', nccl_hdr_path)
1215 break
1216 else:
TensorFlower Gardenerea5c5292018-10-01 17:28:26 -07001217 print(
1218 'The header for NCCL2 cannot be found. Please install the libnccl-dev package.'
1219 )
Jason Furmanek7c234152018-09-26 04:44:12 +00001220 else:
TensorFlower Gardenerea5c5292018-10-01 17:28:26 -07001221 print('NCCL2 is listed by ldconfig but the library is not found. '
1222 'Your ldconfig is out of date. Please run sudo ldconfig.')
Jason Furmanek7c234152018-09-26 04:44:12 +00001223 else:
1224 # NCCL is not found in ldconfig. Ask the user for the location.
1225 default_nccl_path = environ_cp.get('CUDA_TOOLKIT_PATH')
TensorFlower Gardenerea5c5292018-10-01 17:28:26 -07001226 ask_nccl_path = (
1227 r'Please specify the location where NCCL %s library is '
1228 'installed. Refer to README.md for more details. [Default '
1229 'is %s]:') % (tf_nccl_version, default_nccl_path)
Jason Furmanek7c234152018-09-26 04:44:12 +00001230 nccl_install_path = get_from_env_or_user_or_default(
TensorFlower Gardenerea5c5292018-10-01 17:28:26 -07001231 environ_cp, 'NCCL_INSTALL_PATH', ask_nccl_path, default_nccl_path)
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001232
Jason Furmanek7c234152018-09-26 04:44:12 +00001233 # Result returned from "read" will be used unexpanded. That make "~"
1234 # unusable. Going through one more level of expansion to handle that.
TensorFlower Gardenerea5c5292018-10-01 17:28:26 -07001235 nccl_install_path = os.path.realpath(
1236 os.path.expanduser(nccl_install_path))
Jason Furmanek7c234152018-09-26 04:44:12 +00001237 if is_windows() or is_cygwin():
1238 nccl_install_path = cygpath(nccl_install_path)
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001239
Guangda Lai62ebf622018-10-23 07:44:13 -07001240 nccl_lib_path = ''
Jason Furmanek7c234152018-09-26 04:44:12 +00001241 if is_windows():
1242 nccl_lib_path = 'lib/x64/nccl.lib'
1243 elif is_linux():
1244 nccl_lib_filename = 'libnccl.so.%s' % tf_nccl_version
1245 nccl_lpath = '%s/lib/%s' % (nccl_install_path, nccl_lib_filename)
1246 if not os.path.exists(nccl_lpath):
1247 for relative_path in NCCL_LIB_PATHS:
TensorFlower Gardenerea5c5292018-10-01 17:28:26 -07001248 path = '%s/%s%s' % (nccl_install_path, relative_path,
1249 nccl_lib_filename)
Jason Furmanek7c234152018-09-26 04:44:12 +00001250 if os.path.exists(path):
TensorFlower Gardenerea5c5292018-10-01 17:28:26 -07001251 print('NCCL found at ' + path)
Jason Furmanek7c234152018-09-26 04:44:12 +00001252 nccl_lib_path = path
1253 break
1254 else:
1255 nccl_lib_path = nccl_lpath
1256 elif is_macos():
1257 nccl_lib_path = 'lib/libnccl.%s.dylib' % tf_nccl_version
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001258
Jason Furmanek7c234152018-09-26 04:44:12 +00001259 nccl_lib_path = os.path.join(nccl_install_path, nccl_lib_path)
TensorFlower Gardenerea5c5292018-10-01 17:28:26 -07001260 nccl_hdr_path = os.path.join(
1261 os.path.dirname(nccl_lib_path), '../include/nccl.h')
1262 print('Assuming NCCL header path is ' + nccl_hdr_path)
Jason Furmanek7c234152018-09-26 04:44:12 +00001263 if os.path.exists(nccl_lib_path) and os.path.exists(nccl_hdr_path):
1264 # Set NCCL_INSTALL_PATH
1265 environ_cp['NCCL_INSTALL_PATH'] = os.path.dirname(nccl_lib_path)
TensorFlower Gardenerea5c5292018-10-01 17:28:26 -07001266 write_action_env_to_bazelrc('NCCL_INSTALL_PATH',
1267 os.path.dirname(nccl_lib_path))
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001268
Jason Furmanek7c234152018-09-26 04:44:12 +00001269 # Set NCCL_HDR_PATH
1270 environ_cp['NCCL_HDR_PATH'] = os.path.dirname(nccl_hdr_path)
TensorFlower Gardenerea5c5292018-10-01 17:28:26 -07001271 write_action_env_to_bazelrc('NCCL_HDR_PATH',
1272 os.path.dirname(nccl_hdr_path))
Jason Furmanek7c234152018-09-26 04:44:12 +00001273 break
1274
1275 # Reset and Retry
TensorFlower Gardenerea5c5292018-10-01 17:28:26 -07001276 print(
1277 'Invalid path to NCCL %s toolkit, %s or %s not found. Please use the '
A. Unique TensorFlowered297342019-03-15 11:25:28 -07001278 'O/S agnostic package of NCCL 2' %
1279 (tf_nccl_version, nccl_lib_path, nccl_hdr_path))
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001280
Jason Furmanek7c234152018-09-26 04:44:12 +00001281 environ_cp['TF_NCCL_VERSION'] = ''
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001282 else:
1283 raise UserInputError('Invalid TF_NCCL setting was provided %d '
1284 'times in a row. Assuming to be a scripting mistake.' %
1285 _DEFAULT_PROMPT_ASK_ATTEMPTS)
1286
1287 # Set TF_NCCL_VERSION
1288 environ_cp['TF_NCCL_VERSION'] = tf_nccl_version
1289 write_action_env_to_bazelrc('TF_NCCL_VERSION', tf_nccl_version)
1290
TensorFlower Gardenerabb763b2019-02-06 16:23:03 -08001291
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001292def get_native_cuda_compute_capabilities(environ_cp):
1293 """Get native cuda compute capabilities.
1294
1295 Args:
1296 environ_cp: copy of the os.environ.
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -07001297
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001298 Returns:
1299 string of native cuda compute capabilities, separated by comma.
1300 """
1301 device_query_bin = os.path.join(
1302 environ_cp.get('CUDA_TOOLKIT_PATH'), 'extras/demo_suite/deviceQuery')
Jonathan Hseu008910f2017-08-25 14:01:05 -07001303 if os.path.isfile(device_query_bin) and os.access(device_query_bin, os.X_OK):
1304 try:
1305 output = run_shell(device_query_bin).split('\n')
1306 pattern = re.compile('[0-9]*\\.[0-9]*')
1307 output = [pattern.search(x) for x in output if 'Capability' in x]
1308 output = ','.join(x.group() for x in output if x is not None)
1309 except subprocess.CalledProcessError:
1310 output = ''
1311 else:
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001312 output = ''
1313 return output
1314
1315
1316def set_tf_cuda_compute_capabilities(environ_cp):
1317 """Set TF_CUDA_COMPUTE_CAPABILITIES."""
1318 while True:
1319 native_cuda_compute_capabilities = get_native_cuda_compute_capabilities(
1320 environ_cp)
1321 if not native_cuda_compute_capabilities:
1322 default_cuda_compute_capabilities = _DEFAULT_CUDA_COMPUTE_CAPABILITIES
1323 else:
1324 default_cuda_compute_capabilities = native_cuda_compute_capabilities
1325
1326 ask_cuda_compute_capabilities = (
1327 'Please specify a list of comma-separated '
P Sudeepam52093562019-02-17 17:34:01 +05301328 'CUDA compute capabilities you want to '
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001329 'build with.\nYou can find the compute '
1330 'capability of your device at: '
1331 'https://developer.nvidia.com/cuda-gpus.\nPlease'
1332 ' note that each additional compute '
1333 'capability significantly increases your '
P Sudeepam52093562019-02-17 17:34:01 +05301334 'build time and binary size, and that '
1335 'TensorFlow only supports compute '
P Sudeepam765ceda2019-02-17 17:39:08 +05301336 'capabilities >= 3.5 [Default is: %s]: ' %
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001337 default_cuda_compute_capabilities)
1338 tf_cuda_compute_capabilities = get_from_env_or_user_or_default(
1339 environ_cp, 'TF_CUDA_COMPUTE_CAPABILITIES',
1340 ask_cuda_compute_capabilities, default_cuda_compute_capabilities)
1341 # Check whether all capabilities from the input is valid
1342 all_valid = True
Maciejd0f5bc12018-04-30 22:30:58 -05001343 # Remove all whitespace characters before splitting the string
Michael Case51053502018-06-05 17:47:19 -07001344 # that users may insert by accident, as this will result in error
Maciejd0f5bc12018-04-30 22:30:58 -05001345 tf_cuda_compute_capabilities = ''.join(tf_cuda_compute_capabilities.split())
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001346 for compute_capability in tf_cuda_compute_capabilities.split(','):
Andrew Harp6e3e7d12017-08-21 12:10:44 -07001347 m = re.match('[0-9]+.[0-9]+', compute_capability)
1348 if not m:
Austin Anderson32202dc2019-02-19 10:46:27 -08001349 print('Invalid compute capability: %s' % compute_capability)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001350 all_valid = False
Andrew Harp6e3e7d12017-08-21 12:10:44 -07001351 else:
P Sudeepam52093562019-02-17 17:34:01 +05301352 ver = float(m.group(0))
A. Unique TensorFlower8dc2d0e2019-03-12 01:41:05 -07001353 if ver < 3.0:
1354 print('ERROR: TensorFlow only supports CUDA compute capabilities 3.0 '
Austin Anderson32202dc2019-02-19 10:46:27 -08001355 'and higher. Please re-specify the list of compute '
1356 'capabilities excluding version %s.' % ver)
Andrew Harp6e3e7d12017-08-21 12:10:44 -07001357 all_valid = False
A. Unique TensorFlower8dc2d0e2019-03-12 01:41:05 -07001358 if ver < 3.5:
1359 print('WARNING: XLA does not support CUDA compute capabilities '
1360 'lower than 3.5. Disable XLA when running on older GPUs.')
P Sudeepam765ceda2019-02-17 17:39:08 +05301361
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001362 if all_valid:
1363 break
1364
1365 # Reset and Retry
1366 environ_cp['TF_CUDA_COMPUTE_CAPABILITIES'] = ''
1367
1368 # Set TF_CUDA_COMPUTE_CAPABILITIES
1369 environ_cp['TF_CUDA_COMPUTE_CAPABILITIES'] = tf_cuda_compute_capabilities
1370 write_action_env_to_bazelrc('TF_CUDA_COMPUTE_CAPABILITIES',
1371 tf_cuda_compute_capabilities)
1372
1373
1374def set_other_cuda_vars(environ_cp):
1375 """Set other CUDA related variables."""
A. Unique TensorFlowerab391982018-07-11 04:52:49 -07001376 # If CUDA is enabled, always use GPU during build and test.
1377 if environ_cp.get('TF_CUDA_CLANG') == '1':
1378 write_to_bazelrc('build --config=cuda_clang')
1379 write_to_bazelrc('test --config=cuda_clang')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001380 else:
A. Unique TensorFlowerab391982018-07-11 04:52:49 -07001381 write_to_bazelrc('build --config=cuda')
1382 write_to_bazelrc('test --config=cuda')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001383
1384
1385def set_host_cxx_compiler(environ_cp):
1386 """Set HOST_CXX_COMPILER."""
Jonathan Hseu008910f2017-08-25 14:01:05 -07001387 default_cxx_host_compiler = which('g++') or ''
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001388
Austin Anderson6afface2017-12-05 11:59:17 -08001389 host_cxx_compiler = prompt_loop_or_load_from_env(
1390 environ_cp,
1391 var_name='HOST_CXX_COMPILER',
1392 var_default=default_cxx_host_compiler,
1393 ask_for_var=('Please specify which C++ compiler should be used as the '
1394 'host C++ compiler.'),
1395 check_success=os.path.exists,
1396 error_msg='Invalid C++ compiler path. %s cannot be found.',
1397 )
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001398
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001399 write_action_env_to_bazelrc('HOST_CXX_COMPILER', host_cxx_compiler)
1400
1401
1402def set_host_c_compiler(environ_cp):
1403 """Set HOST_C_COMPILER."""
Jonathan Hseu008910f2017-08-25 14:01:05 -07001404 default_c_host_compiler = which('gcc') or ''
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001405
Austin Anderson6afface2017-12-05 11:59:17 -08001406 host_c_compiler = prompt_loop_or_load_from_env(
1407 environ_cp,
1408 var_name='HOST_C_COMPILER',
1409 var_default=default_c_host_compiler,
Shanqing Cai71445712018-03-12 19:33:52 -07001410 ask_for_var=('Please specify which C compiler should be used as the host '
Austin Anderson6afface2017-12-05 11:59:17 -08001411 'C compiler.'),
1412 check_success=os.path.exists,
1413 error_msg='Invalid C compiler path. %s cannot be found.',
1414 )
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001415
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001416 write_action_env_to_bazelrc('HOST_C_COMPILER', host_c_compiler)
1417
1418
1419def set_computecpp_toolkit_path(environ_cp):
1420 """Set COMPUTECPP_TOOLKIT_PATH."""
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001421
Austin Anderson6afface2017-12-05 11:59:17 -08001422 def toolkit_exists(toolkit_path):
1423 """Check if a computecpp toolkit path is valid."""
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001424 if is_linux():
1425 sycl_rt_lib_path = 'lib/libComputeCpp.so'
1426 else:
1427 sycl_rt_lib_path = ''
1428
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -07001429 sycl_rt_lib_path_full = os.path.join(toolkit_path, sycl_rt_lib_path)
Austin Anderson6afface2017-12-05 11:59:17 -08001430 exists = os.path.exists(sycl_rt_lib_path_full)
1431 if not exists:
1432 print('Invalid SYCL %s library path. %s cannot be found' %
1433 (_TF_OPENCL_VERSION, sycl_rt_lib_path_full))
1434 return exists
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001435
Austin Anderson6afface2017-12-05 11:59:17 -08001436 computecpp_toolkit_path = prompt_loop_or_load_from_env(
1437 environ_cp,
1438 var_name='COMPUTECPP_TOOLKIT_PATH',
1439 var_default=_DEFAULT_COMPUTECPP_TOOLKIT_PATH,
1440 ask_for_var=(
1441 'Please specify the location where ComputeCpp for SYCL %s is '
1442 'installed.' % _TF_OPENCL_VERSION),
1443 check_success=toolkit_exists,
1444 error_msg='Invalid SYCL compiler path. %s cannot be found.',
1445 suppress_default_error=True)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001446
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001447 write_action_env_to_bazelrc('COMPUTECPP_TOOLKIT_PATH',
1448 computecpp_toolkit_path)
1449
Michael Cased31531a2018-01-05 14:09:41 -08001450
Dandelion Man?90e42f32017-12-15 18:15:07 -08001451def set_trisycl_include_dir(environ_cp):
Michael Cased31531a2018-01-05 14:09:41 -08001452 """Set TRISYCL_INCLUDE_DIR."""
Frank Chenc4ef9272018-01-10 11:36:52 -08001453
Dandelion Man?90e42f32017-12-15 18:15:07 -08001454 ask_trisycl_include_dir = ('Please specify the location of the triSYCL '
1455 'include directory. (Use --config=sycl_trisycl '
1456 'when building with Bazel) '
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -07001457 '[Default is %s]: ') % (
1458 _DEFAULT_TRISYCL_INCLUDE_DIR)
Frank Chenc4ef9272018-01-10 11:36:52 -08001459
Dandelion Man?90e42f32017-12-15 18:15:07 -08001460 while True:
1461 trisycl_include_dir = get_from_env_or_user_or_default(
Michael Cased31531a2018-01-05 14:09:41 -08001462 environ_cp, 'TRISYCL_INCLUDE_DIR', ask_trisycl_include_dir,
1463 _DEFAULT_TRISYCL_INCLUDE_DIR)
Dandelion Man?90e42f32017-12-15 18:15:07 -08001464 if os.path.exists(trisycl_include_dir):
1465 break
1466
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -07001467 print('Invalid triSYCL include directory, %s cannot be found' %
1468 (trisycl_include_dir))
Dandelion Man?90e42f32017-12-15 18:15:07 -08001469
1470 # Set TRISYCL_INCLUDE_DIR
1471 environ_cp['TRISYCL_INCLUDE_DIR'] = trisycl_include_dir
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -07001472 write_action_env_to_bazelrc('TRISYCL_INCLUDE_DIR', trisycl_include_dir)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001473
Yifei Fengb1d8c592017-11-22 13:42:21 -08001474
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001475def set_mpi_home(environ_cp):
1476 """Set MPI_HOME."""
Austin Anderson6afface2017-12-05 11:59:17 -08001477
Jonathan Hseu008910f2017-08-25 14:01:05 -07001478 default_mpi_home = which('mpirun') or which('mpiexec') or ''
1479 default_mpi_home = os.path.dirname(os.path.dirname(default_mpi_home))
1480
Austin Anderson6afface2017-12-05 11:59:17 -08001481 def valid_mpi_path(mpi_home):
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -07001482 exists = (
1483 os.path.exists(os.path.join(mpi_home, 'include')) and
TensorFlower Gardenerf7c861f2018-11-01 11:29:40 -07001484 (os.path.exists(os.path.join(mpi_home, 'lib')) or
1485 os.path.exists(os.path.join(mpi_home, 'lib64')) or
1486 os.path.exists(os.path.join(mpi_home, 'lib32'))))
Austin Anderson6afface2017-12-05 11:59:17 -08001487 if not exists:
TensorFlower Gardenerf7c861f2018-11-01 11:29:40 -07001488 print(
1489 'Invalid path to the MPI Toolkit. %s or %s or %s or %s cannot be found'
1490 % (os.path.join(mpi_home, 'include'),
Christian Gollba95d092018-10-04 17:06:23 +02001491 os.path.exists(os.path.join(mpi_home, 'lib')),
1492 os.path.exists(os.path.join(mpi_home, 'lib64')),
1493 os.path.exists(os.path.join(mpi_home, 'lib32'))))
Austin Anderson6afface2017-12-05 11:59:17 -08001494 return exists
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001495
Austin Anderson6afface2017-12-05 11:59:17 -08001496 _ = prompt_loop_or_load_from_env(
1497 environ_cp,
1498 var_name='MPI_HOME',
1499 var_default=default_mpi_home,
1500 ask_for_var='Please specify the MPI toolkit folder.',
1501 check_success=valid_mpi_path,
1502 error_msg='',
1503 suppress_default_error=True)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001504
1505
1506def set_other_mpi_vars(environ_cp):
1507 """Set other MPI related variables."""
1508 # Link the MPI header files
1509 mpi_home = environ_cp.get('MPI_HOME')
1510 symlink_force('%s/include/mpi.h' % mpi_home, 'third_party/mpi/mpi.h')
1511
1512 # Determine if we use OpenMPI or MVAPICH, these require different header files
1513 # to be included here to make bazel dependency checker happy
1514 if os.path.exists(os.path.join(mpi_home, 'include/mpi_portable_platform.h')):
1515 symlink_force(
1516 os.path.join(mpi_home, 'include/mpi_portable_platform.h'),
1517 'third_party/mpi/mpi_portable_platform.h')
1518 # TODO(gunan): avoid editing files in configure
1519 sed_in_place('third_party/mpi/mpi.bzl', 'MPI_LIB_IS_OPENMPI=False',
1520 'MPI_LIB_IS_OPENMPI=True')
1521 else:
1522 # MVAPICH / MPICH
1523 symlink_force(
1524 os.path.join(mpi_home, 'include/mpio.h'), 'third_party/mpi/mpio.h')
1525 symlink_force(
1526 os.path.join(mpi_home, 'include/mpicxx.h'), 'third_party/mpi/mpicxx.h')
1527 # TODO(gunan): avoid editing files in configure
1528 sed_in_place('third_party/mpi/mpi.bzl', 'MPI_LIB_IS_OPENMPI=True',
1529 'MPI_LIB_IS_OPENMPI=False')
1530
1531 if os.path.exists(os.path.join(mpi_home, 'lib/libmpi.so')):
1532 symlink_force(
1533 os.path.join(mpi_home, 'lib/libmpi.so'), 'third_party/mpi/libmpi.so')
Christian Gollba95d092018-10-04 17:06:23 +02001534 elif os.path.exists(os.path.join(mpi_home, 'lib64/libmpi.so')):
1535 symlink_force(
1536 os.path.join(mpi_home, 'lib64/libmpi.so'), 'third_party/mpi/libmpi.so')
1537 elif os.path.exists(os.path.join(mpi_home, 'lib32/libmpi.so')):
1538 symlink_force(
1539 os.path.join(mpi_home, 'lib32/libmpi.so'), 'third_party/mpi/libmpi.so')
1540
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001541 else:
TensorFlower Gardenerf7c861f2018-11-01 11:29:40 -07001542 raise ValueError(
1543 'Cannot find the MPI library file in %s/lib or %s/lib64 or %s/lib32' %
Mihai Maruseac91ebeec2019-01-29 17:07:38 -08001544 (mpi_home, mpi_home, mpi_home))
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001545
A. Unique TensorFlowered297342019-03-15 11:25:28 -07001546
A. Unique TensorFlowere9797fd2019-03-22 11:02:40 -07001547def system_specific_test_config(env):
A. Unique TensorFlower7bd86372019-03-21 15:19:30 -07001548 """Add default build and test flags required for TF tests to bazelrc."""
Gunhan Gulsoyfff66962019-02-20 15:28:43 -08001549 write_to_bazelrc('test --flaky_test_attempts=3')
1550 write_to_bazelrc('test --test_size_filters=small,medium')
1551 write_to_bazelrc(
1552 'test --test_tag_filters=-benchmark-test,-no_oss,-oss_serial')
1553 write_to_bazelrc('test --build_tag_filters=-benchmark-test,-no_oss')
1554 if is_windows():
Guangda Laibcd701a2019-03-12 21:04:51 -07001555 if env.get('TF_NEED_CUDA', None) == '1':
Gunhan Gulsoyfff66962019-02-20 15:28:43 -08001556 write_to_bazelrc(
1557 'test --test_tag_filters=-no_windows,-no_windows_gpu,-no_gpu')
1558 write_to_bazelrc(
1559 'test --build_tag_filters=-no_windows,-no_windows_gpu,-no_gpu')
1560 else:
1561 write_to_bazelrc('test --test_tag_filters=-no_windows,-gpu')
1562 write_to_bazelrc('test --build_tag_filters=-no_windows,-gpu')
1563 elif is_macos():
1564 write_to_bazelrc('test --test_tag_filters=-gpu,-nomac,-no_mac')
1565 write_to_bazelrc('test --build_tag_filters=-gpu,-nomac,-no_mac')
1566 elif is_linux():
Guangda Laibcd701a2019-03-12 21:04:51 -07001567 if env.get('TF_NEED_CUDA', None) == '1':
Gunhan Gulsoyfff66962019-02-20 15:28:43 -08001568 write_to_bazelrc('test --test_tag_filters=-no_gpu')
1569 write_to_bazelrc('test --build_tag_filters=-no_gpu')
1570 write_to_bazelrc('test --test_env=LD_LIBRARY_PATH')
1571 else:
1572 write_to_bazelrc('test --test_tag_filters=-gpu')
1573 write_to_bazelrc('test --build_tag_filters=-gpu')
1574
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001575
Yifei Feng5198cb82018-08-17 13:53:06 -07001576def set_system_libs_flag(environ_cp):
1577 syslibs = environ_cp.get('TF_SYSTEM_LIBS', '')
TensorFlower Gardener61a87202018-10-01 12:25:39 -07001578 if syslibs:
Jason Zaman5fc39bd2018-09-16 01:38:55 +08001579 if ',' in syslibs:
1580 syslibs = ','.join(sorted(syslibs.split(',')))
1581 else:
1582 syslibs = ','.join(sorted(syslibs.split()))
Yifei Feng5198cb82018-08-17 13:53:06 -07001583 write_action_env_to_bazelrc('TF_SYSTEM_LIBS', syslibs)
1584
Jason Zaman5fc39bd2018-09-16 01:38:55 +08001585 if 'PREFIX' in environ_cp:
1586 write_to_bazelrc('build --define=PREFIX=%s' % environ_cp['PREFIX'])
1587 if 'LIBDIR' in environ_cp:
1588 write_to_bazelrc('build --define=LIBDIR=%s' % environ_cp['LIBDIR'])
1589 if 'INCLUDEDIR' in environ_cp:
1590 write_to_bazelrc('build --define=INCLUDEDIR=%s' % environ_cp['INCLUDEDIR'])
1591
Yifei Feng5198cb82018-08-17 13:53:06 -07001592
A. Unique TensorFlower1b212352018-07-19 13:48:50 -07001593def set_windows_build_flags(environ_cp):
1594 """Set Windows specific build options."""
1595 # The non-monolithic build is not supported yet
1596 write_to_bazelrc('build --config monolithic')
1597 # Suppress warning messages
1598 write_to_bazelrc('build --copt=-w --host_copt=-w')
Loo Rong Jie31f10d22019-02-02 10:03:20 +08001599 # Fix winsock2.h conflicts
TensorFlower Gardener345cccf2019-02-28 15:22:59 -08001600 write_to_bazelrc(
1601 'build --copt=-DWIN32_LEAN_AND_MEAN --host_copt=-DWIN32_LEAN_AND_MEAN')
A. Unique TensorFlower1b212352018-07-19 13:48:50 -07001602 # Output more verbose information when something goes wrong
1603 write_to_bazelrc('build --verbose_failures')
1604 # The host and target platforms are the same in Windows build. So we don't
1605 # have to distinct them. This avoids building the same targets twice.
1606 write_to_bazelrc('build --distinct_host_configuration=false')
A. Unique TensorFlower1b212352018-07-19 13:48:50 -07001607
1608 if get_var(
1609 environ_cp, 'TF_OVERRIDE_EIGEN_STRONG_INLINE', 'Eigen strong inline',
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -07001610 True, ('Would you like to override eigen strong inline for some C++ '
1611 'compilation to reduce the compilation time?'),
1612 'Eigen strong inline overridden.', 'Not overriding eigen strong inline, '
A. Unique TensorFlower1b212352018-07-19 13:48:50 -07001613 'some compilations could take more than 20 mins.'):
1614 # Due to a known MSVC compiler issue
1615 # https://github.com/tensorflow/tensorflow/issues/10521
1616 # Overriding eigen strong inline speeds up the compiling of
1617 # conv_grad_ops_3d.cc and conv_ops_3d.cc by 20 minutes,
1618 # but this also hurts the performance. Let users decide what they want.
1619 write_to_bazelrc('build --define=override_eigen_strong_inline=true')
Dandelion Man?90e42f32017-12-15 18:15:07 -08001620
A. Unique TensorFlower061c3592017-11-13 14:21:04 -08001621
Michael Cased31531a2018-01-05 14:09:41 -08001622def config_info_line(name, help_text):
1623 """Helper function to print formatted help text for Bazel config options."""
1624 print('\t--config=%-12s\t# %s' % (name, help_text))
1625
1626
A. Unique TensorFlower76e879d2019-03-22 00:25:36 -07001627def configure_ios():
1628 """Configures TensorFlow for iOS builds.
A. Unique TensorFlower93e70732019-02-14 16:45:32 -08001629
A. Unique TensorFlower76e879d2019-03-22 00:25:36 -07001630 This function will only be executed if `is_macos()` is true.
A. Unique TensorFlower93e70732019-02-14 16:45:32 -08001631 """
1632 if not is_macos():
1633 return
A. Unique TensorFlowered297342019-03-15 11:25:28 -07001634 if _TF_CURRENT_BAZEL_VERSION is None or _TF_CURRENT_BAZEL_VERSION < 23000:
1635 print(
1636 'Building Bazel rules on Apple platforms requires Bazel 0.23 or later.')
A. Unique TensorFlower76e879d2019-03-22 00:25:36 -07001637 for filepath in APPLE_BAZEL_FILES:
1638 existing_filepath = os.path.join(_TF_WORKSPACE_ROOT, filepath + '.apple')
1639 renamed_filepath = os.path.join(_TF_WORKSPACE_ROOT, filepath)
1640 symlink_force(existing_filepath, renamed_filepath)
1641 for filepath in IOS_FILES:
1642 filename = os.path.basename(filepath)
1643 new_filepath = os.path.join(_TF_WORKSPACE_ROOT, filename)
1644 symlink_force(filepath, new_filepath)
A. Unique TensorFlower93e70732019-02-14 16:45:32 -08001645
1646
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001647def main():
A. Unique TensorFlower7c5eb352018-10-01 07:15:23 -07001648 global _TF_WORKSPACE_ROOT
1649 global _TF_BAZELRC
A. Unique TensorFlowered297342019-03-15 11:25:28 -07001650 global _TF_CURRENT_BAZEL_VERSION
A. Unique TensorFlower7c5eb352018-10-01 07:15:23 -07001651
Shanqing Cai71445712018-03-12 19:33:52 -07001652 parser = argparse.ArgumentParser()
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -07001653 parser.add_argument(
1654 '--workspace',
1655 type=str,
A. Unique TensorFlower7c5eb352018-10-01 07:15:23 -07001656 default=os.path.abspath(os.path.dirname(__file__)),
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -07001657 help='The absolute path to your active Bazel workspace.')
Shanqing Cai71445712018-03-12 19:33:52 -07001658 args = parser.parse_args()
1659
A. Unique TensorFlower7c5eb352018-10-01 07:15:23 -07001660 _TF_WORKSPACE_ROOT = args.workspace
1661 _TF_BAZELRC = os.path.join(_TF_WORKSPACE_ROOT, _TF_BAZELRC_FILENAME)
1662
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001663 # Make a copy of os.environ to be clear when functions and getting and setting
1664 # environment variables.
1665 environ_cp = dict(os.environ)
1666
A. Unique TensorFlower2b9c2992019-04-04 10:30:19 -07001667 current_bazel_version = check_bazel_version('0.22.0', '0.24.1')
A. Unique TensorFlowered297342019-03-15 11:25:28 -07001668 _TF_CURRENT_BAZEL_VERSION = convert_version_to_int(current_bazel_version)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001669
A. Unique TensorFlower7c5eb352018-10-01 07:15:23 -07001670 reset_tf_configure_bazelrc()
Yun Peng03e63a22018-11-07 11:18:53 +01001671
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001672 cleanup_makefile()
Gunhan Gulsoyed89a2b2017-09-19 18:36:26 -07001673 setup_python(environ_cp)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001674
1675 if is_windows():
Yifei Fengb1d8c592017-11-22 13:42:21 -08001676 environ_cp['TF_NEED_OPENCL_SYCL'] = '0'
1677 environ_cp['TF_NEED_COMPUTECPP'] = '0'
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001678 environ_cp['TF_NEED_OPENCL'] = '0'
1679 environ_cp['TF_CUDA_CLANG'] = '0'
Guangda Lai76f69382018-01-25 23:59:19 -08001680 environ_cp['TF_NEED_TENSORRT'] = '0'
Ilya Biryukov9e651e42018-03-22 05:33:42 -07001681 # TODO(ibiryukov): Investigate using clang as a cpu or cuda compiler on
1682 # Windows.
1683 environ_cp['TF_DOWNLOAD_CLANG'] = '0'
A. Unique TensorFlower6e97fb32018-07-16 14:07:29 -07001684 environ_cp['TF_NEED_MPI'] = '0'
1685 environ_cp['TF_SET_ANDROID_WORKSPACE'] = '0'
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001686
1687 if is_macos():
Guangda Lai76f69382018-01-25 23:59:19 -08001688 environ_cp['TF_NEED_TENSORRT'] = '0'
A. Unique TensorFlower93e70732019-02-14 16:45:32 -08001689 else:
A. Unique TensorFlower76e879d2019-03-22 00:25:36 -07001690 environ_cp['TF_CONFIGURE_IOS'] = '0'
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001691
Jon Triebenbach6896a742018-06-27 13:29:53 -05001692 # The numpy package on ppc64le uses OpenBLAS which has multi-threading
1693 # issues that lead to incorrect answers. Set OMP_NUM_THREADS=1 at
1694 # runtime to allow the Tensorflow testcases which compare numpy
1695 # results to Tensorflow results to succeed.
1696 if is_ppc64le():
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -07001697 write_action_env_to_bazelrc('OMP_NUM_THREADS', 1)
Jon Triebenbach6896a742018-06-27 13:29:53 -05001698
Grzegorz Pawelczakec82efd2018-10-09 15:03:46 +01001699 xla_enabled_by_default = is_linux()
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001700 set_build_var(environ_cp, 'TF_ENABLE_XLA', 'XLA JIT', 'with_xla_support',
Grzegorz Pawelczakec82efd2018-10-09 15:03:46 +01001701 xla_enabled_by_default, 'xla')
Gunhan Gulsoy3da0dff2018-09-26 11:55:50 -07001702
Yifei Fengb1d8c592017-11-22 13:42:21 -08001703 set_action_env_var(environ_cp, 'TF_NEED_OPENCL_SYCL', 'OpenCL SYCL', False)
1704 if environ_cp.get('TF_NEED_OPENCL_SYCL') == '1':
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001705 set_host_cxx_compiler(environ_cp)
1706 set_host_c_compiler(environ_cp)
Yifei Fengb1d8c592017-11-22 13:42:21 -08001707 set_action_env_var(environ_cp, 'TF_NEED_COMPUTECPP', 'ComputeCPP', True)
1708 if environ_cp.get('TF_NEED_COMPUTECPP') == '1':
1709 set_computecpp_toolkit_path(environ_cp)
1710 else:
1711 set_trisycl_include_dir(environ_cp)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001712
Wen-Heng (Jack) Chung69d3b8f2018-06-22 23:09:43 -05001713 set_action_env_var(environ_cp, 'TF_NEED_ROCM', 'ROCm', False)
1714 if (environ_cp.get('TF_NEED_ROCM') == '1' and
TensorFlower Gardener62e60162018-09-27 10:22:55 -07001715 'LD_LIBRARY_PATH' in environ_cp and
1716 environ_cp.get('LD_LIBRARY_PATH') != '1'):
1717 write_action_env_to_bazelrc('LD_LIBRARY_PATH',
1718 environ_cp.get('LD_LIBRARY_PATH'))
Wen-Heng (Jack) Chung69d3b8f2018-06-22 23:09:43 -05001719
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001720 set_action_env_var(environ_cp, 'TF_NEED_CUDA', 'CUDA', False)
A. Unique TensorFlower24cbb2a2017-09-08 07:45:44 -07001721 if (environ_cp.get('TF_NEED_CUDA') == '1' and
1722 'TF_CUDA_CONFIG_REPO' not in environ_cp):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001723 set_tf_cuda_version(environ_cp)
Yifei Fengb1d8c592017-11-22 13:42:21 -08001724 set_tf_cudnn_version(environ_cp)
Guangda Lai76f69382018-01-25 23:59:19 -08001725 if is_linux():
1726 set_tf_tensorrt_install_path(environ_cp)
Michael Case0073d132018-04-11 09:34:44 -07001727 set_tf_nccl_install_path(environ_cp)
1728
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001729 set_tf_cuda_compute_capabilities(environ_cp)
Ankur Taly0e6f39d2018-02-16 18:22:55 -08001730 if 'LD_LIBRARY_PATH' in environ_cp and environ_cp.get(
1731 'LD_LIBRARY_PATH') != '1':
1732 write_action_env_to_bazelrc('LD_LIBRARY_PATH',
1733 environ_cp.get('LD_LIBRARY_PATH'))
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001734
1735 set_tf_cuda_clang(environ_cp)
1736 if environ_cp.get('TF_CUDA_CLANG') == '1':
Ilya Biryukov9e651e42018-03-22 05:33:42 -07001737 # Ask whether we should download the clang toolchain.
1738 set_tf_download_clang(environ_cp)
A. Unique TensorFlowerfd29e952017-12-22 03:07:51 -08001739 if environ_cp.get('TF_DOWNLOAD_CLANG') != '1':
1740 # Set up which clang we should use as the cuda / host compiler.
1741 set_clang_cuda_compiler_path(environ_cp)
Ilya Biryukov1c3d02e2018-09-04 03:09:52 -07001742 else:
1743 # Use downloaded LLD for linking.
1744 write_to_bazelrc('build:cuda_clang --config=download_clang_use_lld')
1745 write_to_bazelrc('test:cuda_clang --config=download_clang_use_lld')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001746 else:
1747 # Set up which gcc nvcc should use as the host compiler
1748 # No need to set this on Windows
1749 if not is_windows():
1750 set_gcc_host_compiler_path(environ_cp)
1751 set_other_cuda_vars(environ_cp)
Ilya Biryukov9e651e42018-03-22 05:33:42 -07001752 else:
1753 # CUDA not required. Ask whether we should download the clang toolchain and
1754 # use it for the CPU build.
1755 set_tf_download_clang(environ_cp)
1756 if environ_cp.get('TF_DOWNLOAD_CLANG') == '1':
1757 write_to_bazelrc('build --config=download_clang')
1758 write_to_bazelrc('test --config=download_clang')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001759
Wen-Heng (Jack) Chung69d3b8f2018-06-22 23:09:43 -05001760 # SYCL / ROCm / CUDA are mutually exclusive.
1761 # At most 1 GPU platform can be configured.
1762 gpu_platform_count = 0
1763 if environ_cp.get('TF_NEED_OPENCL_SYCL') == '1':
1764 gpu_platform_count += 1
1765 if environ_cp.get('TF_NEED_ROCM') == '1':
1766 gpu_platform_count += 1
1767 if environ_cp.get('TF_NEED_CUDA') == '1':
1768 gpu_platform_count += 1
1769 if gpu_platform_count >= 2:
1770 raise UserInputError('SYCL / CUDA / ROCm are mututally exclusive. '
1771 'At most 1 GPU platform can be configured.')
1772
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001773 set_build_var(environ_cp, 'TF_NEED_MPI', 'MPI', 'with_mpi_support', False)
1774 if environ_cp.get('TF_NEED_MPI') == '1':
1775 set_mpi_home(environ_cp)
1776 set_other_mpi_vars(environ_cp)
1777
1778 set_cc_opt_flags(environ_cp)
Yifei Feng5198cb82018-08-17 13:53:06 -07001779 set_system_libs_flag(environ_cp)
A. Unique TensorFlower1b212352018-07-19 13:48:50 -07001780 if is_windows():
1781 set_windows_build_flags(environ_cp)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001782
Anna Ra9a1d5a2018-09-14 12:44:31 -07001783 # Add a config option to build TensorFlow 2.0 API.
1784 write_to_bazelrc('build:v2 --define=tf_api_version=2')
1785
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -07001786 if get_var(environ_cp, 'TF_SET_ANDROID_WORKSPACE', 'android workspace', False,
1787 ('Would you like to interactively configure ./WORKSPACE for '
1788 'Android builds?'), 'Searching for NDK and SDK installations.',
1789 'Not configuring the WORKSPACE for Android builds.'):
Michael Case51053502018-06-05 17:47:19 -07001790 create_android_ndk_rule(environ_cp)
1791 create_android_sdk_rule(environ_cp)
Austin Anderson6afface2017-12-05 11:59:17 -08001792
A. Unique TensorFlowere9797fd2019-03-22 11:02:40 -07001793 system_specific_test_config(os.environ)
Gunhan Gulsoyfff66962019-02-20 15:28:43 -08001794
A. Unique TensorFlower5001ac02019-04-03 11:59:08 -07001795 set_action_env_var(environ_cp, 'TF_CONFIGURE_IOS', 'iOS', False)
1796 if environ_cp.get('TF_CONFIGURE_IOS') == '1':
A. Unique TensorFlower76e879d2019-03-22 00:25:36 -07001797 configure_ios()
A. Unique TensorFlowere9797fd2019-03-22 11:02:40 -07001798 else:
1799 # TODO(pcloudy): Remove BAZEL_USE_CPP_ONLY_TOOLCHAIN after Bazel is upgraded
1800 # to 0.24.0.
1801 # For working around https://github.com/bazelbuild/bazel/issues/7607
1802 if is_macos():
1803 write_to_bazelrc('build --action_env=BAZEL_USE_CPP_ONLY_TOOLCHAIN=1')
A. Unique TensorFlower93e70732019-02-14 16:45:32 -08001804
Gunhan Gulsoy34370982018-10-12 15:26:01 -07001805 print('Preconfigured Bazel build configs. You can use any of the below by '
1806 'adding "--config=<>" to your build command. See .bazelrc for more '
1807 'details.')
1808 config_info_line('mkl', 'Build with MKL support.')
1809 config_info_line('monolithic', 'Config for mostly static monolithic build.')
1810 config_info_line('gdr', 'Build with GDR support.')
1811 config_info_line('verbs', 'Build with libverbs support.')
1812 config_info_line('ngraph', 'Build with Intel nGraph support.')
A. Unique TensorFlowera6bf9c82019-02-26 10:08:35 -08001813 config_info_line('numa', 'Build with NUMA support.')
TensorFlower Gardenerabb763b2019-02-06 16:23:03 -08001814 config_info_line(
1815 'dynamic_kernels',
1816 '(Experimental) Build kernels into separate shared objects.')
Gunhan Gulsoy34370982018-10-12 15:26:01 -07001817
1818 print('Preconfigured Bazel build configs to DISABLE default on features:')
1819 config_info_line('noaws', 'Disable AWS S3 filesystem support.')
1820 config_info_line('nogcp', 'Disable GCP support.')
1821 config_info_line('nohdfs', 'Disable HDFS support.')
Penporn Koanantakool489f1dc2019-01-10 22:07:22 -08001822 config_info_line('noignite', 'Disable Apache Ignite support.')
Gunhan Gulsoy34370982018-10-12 15:26:01 -07001823 config_info_line('nokafka', 'Disable Apache Kafka support.')
Gunhan Gulsoyeea81682018-11-26 16:51:23 -08001824 config_info_line('nonccl', 'Disable NVIDIA NCCL support.')
Austin Anderson6afface2017-12-05 11:59:17 -08001825
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -07001826
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001827if __name__ == '__main__':
1828 main()