blob: 5ca6df713bdffe7ccda2ee4ee3de931a5e2b817c [file] [log] [blame]
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001# Copyright 2017 The TensorFlow Authors. All Rights Reserved.
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14# ==============================================================================
15"""configure script to get build parameters from user."""
16
17from __future__ import absolute_import
18from __future__ import division
19from __future__ import print_function
20
Shanqing Cai71445712018-03-12 19:33:52 -070021import argparse
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -070022import errno
23import os
24import platform
25import re
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -070026import subprocess
27import sys
28
Andrew Sellec9885ea2017-11-06 09:37:03 -080029# pylint: disable=g-import-not-at-top
Jonathan Hseu008910f2017-08-25 14:01:05 -070030try:
31 from shutil import which
32except ImportError:
33 from distutils.spawn import find_executable as which
Andrew Sellec9885ea2017-11-06 09:37:03 -080034# pylint: enable=g-import-not-at-top
Jonathan Hseu008910f2017-08-25 14:01:05 -070035
Gunhan Gulsoyc59db932018-12-28 16:32:01 -080036_DEFAULT_CUDA_VERSION = '10.0'
Dandelion Man?90e42f32017-12-15 18:15:07 -080037_DEFAULT_CUDNN_VERSION = '7'
Smit Hinsufe7d1d92018-07-14 13:16:58 -070038_DEFAULT_CUDA_COMPUTE_CAPABILITIES = '3.5,7.0'
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -070039_DEFAULT_CUDA_PATH = '/usr/local/cuda'
40_DEFAULT_CUDA_PATH_LINUX = '/opt/cuda'
41_DEFAULT_CUDA_PATH_WIN = ('C:/Program Files/NVIDIA GPU Computing '
42 'Toolkit/CUDA/v%s' % _DEFAULT_CUDA_VERSION)
43_TF_OPENCL_VERSION = '1.2'
44_DEFAULT_COMPUTECPP_TOOLKIT_PATH = '/usr/local/computecpp'
Yifei Fengb1d8c592017-11-22 13:42:21 -080045_DEFAULT_TRISYCL_INCLUDE_DIR = '/usr/local/triSYCL/include'
A. Unique TensorFlower82820ef2018-11-12 13:22:13 -080046_SUPPORTED_ANDROID_NDK_VERSIONS = [10, 11, 12, 13, 14, 15, 16, 17, 18]
Austin Anderson6afface2017-12-05 11:59:17 -080047
48_DEFAULT_PROMPT_ASK_ATTEMPTS = 10
49
Shanqing Cai71445712018-03-12 19:33:52 -070050_TF_BAZELRC_FILENAME = '.tf_configure.bazelrc'
A. Unique TensorFlower7c5eb352018-10-01 07:15:23 -070051_TF_WORKSPACE_ROOT = ''
52_TF_BAZELRC = ''
A. Unique TensorFlowered297342019-03-15 11:25:28 -070053_TF_CURRENT_BAZEL_VERSION = None
Shanqing Cai71445712018-03-12 19:33:52 -070054
Jason Furmanek7c234152018-09-26 04:44:12 +000055NCCL_LIB_PATHS = [
TensorFlower Gardenerea5c5292018-10-01 17:28:26 -070056 'lib64/', 'lib/powerpc64le-linux-gnu/', 'lib/x86_64-linux-gnu/', ''
Jason Furmanek7c234152018-09-26 04:44:12 +000057]
Austin Anderson6afface2017-12-05 11:59:17 -080058
A. Unique TensorFlower76e879d2019-03-22 00:25:36 -070059# List of files to configure when building Bazel on Apple platforms.
A. Unique TensorFlower93e70732019-02-14 16:45:32 -080060APPLE_BAZEL_FILES = [
61 'tensorflow/lite/experimental/objc/BUILD',
62 'tensorflow/lite/experimental/swift/BUILD'
63]
64
A. Unique TensorFlower76e879d2019-03-22 00:25:36 -070065# List of files to move when building for iOS.
66IOS_FILES = [
67 'tensorflow/lite/experimental/objc/TensorFlowLiteObjC.podspec',
68 'tensorflow/lite/experimental/swift/TensorFlowLiteSwift.podspec',
69]
70
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -070071if platform.machine() == 'ppc64le':
72 _DEFAULT_TENSORRT_PATH_LINUX = '/usr/lib/powerpc64le-linux-gnu/'
73else:
74 _DEFAULT_TENSORRT_PATH_LINUX = '/usr/lib/%s-linux-gnu' % platform.machine()
75
Austin Anderson6afface2017-12-05 11:59:17 -080076
77class UserInputError(Exception):
78 pass
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -070079
80
81def is_windows():
82 return platform.system() == 'Windows'
83
84
85def is_linux():
86 return platform.system() == 'Linux'
87
88
89def is_macos():
90 return platform.system() == 'Darwin'
91
92
93def is_ppc64le():
94 return platform.machine() == 'ppc64le'
95
96
Jonathan Hseu008910f2017-08-25 14:01:05 -070097def is_cygwin():
98 return platform.system().startswith('CYGWIN_NT')
99
100
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700101def get_input(question):
102 try:
103 try:
104 answer = raw_input(question)
105 except NameError:
106 answer = input(question) # pylint: disable=bad-builtin
107 except EOFError:
108 answer = ''
109 return answer
110
111
112def symlink_force(target, link_name):
113 """Force symlink, equivalent of 'ln -sf'.
114
115 Args:
116 target: items to link to.
117 link_name: name of the link.
118 """
119 try:
120 os.symlink(target, link_name)
121 except OSError as e:
122 if e.errno == errno.EEXIST:
123 os.remove(link_name)
124 os.symlink(target, link_name)
125 else:
126 raise e
127
128
129def sed_in_place(filename, old, new):
130 """Replace old string with new string in file.
131
132 Args:
133 filename: string for filename.
134 old: string to replace.
135 new: new string to replace to.
136 """
137 with open(filename, 'r') as f:
138 filedata = f.read()
139 newdata = filedata.replace(old, new)
140 with open(filename, 'w') as f:
141 f.write(newdata)
142
143
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700144def write_to_bazelrc(line):
145 with open(_TF_BAZELRC, 'a') as f:
146 f.write(line + '\n')
147
148
149def write_action_env_to_bazelrc(var_name, var):
150 write_to_bazelrc('build --action_env %s="%s"' % (var_name, str(var)))
151
152
Jonathan Hseu008910f2017-08-25 14:01:05 -0700153def run_shell(cmd, allow_non_zero=False):
154 if allow_non_zero:
155 try:
156 output = subprocess.check_output(cmd)
157 except subprocess.CalledProcessError as e:
158 output = e.output
159 else:
160 output = subprocess.check_output(cmd)
161 return output.decode('UTF-8').strip()
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700162
163
164def cygpath(path):
165 """Convert path from posix to windows."""
Martin Wicked57572e2017-09-02 19:21:45 -0700166 return os.path.abspath(path).replace('\\', '/')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700167
168
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700169def get_python_path(environ_cp, python_bin_path):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700170 """Get the python site package paths."""
171 python_paths = []
172 if environ_cp.get('PYTHONPATH'):
173 python_paths = environ_cp.get('PYTHONPATH').split(':')
174 try:
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700175 library_paths = run_shell([
176 python_bin_path, '-c',
177 'import site; print("\\n".join(site.getsitepackages()))'
178 ]).split('\n')
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700179 except subprocess.CalledProcessError:
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700180 library_paths = [
181 run_shell([
182 python_bin_path, '-c',
183 'from distutils.sysconfig import get_python_lib;'
184 'print(get_python_lib())'
185 ])
186 ]
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700187
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700188 all_paths = set(python_paths + library_paths)
189
190 paths = []
191 for path in all_paths:
192 if os.path.isdir(path):
193 paths.append(path)
194 return paths
195
196
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700197def get_python_major_version(python_bin_path):
198 """Get the python major version."""
Jonathan Hseu008910f2017-08-25 14:01:05 -0700199 return run_shell([python_bin_path, '-c', 'import sys; print(sys.version[0])'])
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700200
201
Gunhan Gulsoyed89a2b2017-09-19 18:36:26 -0700202def setup_python(environ_cp):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700203 """Setup python related env variables."""
204 # Get PYTHON_BIN_PATH, default is the current running python.
205 default_python_bin_path = sys.executable
206 ask_python_bin_path = ('Please specify the location of python. [Default is '
207 '%s]: ') % default_python_bin_path
208 while True:
209 python_bin_path = get_from_env_or_user_or_default(
210 environ_cp, 'PYTHON_BIN_PATH', ask_python_bin_path,
211 default_python_bin_path)
212 # Check if the path is valid
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700213 if os.path.isfile(python_bin_path) and os.access(python_bin_path, os.X_OK):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700214 break
215 elif not os.path.exists(python_bin_path):
216 print('Invalid python path: %s cannot be found.' % python_bin_path)
217 else:
218 print('%s is not executable. Is it the python binary?' % python_bin_path)
219 environ_cp['PYTHON_BIN_PATH'] = ''
220
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700221 # Convert python path to Windows style before checking lib and version
Martin Wicked57572e2017-09-02 19:21:45 -0700222 if is_windows() or is_cygwin():
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700223 python_bin_path = cygpath(python_bin_path)
224
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700225 # Get PYTHON_LIB_PATH
226 python_lib_path = environ_cp.get('PYTHON_LIB_PATH')
227 if not python_lib_path:
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700228 python_lib_paths = get_python_path(environ_cp, python_bin_path)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700229 if environ_cp.get('USE_DEFAULT_PYTHON_LIB_PATH') == '1':
Vijay Vasudevana1fba7f2017-07-28 10:58:56 -0700230 python_lib_path = python_lib_paths[0]
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700231 else:
Jonathan Hseu008910f2017-08-25 14:01:05 -0700232 print('Found possible Python library paths:\n %s' %
233 '\n '.join(python_lib_paths))
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700234 default_python_lib_path = python_lib_paths[0]
235 python_lib_path = get_input(
Jonathan Hseu008910f2017-08-25 14:01:05 -0700236 'Please input the desired Python library path to use. '
237 'Default is [%s]\n' % python_lib_paths[0])
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700238 if not python_lib_path:
239 python_lib_path = default_python_lib_path
Vijay Vasudevana1fba7f2017-07-28 10:58:56 -0700240 environ_cp['PYTHON_LIB_PATH'] = python_lib_path
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700241
TensorFlower Gardener61a87202018-10-01 12:25:39 -0700242 _ = get_python_major_version(python_bin_path)
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700243
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700244 # Convert python path to Windows style before writing into bazel.rc
Martin Wicked57572e2017-09-02 19:21:45 -0700245 if is_windows() or is_cygwin():
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700246 python_lib_path = cygpath(python_lib_path)
247
248 # Set-up env variables used by python_configure.bzl
249 write_action_env_to_bazelrc('PYTHON_BIN_PATH', python_bin_path)
250 write_action_env_to_bazelrc('PYTHON_LIB_PATH', python_lib_path)
Gunhan Gulsoyed89a2b2017-09-19 18:36:26 -0700251 write_to_bazelrc('build --python_path=\"%s"' % python_bin_path)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700252 environ_cp['PYTHON_BIN_PATH'] = python_bin_path
253
William D. Ironsdcc76a52018-11-20 10:35:18 -0600254 # If choosen python_lib_path is from a path specified in the PYTHONPATH
255 # variable, need to tell bazel to include PYTHONPATH
256 if environ_cp.get('PYTHONPATH'):
257 python_paths = environ_cp.get('PYTHONPATH').split(':')
258 if python_lib_path in python_paths:
TensorFlower Gardener968cd182018-11-28 11:33:16 -0800259 write_action_env_to_bazelrc('PYTHONPATH', environ_cp.get('PYTHONPATH'))
William D. Ironsdcc76a52018-11-20 10:35:18 -0600260
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700261 # Write tools/python_bin_path.sh
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700262 with open(
263 os.path.join(_TF_WORKSPACE_ROOT, 'tools', 'python_bin_path.sh'),
264 'w') as f:
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700265 f.write('export PYTHON_BIN_PATH="%s"' % python_bin_path)
266
267
A. Unique TensorFlower7c5eb352018-10-01 07:15:23 -0700268def reset_tf_configure_bazelrc():
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700269 """Reset file that contains customized config settings."""
270 open(_TF_BAZELRC, 'w').close()
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700271
TensorFlower Gardenerabb763b2019-02-06 16:23:03 -0800272
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700273def cleanup_makefile():
274 """Delete any leftover BUILD files from the Makefile build.
275
276 These files could interfere with Bazel parsing.
277 """
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700278 makefile_download_dir = os.path.join(_TF_WORKSPACE_ROOT, 'tensorflow',
279 'contrib', 'makefile', 'downloads')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700280 if os.path.isdir(makefile_download_dir):
281 for root, _, filenames in os.walk(makefile_download_dir):
282 for f in filenames:
283 if f.endswith('BUILD'):
284 os.remove(os.path.join(root, f))
285
286
287def get_var(environ_cp,
288 var_name,
289 query_item,
290 enabled_by_default,
291 question=None,
292 yes_reply=None,
293 no_reply=None):
294 """Get boolean input from user.
295
296 If var_name is not set in env, ask user to enable query_item or not. If the
297 response is empty, use the default.
298
299 Args:
300 environ_cp: copy of the os.environ.
301 var_name: string for name of environment variable, e.g. "TF_NEED_HDFS".
302 query_item: string for feature related to the variable, e.g. "Hadoop File
303 System".
304 enabled_by_default: boolean for default behavior.
305 question: optional string for how to ask for user input.
Michael Cased90054e2018-02-07 14:36:00 -0800306 yes_reply: optional string for reply when feature is enabled.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700307 no_reply: optional string for reply when feature is disabled.
308
309 Returns:
310 boolean value of the variable.
Frank Chenc4ef9272018-01-10 11:36:52 -0800311
312 Raises:
313 UserInputError: if an environment variable is set, but it cannot be
314 interpreted as a boolean indicator, assume that the user has made a
315 scripting error, and will continue to provide invalid input.
316 Raise the error to avoid infinitely looping.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700317 """
318 if not question:
319 question = 'Do you wish to build TensorFlow with %s support?' % query_item
320 if not yes_reply:
321 yes_reply = '%s support will be enabled for TensorFlow.' % query_item
322 if not no_reply:
323 no_reply = 'No %s' % yes_reply
324
325 yes_reply += '\n'
326 no_reply += '\n'
327
328 if enabled_by_default:
329 question += ' [Y/n]: '
330 else:
331 question += ' [y/N]: '
332
333 var = environ_cp.get(var_name)
Frank Chenc4ef9272018-01-10 11:36:52 -0800334 if var is not None:
335 var_content = var.strip().lower()
336 true_strings = ('1', 't', 'true', 'y', 'yes')
337 false_strings = ('0', 'f', 'false', 'n', 'no')
338 if var_content in true_strings:
339 var = True
340 elif var_content in false_strings:
341 var = False
342 else:
343 raise UserInputError(
344 'Environment variable %s must be set as a boolean indicator.\n'
345 'The following are accepted as TRUE : %s.\n'
346 'The following are accepted as FALSE: %s.\n'
A. Unique TensorFlowered297342019-03-15 11:25:28 -0700347 'Current value is %s.' %
348 (var_name, ', '.join(true_strings), ', '.join(false_strings), var))
Frank Chenc4ef9272018-01-10 11:36:52 -0800349
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700350 while var is None:
351 user_input_origin = get_input(question)
352 user_input = user_input_origin.strip().lower()
353 if user_input == 'y':
354 print(yes_reply)
355 var = True
356 elif user_input == 'n':
357 print(no_reply)
358 var = False
359 elif not user_input:
360 if enabled_by_default:
361 print(yes_reply)
362 var = True
363 else:
364 print(no_reply)
365 var = False
366 else:
367 print('Invalid selection: %s' % user_input_origin)
368 return var
369
370
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700371def set_build_var(environ_cp,
372 var_name,
373 query_item,
374 option_name,
375 enabled_by_default,
376 bazel_config_name=None):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700377 """Set if query_item will be enabled for the build.
378
379 Ask user if query_item will be enabled. Default is used if no input is given.
380 Set subprocess environment variable and write to .bazelrc if enabled.
381
382 Args:
383 environ_cp: copy of the os.environ.
384 var_name: string for name of environment variable, e.g. "TF_NEED_HDFS".
385 query_item: string for feature related to the variable, e.g. "Hadoop File
386 System".
387 option_name: string for option to define in .bazelrc.
388 enabled_by_default: boolean for default behavior.
Michael Case98850a52017-09-14 13:35:57 -0700389 bazel_config_name: Name for Bazel --config argument to enable build feature.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700390 """
391
392 var = str(int(get_var(environ_cp, var_name, query_item, enabled_by_default)))
393 environ_cp[var_name] = var
394 if var == '1':
Yifei Fengec451f52018-10-05 12:53:50 -0700395 write_to_bazelrc(
396 'build:%s --define %s=true' % (bazel_config_name, option_name))
397 write_to_bazelrc('build --config=%s' % bazel_config_name)
Michael Case98850a52017-09-14 13:35:57 -0700398 elif bazel_config_name is not None:
399 # TODO(mikecase): Migrate all users of configure.py to use --config Bazel
400 # options and not to set build configs through environment variables.
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700401 write_to_bazelrc(
402 'build:%s --define %s=true' % (bazel_config_name, option_name))
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700403
404
405def set_action_env_var(environ_cp,
406 var_name,
407 query_item,
408 enabled_by_default,
409 question=None,
410 yes_reply=None,
411 no_reply=None):
412 """Set boolean action_env variable.
413
414 Ask user if query_item will be enabled. Default is used if no input is given.
415 Set environment variable and write to .bazelrc.
416
417 Args:
418 environ_cp: copy of the os.environ.
419 var_name: string for name of environment variable, e.g. "TF_NEED_HDFS".
420 query_item: string for feature related to the variable, e.g. "Hadoop File
421 System".
422 enabled_by_default: boolean for default behavior.
423 question: optional string for how to ask for user input.
Michael Cased90054e2018-02-07 14:36:00 -0800424 yes_reply: optional string for reply when feature is enabled.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700425 no_reply: optional string for reply when feature is disabled.
426 """
427 var = int(
428 get_var(environ_cp, var_name, query_item, enabled_by_default, question,
429 yes_reply, no_reply))
430
431 write_action_env_to_bazelrc(var_name, var)
432 environ_cp[var_name] = str(var)
433
434
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700435def convert_version_to_int(version):
436 """Convert a version number to a integer that can be used to compare.
437
A. Unique TensorFlower28ce1d12017-08-15 12:08:29 -0700438 Version strings of the form X.YZ and X.Y.Z-xxxxx are supported. The
439 'xxxxx' part, for instance 'homebrew' on OS/X, is ignored.
440
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700441 Args:
A. Unique TensorFlower28ce1d12017-08-15 12:08:29 -0700442 version: a version to be converted
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700443
444 Returns:
445 An integer if converted successfully, otherwise return None.
446 """
A. Unique TensorFlower28ce1d12017-08-15 12:08:29 -0700447 version = version.split('-')[0]
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700448 version_segments = version.split('.')
449 for seg in version_segments:
450 if not seg.isdigit():
451 return None
452
453 version_str = ''.join(['%03d' % int(seg) for seg in version_segments])
454 return int(version_str)
455
456
Mihai Maruseace7a123f2018-11-30 13:33:25 -0800457def check_bazel_version(min_version, max_version):
458 """Check installed bazel version is between min_version and max_version.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700459
460 Args:
461 min_version: string for minimum bazel version.
Mihai Maruseace7a123f2018-11-30 13:33:25 -0800462 max_version: string for maximum bazel version.
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700463
464 Returns:
465 The bazel version detected.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700466 """
Jonathan Hseu008910f2017-08-25 14:01:05 -0700467 if which('bazel') is None:
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700468 print('Cannot find bazel. Please install bazel.')
469 sys.exit(0)
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700470 curr_version = run_shell(
471 ['bazel', '--batch', '--bazelrc=/dev/null', 'version'])
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700472
473 for line in curr_version.split('\n'):
474 if 'Build label: ' in line:
475 curr_version = line.split('Build label: ')[1]
476 break
477
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700478 min_version_int = convert_version_to_int(min_version)
479 curr_version_int = convert_version_to_int(curr_version)
Mihai Maruseace7a123f2018-11-30 13:33:25 -0800480 max_version_int = convert_version_to_int(max_version)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700481
482 # Check if current bazel version can be detected properly.
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700483 if not curr_version_int:
484 print('WARNING: current bazel installation is not a release version.')
485 print('Make sure you are running at least bazel %s' % min_version)
486 return curr_version
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700487
Michael Cased94271a2017-08-22 17:26:52 -0700488 print('You have bazel %s installed.' % curr_version)
A. Unique TensorFlower28ce1d12017-08-15 12:08:29 -0700489
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700490 if curr_version_int < min_version_int:
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700491 print('Please upgrade your bazel installation to version %s or higher to '
492 'build TensorFlow!' % min_version)
Jason Zamanb41761c2018-10-14 11:28:53 +0800493 sys.exit(1)
TensorFlower Gardener78c246b2018-12-13 12:37:42 -0800494 if (curr_version_int > max_version_int and
495 'TF_IGNORE_MAX_BAZEL_VERSION' not in os.environ):
Mihai Maruseace7a123f2018-11-30 13:33:25 -0800496 print('Please downgrade your bazel installation to version %s or lower to '
Mihai Maruseace0963c42018-12-20 14:27:40 -0800497 'build TensorFlow! To downgrade: download the installer for the old '
498 'version (from https://github.com/bazelbuild/bazel/releases) then '
499 'run the installer.' % max_version)
Jason Zamanb41761c2018-10-14 11:28:53 +0800500 sys.exit(1)
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700501 return curr_version
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700502
503
504def set_cc_opt_flags(environ_cp):
505 """Set up architecture-dependent optimization flags.
506
507 Also append CC optimization flags to bazel.rc..
508
509 Args:
510 environ_cp: copy of the os.environ.
511 """
512 if is_ppc64le():
513 # gcc on ppc64le does not support -march, use mcpu instead
514 default_cc_opt_flags = '-mcpu=native'
A. Unique TensorFlower1bba94a2018-04-04 15:45:20 -0700515 elif is_windows():
516 default_cc_opt_flags = '/arch:AVX'
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700517 else:
Justin Lebar9ef04f52018-10-10 18:52:45 -0700518 default_cc_opt_flags = '-march=native -Wno-sign-compare'
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700519 question = ('Please specify optimization flags to use during compilation when'
520 ' bazel option "--config=opt" is specified [Default is %s]: '
521 ) % default_cc_opt_flags
522 cc_opt_flags = get_from_env_or_user_or_default(environ_cp, 'CC_OPT_FLAGS',
523 question, default_cc_opt_flags)
524 for opt in cc_opt_flags.split():
Michael Case00177422017-11-10 13:14:03 -0800525 write_to_bazelrc('build:opt --copt=%s' % opt)
526 # It should be safe on the same build host.
A. Unique TensorFlower1bba94a2018-04-04 15:45:20 -0700527 if not is_ppc64le() and not is_windows():
Shanqing Cai71445712018-03-12 19:33:52 -0700528 write_to_bazelrc('build:opt --host_copt=-march=native')
Michael Casebb3355d2017-11-09 08:46:31 -0800529 write_to_bazelrc('build:opt --define with_default_optimizations=true')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700530
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700531
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700532def set_tf_cuda_clang(environ_cp):
533 """set TF_CUDA_CLANG action_env.
534
535 Args:
536 environ_cp: copy of the os.environ.
537 """
538 question = 'Do you want to use clang as CUDA compiler?'
539 yes_reply = 'Clang will be used as CUDA compiler.'
540 no_reply = 'nvcc will be used as CUDA compiler.'
541 set_action_env_var(
542 environ_cp,
543 'TF_CUDA_CLANG',
544 None,
545 False,
546 question=question,
547 yes_reply=yes_reply,
548 no_reply=no_reply)
549
550
A. Unique TensorFlowerfd29e952017-12-22 03:07:51 -0800551def set_tf_download_clang(environ_cp):
552 """Set TF_DOWNLOAD_CLANG action_env."""
Ilya Biryukov9e651e42018-03-22 05:33:42 -0700553 question = 'Do you wish to download a fresh release of clang? (Experimental)'
A. Unique TensorFlowerfd29e952017-12-22 03:07:51 -0800554 yes_reply = 'Clang will be downloaded and used to compile tensorflow.'
555 no_reply = 'Clang will not be downloaded.'
556 set_action_env_var(
557 environ_cp,
558 'TF_DOWNLOAD_CLANG',
559 None,
560 False,
561 question=question,
562 yes_reply=yes_reply,
563 no_reply=no_reply)
564
565
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700566def get_from_env_or_user_or_default(environ_cp, var_name, ask_for_var,
567 var_default):
568 """Get var_name either from env, or user or default.
569
570 If var_name has been set as environment variable, use the preset value, else
571 ask for user input. If no input is provided, the default is used.
572
573 Args:
574 environ_cp: copy of the os.environ.
575 var_name: string for name of environment variable, e.g. "TF_NEED_HDFS".
576 ask_for_var: string for how to ask for user input.
577 var_default: default value string.
578
579 Returns:
580 string value for var_name
581 """
582 var = environ_cp.get(var_name)
583 if not var:
584 var = get_input(ask_for_var)
Michael Cased94271a2017-08-22 17:26:52 -0700585 print('\n')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700586 if not var:
587 var = var_default
588 return var
589
590
591def set_clang_cuda_compiler_path(environ_cp):
592 """Set CLANG_CUDA_COMPILER_PATH."""
Jonathan Hseu008910f2017-08-25 14:01:05 -0700593 default_clang_path = which('clang') or ''
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700594 ask_clang_path = ('Please specify which clang should be used as device and '
595 'host compiler. [Default is %s]: ') % default_clang_path
596
597 while True:
598 clang_cuda_compiler_path = get_from_env_or_user_or_default(
599 environ_cp, 'CLANG_CUDA_COMPILER_PATH', ask_clang_path,
600 default_clang_path)
601 if os.path.exists(clang_cuda_compiler_path):
602 break
603
604 # Reset and retry
605 print('Invalid clang path: %s cannot be found.' % clang_cuda_compiler_path)
606 environ_cp['CLANG_CUDA_COMPILER_PATH'] = ''
607
608 # Set CLANG_CUDA_COMPILER_PATH
609 environ_cp['CLANG_CUDA_COMPILER_PATH'] = clang_cuda_compiler_path
610 write_action_env_to_bazelrc('CLANG_CUDA_COMPILER_PATH',
611 clang_cuda_compiler_path)
612
613
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700614def prompt_loop_or_load_from_env(environ_cp,
615 var_name,
616 var_default,
617 ask_for_var,
618 check_success,
619 error_msg,
620 suppress_default_error=False,
621 n_ask_attempts=_DEFAULT_PROMPT_ASK_ATTEMPTS):
Austin Anderson6afface2017-12-05 11:59:17 -0800622 """Loop over user prompts for an ENV param until receiving a valid response.
623
624 For the env param var_name, read from the environment or verify user input
625 until receiving valid input. When done, set var_name in the environ_cp to its
626 new value.
627
628 Args:
629 environ_cp: (Dict) copy of the os.environ.
630 var_name: (String) string for name of environment variable, e.g. "TF_MYVAR".
631 var_default: (String) default value string.
632 ask_for_var: (String) string for how to ask for user input.
633 check_success: (Function) function that takes one argument and returns a
634 boolean. Should return True if the value provided is considered valid. May
635 contain a complex error message if error_msg does not provide enough
636 information. In that case, set suppress_default_error to True.
637 error_msg: (String) String with one and only one '%s'. Formatted with each
638 invalid response upon check_success(input) failure.
639 suppress_default_error: (Bool) Suppress the above error message in favor of
640 one from the check_success function.
641 n_ask_attempts: (Integer) Number of times to query for valid input before
642 raising an error and quitting.
643
644 Returns:
645 [String] The value of var_name after querying for input.
646
647 Raises:
648 UserInputError: if a query has been attempted n_ask_attempts times without
Frank Chenc4ef9272018-01-10 11:36:52 -0800649 success, assume that the user has made a scripting error, and will
650 continue to provide invalid input. Raise the error to avoid infinitely
651 looping.
Austin Anderson6afface2017-12-05 11:59:17 -0800652 """
653 default = environ_cp.get(var_name) or var_default
654 full_query = '%s [Default is %s]: ' % (
655 ask_for_var,
656 default,
657 )
658
659 for _ in range(n_ask_attempts):
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700660 val = get_from_env_or_user_or_default(environ_cp, var_name, full_query,
Austin Anderson6afface2017-12-05 11:59:17 -0800661 default)
662 if check_success(val):
663 break
664 if not suppress_default_error:
665 print(error_msg % val)
666 environ_cp[var_name] = ''
667 else:
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700668 raise UserInputError(
669 'Invalid %s setting was provided %d times in a row. '
670 'Assuming to be a scripting mistake.' % (var_name, n_ask_attempts))
Austin Anderson6afface2017-12-05 11:59:17 -0800671
672 environ_cp[var_name] = val
673 return val
674
675
676def create_android_ndk_rule(environ_cp):
677 """Set ANDROID_NDK_HOME and write Android NDK WORKSPACE rule."""
678 if is_windows() or is_cygwin():
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700679 default_ndk_path = cygpath(
680 '%s/Android/Sdk/ndk-bundle' % environ_cp['APPDATA'])
Austin Anderson6afface2017-12-05 11:59:17 -0800681 elif is_macos():
682 default_ndk_path = '%s/library/Android/Sdk/ndk-bundle' % environ_cp['HOME']
683 else:
684 default_ndk_path = '%s/Android/Sdk/ndk-bundle' % environ_cp['HOME']
685
686 def valid_ndk_path(path):
687 return (os.path.exists(path) and
688 os.path.exists(os.path.join(path, 'source.properties')))
689
690 android_ndk_home_path = prompt_loop_or_load_from_env(
691 environ_cp,
692 var_name='ANDROID_NDK_HOME',
693 var_default=default_ndk_path,
694 ask_for_var='Please specify the home path of the Android NDK to use.',
695 check_success=valid_ndk_path,
696 error_msg=('The path %s or its child file "source.properties" '
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700697 'does not exist.'))
Michael Case51053502018-06-05 17:47:19 -0700698 write_action_env_to_bazelrc('ANDROID_NDK_HOME', android_ndk_home_path)
699 write_action_env_to_bazelrc('ANDROID_NDK_API_LEVEL',
700 check_ndk_level(android_ndk_home_path))
Austin Anderson6afface2017-12-05 11:59:17 -0800701
702
703def create_android_sdk_rule(environ_cp):
704 """Set Android variables and write Android SDK WORKSPACE rule."""
705 if is_windows() or is_cygwin():
706 default_sdk_path = cygpath('%s/Android/Sdk' % environ_cp['APPDATA'])
707 elif is_macos():
Shashi Shekharc0ff0cc2018-07-17 09:00:24 -0700708 default_sdk_path = '%s/library/Android/Sdk' % environ_cp['HOME']
Austin Anderson6afface2017-12-05 11:59:17 -0800709 else:
710 default_sdk_path = '%s/Android/Sdk' % environ_cp['HOME']
711
712 def valid_sdk_path(path):
713 return (os.path.exists(path) and
714 os.path.exists(os.path.join(path, 'platforms')) and
715 os.path.exists(os.path.join(path, 'build-tools')))
716
717 android_sdk_home_path = prompt_loop_or_load_from_env(
718 environ_cp,
719 var_name='ANDROID_SDK_HOME',
720 var_default=default_sdk_path,
721 ask_for_var='Please specify the home path of the Android SDK to use.',
722 check_success=valid_sdk_path,
723 error_msg=('Either %s does not exist, or it does not contain the '
724 'subdirectories "platforms" and "build-tools".'))
725
726 platforms = os.path.join(android_sdk_home_path, 'platforms')
727 api_levels = sorted(os.listdir(platforms))
728 api_levels = [x.replace('android-', '') for x in api_levels]
729
730 def valid_api_level(api_level):
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700731 return os.path.exists(
732 os.path.join(android_sdk_home_path, 'platforms',
733 'android-' + api_level))
Austin Anderson6afface2017-12-05 11:59:17 -0800734
735 android_api_level = prompt_loop_or_load_from_env(
736 environ_cp,
737 var_name='ANDROID_API_LEVEL',
738 var_default=api_levels[-1],
739 ask_for_var=('Please specify the Android SDK API level to use. '
740 '[Available levels: %s]') % api_levels,
741 check_success=valid_api_level,
742 error_msg='Android-%s is not present in the SDK path.')
743
744 build_tools = os.path.join(android_sdk_home_path, 'build-tools')
745 versions = sorted(os.listdir(build_tools))
746
747 def valid_build_tools(version):
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700748 return os.path.exists(
749 os.path.join(android_sdk_home_path, 'build-tools', version))
Austin Anderson6afface2017-12-05 11:59:17 -0800750
751 android_build_tools_version = prompt_loop_or_load_from_env(
752 environ_cp,
753 var_name='ANDROID_BUILD_TOOLS_VERSION',
754 var_default=versions[-1],
755 ask_for_var=('Please specify an Android build tools version to use. '
756 '[Available versions: %s]') % versions,
757 check_success=valid_build_tools,
758 error_msg=('The selected SDK does not have build-tools version %s '
759 'available.'))
760
Michael Case51053502018-06-05 17:47:19 -0700761 write_action_env_to_bazelrc('ANDROID_BUILD_TOOLS_VERSION',
762 android_build_tools_version)
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700763 write_action_env_to_bazelrc('ANDROID_SDK_API_LEVEL', android_api_level)
764 write_action_env_to_bazelrc('ANDROID_SDK_HOME', android_sdk_home_path)
Austin Anderson6afface2017-12-05 11:59:17 -0800765
766
767def check_ndk_level(android_ndk_home_path):
768 """Check the revision number of an Android NDK path."""
769 properties_path = '%s/source.properties' % android_ndk_home_path
770 if is_windows() or is_cygwin():
771 properties_path = cygpath(properties_path)
772 with open(properties_path, 'r') as f:
773 filedata = f.read()
774
775 revision = re.search(r'Pkg.Revision = (\d+)', filedata)
776 if revision:
Michael Case51053502018-06-05 17:47:19 -0700777 ndk_api_level = revision.group(1)
778 else:
779 raise Exception('Unable to parse NDK revision.')
780 if int(ndk_api_level) not in _SUPPORTED_ANDROID_NDK_VERSIONS:
A. Unique TensorFlowered297342019-03-15 11:25:28 -0700781 print(
782 'WARNING: The API level of the NDK in %s is %s, which is not '
783 'supported by Bazel (officially supported versions: %s). Please use '
784 'another version. Compiling Android targets may result in confusing '
785 'errors.\n' %
786 (android_ndk_home_path, ndk_api_level, _SUPPORTED_ANDROID_NDK_VERSIONS))
Michael Case51053502018-06-05 17:47:19 -0700787 return ndk_api_level
Austin Anderson6afface2017-12-05 11:59:17 -0800788
789
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700790def set_gcc_host_compiler_path(environ_cp):
791 """Set GCC_HOST_COMPILER_PATH."""
Jonathan Hseu008910f2017-08-25 14:01:05 -0700792 default_gcc_host_compiler_path = which('gcc') or ''
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700793 cuda_bin_symlink = '%s/bin/gcc' % environ_cp.get('CUDA_TOOLKIT_PATH')
794
795 if os.path.islink(cuda_bin_symlink):
796 # os.readlink is only available in linux
Jonathan Hseu008910f2017-08-25 14:01:05 -0700797 default_gcc_host_compiler_path = os.path.realpath(cuda_bin_symlink)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700798
Austin Anderson6afface2017-12-05 11:59:17 -0800799 gcc_host_compiler_path = prompt_loop_or_load_from_env(
800 environ_cp,
801 var_name='GCC_HOST_COMPILER_PATH',
802 var_default=default_gcc_host_compiler_path,
TensorFlower Gardenerabb763b2019-02-06 16:23:03 -0800803 ask_for_var='Please specify which gcc should be used by nvcc as the host compiler.',
Austin Anderson6afface2017-12-05 11:59:17 -0800804 check_success=os.path.exists,
805 error_msg='Invalid gcc path. %s cannot be found.',
806 )
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700807
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700808 write_action_env_to_bazelrc('GCC_HOST_COMPILER_PATH', gcc_host_compiler_path)
809
810
Ankur Taly0e6f39d2018-02-16 18:22:55 -0800811def reformat_version_sequence(version_str, sequence_count):
812 """Reformat the version string to have the given number of sequences.
813
814 For example:
815 Given (7, 2) -> 7.0
816 (7.0.1, 2) -> 7.0
817 (5, 1) -> 5
818 (5.0.3.2, 1) -> 5
819
820 Args:
821 version_str: String, the version string.
822 sequence_count: int, an integer.
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700823
Ankur Taly0e6f39d2018-02-16 18:22:55 -0800824 Returns:
825 string, reformatted version string.
826 """
827 v = version_str.split('.')
828 if len(v) < sequence_count:
829 v = v + (['0'] * (sequence_count - len(v)))
830
831 return '.'.join(v[:sequence_count])
832
833
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700834def set_tf_cuda_version(environ_cp):
835 """Set CUDA_TOOLKIT_PATH and TF_CUDA_VERSION."""
836 ask_cuda_version = (
A. Unique TensorFlowerb15500b2018-05-08 12:04:38 -0700837 'Please specify the CUDA SDK version you want to use. '
838 '[Leave empty to default to CUDA %s]: ') % _DEFAULT_CUDA_VERSION
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700839
Austin Andersonf9a88f82017-12-13 11:49:40 -0800840 for _ in range(_DEFAULT_PROMPT_ASK_ATTEMPTS):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700841 # Configure the Cuda SDK version to use.
842 tf_cuda_version = get_from_env_or_user_or_default(
843 environ_cp, 'TF_CUDA_VERSION', ask_cuda_version, _DEFAULT_CUDA_VERSION)
Ankur Taly0e6f39d2018-02-16 18:22:55 -0800844 tf_cuda_version = reformat_version_sequence(str(tf_cuda_version), 2)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700845
846 # Find out where the CUDA toolkit is installed
847 default_cuda_path = _DEFAULT_CUDA_PATH
Martin Wicked57572e2017-09-02 19:21:45 -0700848 if is_windows() or is_cygwin():
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700849 default_cuda_path = cygpath(
850 environ_cp.get('CUDA_PATH', _DEFAULT_CUDA_PATH_WIN))
851 elif is_linux():
852 # If the default doesn't exist, try an alternative default.
853 if (not os.path.exists(default_cuda_path)
854 ) and os.path.exists(_DEFAULT_CUDA_PATH_LINUX):
855 default_cuda_path = _DEFAULT_CUDA_PATH_LINUX
856 ask_cuda_path = ('Please specify the location where CUDA %s toolkit is'
857 ' installed. Refer to README.md for more details. '
858 '[Default is %s]: ') % (tf_cuda_version, default_cuda_path)
859 cuda_toolkit_path = get_from_env_or_user_or_default(
860 environ_cp, 'CUDA_TOOLKIT_PATH', ask_cuda_path, default_cuda_path)
A. Unique TensorFlower02f17fe2018-07-07 06:59:19 -0700861 if is_windows() or is_cygwin():
862 cuda_toolkit_path = cygpath(cuda_toolkit_path)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700863
864 if is_windows():
Niall Moranb7d97e82018-08-09 00:29:49 +0100865 cuda_rt_lib_paths = ['lib/x64/cudart.lib']
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700866 elif is_linux():
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700867 cuda_rt_lib_paths = [
868 '%s/libcudart.so.%s' % (x, tf_cuda_version) for x in [
869 'lib64',
870 'lib/powerpc64le-linux-gnu',
871 'lib/x86_64-linux-gnu',
872 ]
873 ]
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700874 elif is_macos():
Niall Moranb7d97e82018-08-09 00:29:49 +0100875 cuda_rt_lib_paths = ['lib/libcudart.%s.dylib' % tf_cuda_version]
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700876
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700877 cuda_toolkit_paths_full = [
878 os.path.join(cuda_toolkit_path, x) for x in cuda_rt_lib_paths
879 ]
Sergei Lebedev95d7bbb2018-11-21 10:40:10 -0800880 if any(os.path.exists(x) for x in cuda_toolkit_paths_full):
Yifei Feng5198cb82018-08-17 13:53:06 -0700881 break
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700882
883 # Reset and retry
884 print('Invalid path to CUDA %s toolkit. %s cannot be found' %
hellcom9a13fc32018-09-12 10:58:24 +0300885 (tf_cuda_version, cuda_toolkit_paths_full))
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700886 environ_cp['TF_CUDA_VERSION'] = ''
887 environ_cp['CUDA_TOOLKIT_PATH'] = ''
888
Austin Andersonf9a88f82017-12-13 11:49:40 -0800889 else:
890 raise UserInputError('Invalid TF_CUDA_SETTING setting was provided %d '
891 'times in a row. Assuming to be a scripting mistake.' %
892 _DEFAULT_PROMPT_ASK_ATTEMPTS)
893
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700894 # Set CUDA_TOOLKIT_PATH and TF_CUDA_VERSION
895 environ_cp['CUDA_TOOLKIT_PATH'] = cuda_toolkit_path
896 write_action_env_to_bazelrc('CUDA_TOOLKIT_PATH', cuda_toolkit_path)
897 environ_cp['TF_CUDA_VERSION'] = tf_cuda_version
898 write_action_env_to_bazelrc('TF_CUDA_VERSION', tf_cuda_version)
899
900
Yifei Fengb1d8c592017-11-22 13:42:21 -0800901def set_tf_cudnn_version(environ_cp):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700902 """Set CUDNN_INSTALL_PATH and TF_CUDNN_VERSION."""
903 ask_cudnn_version = (
Jonathan Hseu008910f2017-08-25 14:01:05 -0700904 'Please specify the cuDNN version you want to use. '
A. Unique TensorFlower44acd832018-10-01 13:42:40 -0700905 '[Leave empty to default to cuDNN %s]: ') % _DEFAULT_CUDNN_VERSION
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700906
Austin Andersonf9a88f82017-12-13 11:49:40 -0800907 for _ in range(_DEFAULT_PROMPT_ASK_ATTEMPTS):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700908 tf_cudnn_version = get_from_env_or_user_or_default(
909 environ_cp, 'TF_CUDNN_VERSION', ask_cudnn_version,
910 _DEFAULT_CUDNN_VERSION)
Ankur Taly0e6f39d2018-02-16 18:22:55 -0800911 tf_cudnn_version = reformat_version_sequence(str(tf_cudnn_version), 1)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700912
913 default_cudnn_path = environ_cp.get('CUDA_TOOLKIT_PATH')
914 ask_cudnn_path = (r'Please specify the location where cuDNN %s library is '
915 'installed. Refer to README.md for more details. [Default'
A. Unique TensorFlower1b212352018-07-19 13:48:50 -0700916 ' is %s]: ') % (tf_cudnn_version, default_cudnn_path)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700917 cudnn_install_path = get_from_env_or_user_or_default(
918 environ_cp, 'CUDNN_INSTALL_PATH', ask_cudnn_path, default_cudnn_path)
919
920 # Result returned from "read" will be used unexpanded. That make "~"
921 # unusable. Going through one more level of expansion to handle that.
922 cudnn_install_path = os.path.realpath(
923 os.path.expanduser(cudnn_install_path))
Martin Wicked57572e2017-09-02 19:21:45 -0700924 if is_windows() or is_cygwin():
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700925 cudnn_install_path = cygpath(cudnn_install_path)
926
927 if is_windows():
928 cuda_dnn_lib_path = 'lib/x64/cudnn.lib'
929 cuda_dnn_lib_alt_path = 'lib/x64/cudnn.lib'
930 elif is_linux():
931 cuda_dnn_lib_path = 'lib64/libcudnn.so.%s' % tf_cudnn_version
932 cuda_dnn_lib_alt_path = 'libcudnn.so.%s' % tf_cudnn_version
933 elif is_macos():
934 cuda_dnn_lib_path = 'lib/libcudnn.%s.dylib' % tf_cudnn_version
935 cuda_dnn_lib_alt_path = 'libcudnn.%s.dylib' % tf_cudnn_version
936
937 cuda_dnn_lib_path_full = os.path.join(cudnn_install_path, cuda_dnn_lib_path)
938 cuda_dnn_lib_alt_path_full = os.path.join(cudnn_install_path,
939 cuda_dnn_lib_alt_path)
940 if os.path.exists(cuda_dnn_lib_path_full) or os.path.exists(
941 cuda_dnn_lib_alt_path_full):
942 break
943
944 # Try another alternative for Linux
945 if is_linux():
Jonathan Hseu008910f2017-08-25 14:01:05 -0700946 ldconfig_bin = which('ldconfig') or '/sbin/ldconfig'
947 cudnn_path_from_ldconfig = run_shell([ldconfig_bin, '-p'])
948 cudnn_path_from_ldconfig = re.search('.*libcudnn.so .* => (.*)',
A. Unique TensorFlowere7223582017-09-06 17:57:04 -0700949 cudnn_path_from_ldconfig)
950 if cudnn_path_from_ldconfig:
951 cudnn_path_from_ldconfig = cudnn_path_from_ldconfig.group(1)
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -0700952 if os.path.exists(
953 '%s.%s' % (cudnn_path_from_ldconfig, tf_cudnn_version)):
A. Unique TensorFlowere7223582017-09-06 17:57:04 -0700954 cudnn_install_path = os.path.dirname(cudnn_path_from_ldconfig)
955 break
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700956
957 # Reset and Retry
958 print(
959 'Invalid path to cuDNN %s toolkit. None of the following files can be '
960 'found:' % tf_cudnn_version)
961 print(cuda_dnn_lib_path_full)
962 print(cuda_dnn_lib_alt_path_full)
963 if is_linux():
964 print('%s.%s' % (cudnn_path_from_ldconfig, tf_cudnn_version))
965
966 environ_cp['TF_CUDNN_VERSION'] = ''
Austin Andersonf9a88f82017-12-13 11:49:40 -0800967 else:
968 raise UserInputError('Invalid TF_CUDNN setting was provided %d '
969 'times in a row. Assuming to be a scripting mistake.' %
970 _DEFAULT_PROMPT_ASK_ATTEMPTS)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700971
972 # Set CUDNN_INSTALL_PATH and TF_CUDNN_VERSION
973 environ_cp['CUDNN_INSTALL_PATH'] = cudnn_install_path
974 write_action_env_to_bazelrc('CUDNN_INSTALL_PATH', cudnn_install_path)
975 environ_cp['TF_CUDNN_VERSION'] = tf_cudnn_version
976 write_action_env_to_bazelrc('TF_CUDNN_VERSION', tf_cudnn_version)
977
978
Mingxing Tan1e7b0e42018-06-28 19:13:20 -0700979def is_cuda_compatible(lib, cuda_ver, cudnn_ver):
980 """Check compatibility between given library and cudnn/cudart libraries."""
981 ldd_bin = which('ldd') or '/usr/bin/ldd'
982 ldd_out = run_shell([ldd_bin, lib], True)
983 ldd_out = ldd_out.split(os.linesep)
984 cudnn_pattern = re.compile('.*libcudnn.so\\.?(.*) =>.*$')
985 cuda_pattern = re.compile('.*libcudart.so\\.?(.*) =>.*$')
986 cudnn = None
987 cudart = None
988 cudnn_ok = True # assume no cudnn dependency by default
989 cuda_ok = True # assume no cuda dependency by default
990 for line in ldd_out:
991 if 'libcudnn.so' in line:
992 cudnn = cudnn_pattern.search(line)
993 cudnn_ok = False
994 elif 'libcudart.so' in line:
995 cudart = cuda_pattern.search(line)
996 cuda_ok = False
997 if cudnn and len(cudnn.group(1)):
998 cudnn = convert_version_to_int(cudnn.group(1))
999 if cudart and len(cudart.group(1)):
1000 cudart = convert_version_to_int(cudart.group(1))
1001 if cudnn is not None:
1002 cudnn_ok = (cudnn == cudnn_ver)
1003 if cudart is not None:
1004 cuda_ok = (cudart == cuda_ver)
1005 return cudnn_ok and cuda_ok
1006
1007
Guangda Lai76f69382018-01-25 23:59:19 -08001008def set_tf_tensorrt_install_path(environ_cp):
1009 """Set TENSORRT_INSTALL_PATH and TF_TENSORRT_VERSION.
1010
1011 Adapted from code contributed by Sami Kama (https://github.com/samikama).
1012
1013 Args:
1014 environ_cp: copy of the os.environ.
1015
1016 Raises:
1017 ValueError: if this method was called under non-Linux platform.
1018 UserInputError: if user has provided invalid input multiple times.
1019 """
1020 if not is_linux():
1021 raise ValueError('Currently TensorRT is only supported on Linux platform.')
1022
1023 # Ask user whether to add TensorRT support.
Mingxing Tan1e7b0e42018-06-28 19:13:20 -07001024 if str(int(get_var(environ_cp, 'TF_NEED_TENSORRT', 'TensorRT',
1025 False))) != '1':
Guangda Lai76f69382018-01-25 23:59:19 -08001026 return
1027
1028 for _ in range(_DEFAULT_PROMPT_ASK_ATTEMPTS):
1029 ask_tensorrt_path = (r'Please specify the location where TensorRT is '
1030 'installed. [Default is %s]:') % (
1031 _DEFAULT_TENSORRT_PATH_LINUX)
1032 trt_install_path = get_from_env_or_user_or_default(
1033 environ_cp, 'TENSORRT_INSTALL_PATH', ask_tensorrt_path,
1034 _DEFAULT_TENSORRT_PATH_LINUX)
1035
1036 # Result returned from "read" will be used unexpanded. That make "~"
1037 # unusable. Going through one more level of expansion to handle that.
Mingxing Tan1e7b0e42018-06-28 19:13:20 -07001038 trt_install_path = os.path.realpath(os.path.expanduser(trt_install_path))
Guangda Lai76f69382018-01-25 23:59:19 -08001039
1040 def find_libs(search_path):
1041 """Search for libnvinfer.so in "search_path"."""
1042 fl = set()
1043 if os.path.exists(search_path) and os.path.isdir(search_path):
Mingxing Tan1e7b0e42018-06-28 19:13:20 -07001044 fl.update([
1045 os.path.realpath(os.path.join(search_path, x))
1046 for x in os.listdir(search_path)
1047 if 'libnvinfer.so' in x
1048 ])
Guangda Lai76f69382018-01-25 23:59:19 -08001049 return fl
1050
1051 possible_files = find_libs(trt_install_path)
1052 possible_files.update(find_libs(os.path.join(trt_install_path, 'lib')))
1053 possible_files.update(find_libs(os.path.join(trt_install_path, 'lib64')))
Guangda Lai76f69382018-01-25 23:59:19 -08001054 cuda_ver = convert_version_to_int(environ_cp['TF_CUDA_VERSION'])
1055 cudnn_ver = convert_version_to_int(environ_cp['TF_CUDNN_VERSION'])
1056 nvinfer_pattern = re.compile('.*libnvinfer.so.?(.*)$')
1057 highest_ver = [0, None, None]
1058
1059 for lib_file in possible_files:
Mingxing Tan1e7b0e42018-06-28 19:13:20 -07001060 if is_cuda_compatible(lib_file, cuda_ver, cudnn_ver):
Jacques Pienaar2d0531d2018-03-21 12:07:51 -07001061 matches = nvinfer_pattern.search(lib_file)
TensorFlower Gardener61a87202018-10-01 12:25:39 -07001062 if not matches.groups():
Jacques Pienaar2d0531d2018-03-21 12:07:51 -07001063 continue
1064 ver_str = matches.group(1)
Guangda Lai76f69382018-01-25 23:59:19 -08001065 ver = convert_version_to_int(ver_str) if len(ver_str) else 0
1066 if ver > highest_ver[0]:
1067 highest_ver = [ver, ver_str, lib_file]
1068 if highest_ver[1] is not None:
1069 trt_install_path = os.path.dirname(highest_ver[2])
1070 tf_tensorrt_version = highest_ver[1]
1071 break
1072
1073 # Try another alternative from ldconfig.
1074 ldconfig_bin = which('ldconfig') or '/sbin/ldconfig'
1075 ldconfig_output = run_shell([ldconfig_bin, '-p'])
Mingxing Tan1e7b0e42018-06-28 19:13:20 -07001076 search_result = re.search('.*libnvinfer.so\\.?([0-9.]*).* => (.*)',
1077 ldconfig_output)
Guangda Lai76f69382018-01-25 23:59:19 -08001078 if search_result:
1079 libnvinfer_path_from_ldconfig = search_result.group(2)
1080 if os.path.exists(libnvinfer_path_from_ldconfig):
Mingxing Tan1e7b0e42018-06-28 19:13:20 -07001081 if is_cuda_compatible(libnvinfer_path_from_ldconfig, cuda_ver,
1082 cudnn_ver):
Guangda Lai76f69382018-01-25 23:59:19 -08001083 trt_install_path = os.path.dirname(libnvinfer_path_from_ldconfig)
1084 tf_tensorrt_version = search_result.group(1)
1085 break
1086
1087 # Reset and Retry
Yifei Fengdce9a492018-02-22 14:24:57 -08001088 if possible_files:
1089 print('TensorRT libraries found in one the following directories',
1090 'are not compatible with selected cuda and cudnn installations')
1091 print(trt_install_path)
1092 print(os.path.join(trt_install_path, 'lib'))
1093 print(os.path.join(trt_install_path, 'lib64'))
1094 if search_result:
1095 print(libnvinfer_path_from_ldconfig)
1096 else:
1097 print(
1098 'Invalid path to TensorRT. None of the following files can be found:')
1099 print(trt_install_path)
1100 print(os.path.join(trt_install_path, 'lib'))
1101 print(os.path.join(trt_install_path, 'lib64'))
1102 if search_result:
1103 print(libnvinfer_path_from_ldconfig)
Guangda Lai76f69382018-01-25 23:59:19 -08001104
1105 else:
1106 raise UserInputError('Invalid TF_TENSORRT setting was provided %d '
1107 'times in a row. Assuming to be a scripting mistake.' %
1108 _DEFAULT_PROMPT_ASK_ATTEMPTS)
1109
1110 # Set TENSORRT_INSTALL_PATH and TF_TENSORRT_VERSION
1111 environ_cp['TENSORRT_INSTALL_PATH'] = trt_install_path
1112 write_action_env_to_bazelrc('TENSORRT_INSTALL_PATH', trt_install_path)
1113 environ_cp['TF_TENSORRT_VERSION'] = tf_tensorrt_version
1114 write_action_env_to_bazelrc('TF_TENSORRT_VERSION', tf_tensorrt_version)
1115
1116
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001117def set_tf_nccl_install_path(environ_cp):
Jason Furmanek7c234152018-09-26 04:44:12 +00001118 """Set NCCL_INSTALL_PATH, NCCL_HDR_PATH and TF_NCCL_VERSION.
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001119
1120 Args:
1121 environ_cp: copy of the os.environ.
1122
1123 Raises:
1124 ValueError: if this method was called under non-Linux platform.
1125 UserInputError: if user has provided invalid input multiple times.
1126 """
1127 if not is_linux():
1128 raise ValueError('Currently NCCL is only supported on Linux platforms.')
1129
1130 ask_nccl_version = (
A. Unique TensorFlower53faa312018-10-05 08:46:54 -07001131 'Please specify the locally installed NCCL version you want to use. '
1132 '[Default is to use https://github.com/nvidia/nccl]: ')
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001133
1134 for _ in range(_DEFAULT_PROMPT_ASK_ATTEMPTS):
1135 tf_nccl_version = get_from_env_or_user_or_default(
A. Unique TensorFlower53faa312018-10-05 08:46:54 -07001136 environ_cp, 'TF_NCCL_VERSION', ask_nccl_version, '')
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001137
A. Unique TensorFlower53faa312018-10-05 08:46:54 -07001138 if not tf_nccl_version:
1139 break # No need to get install path, building the open source code.
1140
1141 tf_nccl_version = reformat_version_sequence(str(tf_nccl_version), 1)
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001142
Jason Furmanek7c234152018-09-26 04:44:12 +00001143 # Look with ldconfig first if we can find the library in paths
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001144 # like /usr/lib/x86_64-linux-gnu and the header file in the corresponding
1145 # include directory. This is where the NCCL .deb packages install them.
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001146
Jason Furmanek7c234152018-09-26 04:44:12 +00001147 # First check to see if NCCL is in the ldconfig.
1148 # If its found, use that location.
1149 if is_linux():
1150 ldconfig_bin = which('ldconfig') or '/sbin/ldconfig'
1151 nccl2_path_from_ldconfig = run_shell([ldconfig_bin, '-p'])
1152 nccl2_path_from_ldconfig = re.search('.*libnccl.so .* => (.*)',
1153 nccl2_path_from_ldconfig)
1154 if nccl2_path_from_ldconfig:
1155 nccl2_path_from_ldconfig = nccl2_path_from_ldconfig.group(1)
1156 if os.path.exists('%s.%s' % (nccl2_path_from_ldconfig, tf_nccl_version)):
1157 nccl_install_path = os.path.dirname(nccl2_path_from_ldconfig)
1158 print('NCCL libraries found in ' + nccl2_path_from_ldconfig)
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001159
Jason Furmanek7c234152018-09-26 04:44:12 +00001160 # Check if this is the main system lib location
1161 if re.search('.*linux-gnu', nccl_install_path):
TensorFlower Gardenerea5c5292018-10-01 17:28:26 -07001162 trunc_nccl_install_path = '/usr'
1163 print('This looks like a system path.')
Jason Furmanek7c234152018-09-26 04:44:12 +00001164 else:
TensorFlower Gardenerea5c5292018-10-01 17:28:26 -07001165 trunc_nccl_install_path = nccl_install_path + '/..'
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001166
Jason Furmanek7c234152018-09-26 04:44:12 +00001167 # Look for header
TensorFlower Gardenerea5c5292018-10-01 17:28:26 -07001168 nccl_hdr_path = trunc_nccl_install_path + '/include'
1169 print('Assuming NCCL header path is ' + nccl_hdr_path)
1170 if os.path.exists(nccl_hdr_path + '/nccl.h'):
Jason Furmanek7c234152018-09-26 04:44:12 +00001171 # Set NCCL_INSTALL_PATH
1172 environ_cp['NCCL_INSTALL_PATH'] = nccl_install_path
1173 write_action_env_to_bazelrc('NCCL_INSTALL_PATH', nccl_install_path)
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001174
Jason Furmanek7c234152018-09-26 04:44:12 +00001175 # Set NCCL_HDR_PATH
1176 environ_cp['NCCL_HDR_PATH'] = nccl_hdr_path
1177 write_action_env_to_bazelrc('NCCL_HDR_PATH', nccl_hdr_path)
1178 break
1179 else:
TensorFlower Gardenerea5c5292018-10-01 17:28:26 -07001180 print(
1181 'The header for NCCL2 cannot be found. Please install the libnccl-dev package.'
1182 )
Jason Furmanek7c234152018-09-26 04:44:12 +00001183 else:
TensorFlower Gardenerea5c5292018-10-01 17:28:26 -07001184 print('NCCL2 is listed by ldconfig but the library is not found. '
1185 'Your ldconfig is out of date. Please run sudo ldconfig.')
Jason Furmanek7c234152018-09-26 04:44:12 +00001186 else:
1187 # NCCL is not found in ldconfig. Ask the user for the location.
1188 default_nccl_path = environ_cp.get('CUDA_TOOLKIT_PATH')
TensorFlower Gardenerea5c5292018-10-01 17:28:26 -07001189 ask_nccl_path = (
1190 r'Please specify the location where NCCL %s library is '
1191 'installed. Refer to README.md for more details. [Default '
1192 'is %s]:') % (tf_nccl_version, default_nccl_path)
Jason Furmanek7c234152018-09-26 04:44:12 +00001193 nccl_install_path = get_from_env_or_user_or_default(
TensorFlower Gardenerea5c5292018-10-01 17:28:26 -07001194 environ_cp, 'NCCL_INSTALL_PATH', ask_nccl_path, default_nccl_path)
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001195
Jason Furmanek7c234152018-09-26 04:44:12 +00001196 # Result returned from "read" will be used unexpanded. That make "~"
1197 # unusable. Going through one more level of expansion to handle that.
TensorFlower Gardenerea5c5292018-10-01 17:28:26 -07001198 nccl_install_path = os.path.realpath(
1199 os.path.expanduser(nccl_install_path))
Jason Furmanek7c234152018-09-26 04:44:12 +00001200 if is_windows() or is_cygwin():
1201 nccl_install_path = cygpath(nccl_install_path)
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001202
Guangda Lai62ebf622018-10-23 07:44:13 -07001203 nccl_lib_path = ''
Jason Furmanek7c234152018-09-26 04:44:12 +00001204 if is_windows():
1205 nccl_lib_path = 'lib/x64/nccl.lib'
1206 elif is_linux():
1207 nccl_lib_filename = 'libnccl.so.%s' % tf_nccl_version
1208 nccl_lpath = '%s/lib/%s' % (nccl_install_path, nccl_lib_filename)
1209 if not os.path.exists(nccl_lpath):
1210 for relative_path in NCCL_LIB_PATHS:
TensorFlower Gardenerea5c5292018-10-01 17:28:26 -07001211 path = '%s/%s%s' % (nccl_install_path, relative_path,
1212 nccl_lib_filename)
Jason Furmanek7c234152018-09-26 04:44:12 +00001213 if os.path.exists(path):
TensorFlower Gardenerea5c5292018-10-01 17:28:26 -07001214 print('NCCL found at ' + path)
Jason Furmanek7c234152018-09-26 04:44:12 +00001215 nccl_lib_path = path
1216 break
1217 else:
1218 nccl_lib_path = nccl_lpath
1219 elif is_macos():
1220 nccl_lib_path = 'lib/libnccl.%s.dylib' % tf_nccl_version
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001221
Jason Furmanek7c234152018-09-26 04:44:12 +00001222 nccl_lib_path = os.path.join(nccl_install_path, nccl_lib_path)
TensorFlower Gardenerea5c5292018-10-01 17:28:26 -07001223 nccl_hdr_path = os.path.join(
1224 os.path.dirname(nccl_lib_path), '../include/nccl.h')
1225 print('Assuming NCCL header path is ' + nccl_hdr_path)
Jason Furmanek7c234152018-09-26 04:44:12 +00001226 if os.path.exists(nccl_lib_path) and os.path.exists(nccl_hdr_path):
1227 # Set NCCL_INSTALL_PATH
1228 environ_cp['NCCL_INSTALL_PATH'] = os.path.dirname(nccl_lib_path)
TensorFlower Gardenerea5c5292018-10-01 17:28:26 -07001229 write_action_env_to_bazelrc('NCCL_INSTALL_PATH',
1230 os.path.dirname(nccl_lib_path))
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001231
Jason Furmanek7c234152018-09-26 04:44:12 +00001232 # Set NCCL_HDR_PATH
1233 environ_cp['NCCL_HDR_PATH'] = os.path.dirname(nccl_hdr_path)
TensorFlower Gardenerea5c5292018-10-01 17:28:26 -07001234 write_action_env_to_bazelrc('NCCL_HDR_PATH',
1235 os.path.dirname(nccl_hdr_path))
Jason Furmanek7c234152018-09-26 04:44:12 +00001236 break
1237
1238 # Reset and Retry
TensorFlower Gardenerea5c5292018-10-01 17:28:26 -07001239 print(
1240 'Invalid path to NCCL %s toolkit, %s or %s not found. Please use the '
A. Unique TensorFlowered297342019-03-15 11:25:28 -07001241 'O/S agnostic package of NCCL 2' %
1242 (tf_nccl_version, nccl_lib_path, nccl_hdr_path))
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001243
Jason Furmanek7c234152018-09-26 04:44:12 +00001244 environ_cp['TF_NCCL_VERSION'] = ''
A. Unique TensorFlower1fda7642018-04-05 03:09:27 -07001245 else:
1246 raise UserInputError('Invalid TF_NCCL setting was provided %d '
1247 'times in a row. Assuming to be a scripting mistake.' %
1248 _DEFAULT_PROMPT_ASK_ATTEMPTS)
1249
1250 # Set TF_NCCL_VERSION
1251 environ_cp['TF_NCCL_VERSION'] = tf_nccl_version
1252 write_action_env_to_bazelrc('TF_NCCL_VERSION', tf_nccl_version)
1253
TensorFlower Gardenerabb763b2019-02-06 16:23:03 -08001254
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001255def get_native_cuda_compute_capabilities(environ_cp):
1256 """Get native cuda compute capabilities.
1257
1258 Args:
1259 environ_cp: copy of the os.environ.
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -07001260
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001261 Returns:
1262 string of native cuda compute capabilities, separated by comma.
1263 """
1264 device_query_bin = os.path.join(
1265 environ_cp.get('CUDA_TOOLKIT_PATH'), 'extras/demo_suite/deviceQuery')
Jonathan Hseu008910f2017-08-25 14:01:05 -07001266 if os.path.isfile(device_query_bin) and os.access(device_query_bin, os.X_OK):
1267 try:
1268 output = run_shell(device_query_bin).split('\n')
1269 pattern = re.compile('[0-9]*\\.[0-9]*')
1270 output = [pattern.search(x) for x in output if 'Capability' in x]
1271 output = ','.join(x.group() for x in output if x is not None)
1272 except subprocess.CalledProcessError:
1273 output = ''
1274 else:
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001275 output = ''
1276 return output
1277
1278
1279def set_tf_cuda_compute_capabilities(environ_cp):
1280 """Set TF_CUDA_COMPUTE_CAPABILITIES."""
1281 while True:
1282 native_cuda_compute_capabilities = get_native_cuda_compute_capabilities(
1283 environ_cp)
1284 if not native_cuda_compute_capabilities:
1285 default_cuda_compute_capabilities = _DEFAULT_CUDA_COMPUTE_CAPABILITIES
1286 else:
1287 default_cuda_compute_capabilities = native_cuda_compute_capabilities
1288
1289 ask_cuda_compute_capabilities = (
1290 'Please specify a list of comma-separated '
P Sudeepam52093562019-02-17 17:34:01 +05301291 'CUDA compute capabilities you want to '
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001292 'build with.\nYou can find the compute '
1293 'capability of your device at: '
1294 'https://developer.nvidia.com/cuda-gpus.\nPlease'
1295 ' note that each additional compute '
1296 'capability significantly increases your '
P Sudeepam52093562019-02-17 17:34:01 +05301297 'build time and binary size, and that '
1298 'TensorFlow only supports compute '
P Sudeepam765ceda2019-02-17 17:39:08 +05301299 'capabilities >= 3.5 [Default is: %s]: ' %
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001300 default_cuda_compute_capabilities)
1301 tf_cuda_compute_capabilities = get_from_env_or_user_or_default(
1302 environ_cp, 'TF_CUDA_COMPUTE_CAPABILITIES',
1303 ask_cuda_compute_capabilities, default_cuda_compute_capabilities)
1304 # Check whether all capabilities from the input is valid
1305 all_valid = True
Maciejd0f5bc12018-04-30 22:30:58 -05001306 # Remove all whitespace characters before splitting the string
Michael Case51053502018-06-05 17:47:19 -07001307 # that users may insert by accident, as this will result in error
Maciejd0f5bc12018-04-30 22:30:58 -05001308 tf_cuda_compute_capabilities = ''.join(tf_cuda_compute_capabilities.split())
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001309 for compute_capability in tf_cuda_compute_capabilities.split(','):
Andrew Harp6e3e7d12017-08-21 12:10:44 -07001310 m = re.match('[0-9]+.[0-9]+', compute_capability)
1311 if not m:
Austin Anderson32202dc2019-02-19 10:46:27 -08001312 print('Invalid compute capability: %s' % compute_capability)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001313 all_valid = False
Andrew Harp6e3e7d12017-08-21 12:10:44 -07001314 else:
P Sudeepam52093562019-02-17 17:34:01 +05301315 ver = float(m.group(0))
A. Unique TensorFlower8dc2d0e2019-03-12 01:41:05 -07001316 if ver < 3.0:
1317 print('ERROR: TensorFlow only supports CUDA compute capabilities 3.0 '
Austin Anderson32202dc2019-02-19 10:46:27 -08001318 'and higher. Please re-specify the list of compute '
1319 'capabilities excluding version %s.' % ver)
Andrew Harp6e3e7d12017-08-21 12:10:44 -07001320 all_valid = False
A. Unique TensorFlower8dc2d0e2019-03-12 01:41:05 -07001321 if ver < 3.5:
1322 print('WARNING: XLA does not support CUDA compute capabilities '
1323 'lower than 3.5. Disable XLA when running on older GPUs.')
P Sudeepam765ceda2019-02-17 17:39:08 +05301324
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001325 if all_valid:
1326 break
1327
1328 # Reset and Retry
1329 environ_cp['TF_CUDA_COMPUTE_CAPABILITIES'] = ''
1330
1331 # Set TF_CUDA_COMPUTE_CAPABILITIES
1332 environ_cp['TF_CUDA_COMPUTE_CAPABILITIES'] = tf_cuda_compute_capabilities
1333 write_action_env_to_bazelrc('TF_CUDA_COMPUTE_CAPABILITIES',
1334 tf_cuda_compute_capabilities)
1335
1336
1337def set_other_cuda_vars(environ_cp):
1338 """Set other CUDA related variables."""
A. Unique TensorFlowerab391982018-07-11 04:52:49 -07001339 # If CUDA is enabled, always use GPU during build and test.
1340 if environ_cp.get('TF_CUDA_CLANG') == '1':
1341 write_to_bazelrc('build --config=cuda_clang')
1342 write_to_bazelrc('test --config=cuda_clang')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001343 else:
A. Unique TensorFlowerab391982018-07-11 04:52:49 -07001344 write_to_bazelrc('build --config=cuda')
1345 write_to_bazelrc('test --config=cuda')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001346
1347
1348def set_host_cxx_compiler(environ_cp):
1349 """Set HOST_CXX_COMPILER."""
Jonathan Hseu008910f2017-08-25 14:01:05 -07001350 default_cxx_host_compiler = which('g++') or ''
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001351
Austin Anderson6afface2017-12-05 11:59:17 -08001352 host_cxx_compiler = prompt_loop_or_load_from_env(
1353 environ_cp,
1354 var_name='HOST_CXX_COMPILER',
1355 var_default=default_cxx_host_compiler,
1356 ask_for_var=('Please specify which C++ compiler should be used as the '
1357 'host C++ compiler.'),
1358 check_success=os.path.exists,
1359 error_msg='Invalid C++ compiler path. %s cannot be found.',
1360 )
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001361
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001362 write_action_env_to_bazelrc('HOST_CXX_COMPILER', host_cxx_compiler)
1363
1364
1365def set_host_c_compiler(environ_cp):
1366 """Set HOST_C_COMPILER."""
Jonathan Hseu008910f2017-08-25 14:01:05 -07001367 default_c_host_compiler = which('gcc') or ''
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001368
Austin Anderson6afface2017-12-05 11:59:17 -08001369 host_c_compiler = prompt_loop_or_load_from_env(
1370 environ_cp,
1371 var_name='HOST_C_COMPILER',
1372 var_default=default_c_host_compiler,
Shanqing Cai71445712018-03-12 19:33:52 -07001373 ask_for_var=('Please specify which C compiler should be used as the host '
Austin Anderson6afface2017-12-05 11:59:17 -08001374 'C compiler.'),
1375 check_success=os.path.exists,
1376 error_msg='Invalid C compiler path. %s cannot be found.',
1377 )
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001378
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001379 write_action_env_to_bazelrc('HOST_C_COMPILER', host_c_compiler)
1380
1381
1382def set_computecpp_toolkit_path(environ_cp):
1383 """Set COMPUTECPP_TOOLKIT_PATH."""
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001384
Austin Anderson6afface2017-12-05 11:59:17 -08001385 def toolkit_exists(toolkit_path):
1386 """Check if a computecpp toolkit path is valid."""
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001387 if is_linux():
1388 sycl_rt_lib_path = 'lib/libComputeCpp.so'
1389 else:
1390 sycl_rt_lib_path = ''
1391
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -07001392 sycl_rt_lib_path_full = os.path.join(toolkit_path, sycl_rt_lib_path)
Austin Anderson6afface2017-12-05 11:59:17 -08001393 exists = os.path.exists(sycl_rt_lib_path_full)
1394 if not exists:
1395 print('Invalid SYCL %s library path. %s cannot be found' %
1396 (_TF_OPENCL_VERSION, sycl_rt_lib_path_full))
1397 return exists
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001398
Austin Anderson6afface2017-12-05 11:59:17 -08001399 computecpp_toolkit_path = prompt_loop_or_load_from_env(
1400 environ_cp,
1401 var_name='COMPUTECPP_TOOLKIT_PATH',
1402 var_default=_DEFAULT_COMPUTECPP_TOOLKIT_PATH,
1403 ask_for_var=(
1404 'Please specify the location where ComputeCpp for SYCL %s is '
1405 'installed.' % _TF_OPENCL_VERSION),
1406 check_success=toolkit_exists,
1407 error_msg='Invalid SYCL compiler path. %s cannot be found.',
1408 suppress_default_error=True)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001409
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001410 write_action_env_to_bazelrc('COMPUTECPP_TOOLKIT_PATH',
1411 computecpp_toolkit_path)
1412
Michael Cased31531a2018-01-05 14:09:41 -08001413
Dandelion Man?90e42f32017-12-15 18:15:07 -08001414def set_trisycl_include_dir(environ_cp):
Michael Cased31531a2018-01-05 14:09:41 -08001415 """Set TRISYCL_INCLUDE_DIR."""
Frank Chenc4ef9272018-01-10 11:36:52 -08001416
Dandelion Man?90e42f32017-12-15 18:15:07 -08001417 ask_trisycl_include_dir = ('Please specify the location of the triSYCL '
1418 'include directory. (Use --config=sycl_trisycl '
1419 'when building with Bazel) '
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -07001420 '[Default is %s]: ') % (
1421 _DEFAULT_TRISYCL_INCLUDE_DIR)
Frank Chenc4ef9272018-01-10 11:36:52 -08001422
Dandelion Man?90e42f32017-12-15 18:15:07 -08001423 while True:
1424 trisycl_include_dir = get_from_env_or_user_or_default(
Michael Cased31531a2018-01-05 14:09:41 -08001425 environ_cp, 'TRISYCL_INCLUDE_DIR', ask_trisycl_include_dir,
1426 _DEFAULT_TRISYCL_INCLUDE_DIR)
Dandelion Man?90e42f32017-12-15 18:15:07 -08001427 if os.path.exists(trisycl_include_dir):
1428 break
1429
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -07001430 print('Invalid triSYCL include directory, %s cannot be found' %
1431 (trisycl_include_dir))
Dandelion Man?90e42f32017-12-15 18:15:07 -08001432
1433 # Set TRISYCL_INCLUDE_DIR
1434 environ_cp['TRISYCL_INCLUDE_DIR'] = trisycl_include_dir
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -07001435 write_action_env_to_bazelrc('TRISYCL_INCLUDE_DIR', trisycl_include_dir)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001436
Yifei Fengb1d8c592017-11-22 13:42:21 -08001437
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001438def set_mpi_home(environ_cp):
1439 """Set MPI_HOME."""
Austin Anderson6afface2017-12-05 11:59:17 -08001440
Jonathan Hseu008910f2017-08-25 14:01:05 -07001441 default_mpi_home = which('mpirun') or which('mpiexec') or ''
1442 default_mpi_home = os.path.dirname(os.path.dirname(default_mpi_home))
1443
Austin Anderson6afface2017-12-05 11:59:17 -08001444 def valid_mpi_path(mpi_home):
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -07001445 exists = (
1446 os.path.exists(os.path.join(mpi_home, 'include')) and
TensorFlower Gardenerf7c861f2018-11-01 11:29:40 -07001447 (os.path.exists(os.path.join(mpi_home, 'lib')) or
1448 os.path.exists(os.path.join(mpi_home, 'lib64')) or
1449 os.path.exists(os.path.join(mpi_home, 'lib32'))))
Austin Anderson6afface2017-12-05 11:59:17 -08001450 if not exists:
TensorFlower Gardenerf7c861f2018-11-01 11:29:40 -07001451 print(
1452 'Invalid path to the MPI Toolkit. %s or %s or %s or %s cannot be found'
1453 % (os.path.join(mpi_home, 'include'),
Christian Gollba95d092018-10-04 17:06:23 +02001454 os.path.exists(os.path.join(mpi_home, 'lib')),
1455 os.path.exists(os.path.join(mpi_home, 'lib64')),
1456 os.path.exists(os.path.join(mpi_home, 'lib32'))))
Austin Anderson6afface2017-12-05 11:59:17 -08001457 return exists
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001458
Austin Anderson6afface2017-12-05 11:59:17 -08001459 _ = prompt_loop_or_load_from_env(
1460 environ_cp,
1461 var_name='MPI_HOME',
1462 var_default=default_mpi_home,
1463 ask_for_var='Please specify the MPI toolkit folder.',
1464 check_success=valid_mpi_path,
1465 error_msg='',
1466 suppress_default_error=True)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001467
1468
1469def set_other_mpi_vars(environ_cp):
1470 """Set other MPI related variables."""
1471 # Link the MPI header files
1472 mpi_home = environ_cp.get('MPI_HOME')
1473 symlink_force('%s/include/mpi.h' % mpi_home, 'third_party/mpi/mpi.h')
1474
1475 # Determine if we use OpenMPI or MVAPICH, these require different header files
1476 # to be included here to make bazel dependency checker happy
1477 if os.path.exists(os.path.join(mpi_home, 'include/mpi_portable_platform.h')):
1478 symlink_force(
1479 os.path.join(mpi_home, 'include/mpi_portable_platform.h'),
1480 'third_party/mpi/mpi_portable_platform.h')
1481 # TODO(gunan): avoid editing files in configure
1482 sed_in_place('third_party/mpi/mpi.bzl', 'MPI_LIB_IS_OPENMPI=False',
1483 'MPI_LIB_IS_OPENMPI=True')
1484 else:
1485 # MVAPICH / MPICH
1486 symlink_force(
1487 os.path.join(mpi_home, 'include/mpio.h'), 'third_party/mpi/mpio.h')
1488 symlink_force(
1489 os.path.join(mpi_home, 'include/mpicxx.h'), 'third_party/mpi/mpicxx.h')
1490 # TODO(gunan): avoid editing files in configure
1491 sed_in_place('third_party/mpi/mpi.bzl', 'MPI_LIB_IS_OPENMPI=True',
1492 'MPI_LIB_IS_OPENMPI=False')
1493
1494 if os.path.exists(os.path.join(mpi_home, 'lib/libmpi.so')):
1495 symlink_force(
1496 os.path.join(mpi_home, 'lib/libmpi.so'), 'third_party/mpi/libmpi.so')
Christian Gollba95d092018-10-04 17:06:23 +02001497 elif os.path.exists(os.path.join(mpi_home, 'lib64/libmpi.so')):
1498 symlink_force(
1499 os.path.join(mpi_home, 'lib64/libmpi.so'), 'third_party/mpi/libmpi.so')
1500 elif os.path.exists(os.path.join(mpi_home, 'lib32/libmpi.so')):
1501 symlink_force(
1502 os.path.join(mpi_home, 'lib32/libmpi.so'), 'third_party/mpi/libmpi.so')
1503
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001504 else:
TensorFlower Gardenerf7c861f2018-11-01 11:29:40 -07001505 raise ValueError(
1506 'Cannot find the MPI library file in %s/lib or %s/lib64 or %s/lib32' %
Mihai Maruseac91ebeec2019-01-29 17:07:38 -08001507 (mpi_home, mpi_home, mpi_home))
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001508
A. Unique TensorFlowered297342019-03-15 11:25:28 -07001509
A. Unique TensorFlower7bd86372019-03-21 15:19:30 -07001510def system_specific_config(env):
1511 """Add default build and test flags required for TF tests to bazelrc."""
Gunhan Gulsoyfff66962019-02-20 15:28:43 -08001512 write_to_bazelrc('test --flaky_test_attempts=3')
1513 write_to_bazelrc('test --test_size_filters=small,medium')
1514 write_to_bazelrc(
1515 'test --test_tag_filters=-benchmark-test,-no_oss,-oss_serial')
1516 write_to_bazelrc('test --build_tag_filters=-benchmark-test,-no_oss')
1517 if is_windows():
Guangda Laibcd701a2019-03-12 21:04:51 -07001518 if env.get('TF_NEED_CUDA', None) == '1':
Gunhan Gulsoyfff66962019-02-20 15:28:43 -08001519 write_to_bazelrc(
1520 'test --test_tag_filters=-no_windows,-no_windows_gpu,-no_gpu')
1521 write_to_bazelrc(
1522 'test --build_tag_filters=-no_windows,-no_windows_gpu,-no_gpu')
1523 else:
1524 write_to_bazelrc('test --test_tag_filters=-no_windows,-gpu')
1525 write_to_bazelrc('test --build_tag_filters=-no_windows,-gpu')
1526 elif is_macos():
1527 write_to_bazelrc('test --test_tag_filters=-gpu,-nomac,-no_mac')
1528 write_to_bazelrc('test --build_tag_filters=-gpu,-nomac,-no_mac')
A. Unique TensorFlower7bd86372019-03-21 15:19:30 -07001529 # TODO(pcloudy): Remove BAZEL_USE_CPP_ONLY_TOOLCHAIN after Bazel is upgraded
1530 # to 0.24.0.
1531 # For working around https://github.com/bazelbuild/bazel/issues/7607
1532 write_to_bazelrc('build --action_env=BAZEL_USE_CPP_ONLY_TOOLCHAIN=1')
Gunhan Gulsoyfff66962019-02-20 15:28:43 -08001533 elif is_linux():
Guangda Laibcd701a2019-03-12 21:04:51 -07001534 if env.get('TF_NEED_CUDA', None) == '1':
Gunhan Gulsoyfff66962019-02-20 15:28:43 -08001535 write_to_bazelrc('test --test_tag_filters=-no_gpu')
1536 write_to_bazelrc('test --build_tag_filters=-no_gpu')
1537 write_to_bazelrc('test --test_env=LD_LIBRARY_PATH')
1538 else:
1539 write_to_bazelrc('test --test_tag_filters=-gpu')
1540 write_to_bazelrc('test --build_tag_filters=-gpu')
1541
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001542
Yifei Feng5198cb82018-08-17 13:53:06 -07001543def set_system_libs_flag(environ_cp):
1544 syslibs = environ_cp.get('TF_SYSTEM_LIBS', '')
TensorFlower Gardener61a87202018-10-01 12:25:39 -07001545 if syslibs:
Jason Zaman5fc39bd2018-09-16 01:38:55 +08001546 if ',' in syslibs:
1547 syslibs = ','.join(sorted(syslibs.split(',')))
1548 else:
1549 syslibs = ','.join(sorted(syslibs.split()))
Yifei Feng5198cb82018-08-17 13:53:06 -07001550 write_action_env_to_bazelrc('TF_SYSTEM_LIBS', syslibs)
1551
Jason Zaman5fc39bd2018-09-16 01:38:55 +08001552 if 'PREFIX' in environ_cp:
1553 write_to_bazelrc('build --define=PREFIX=%s' % environ_cp['PREFIX'])
1554 if 'LIBDIR' in environ_cp:
1555 write_to_bazelrc('build --define=LIBDIR=%s' % environ_cp['LIBDIR'])
1556 if 'INCLUDEDIR' in environ_cp:
1557 write_to_bazelrc('build --define=INCLUDEDIR=%s' % environ_cp['INCLUDEDIR'])
1558
Yifei Feng5198cb82018-08-17 13:53:06 -07001559
A. Unique TensorFlower1b212352018-07-19 13:48:50 -07001560def set_windows_build_flags(environ_cp):
1561 """Set Windows specific build options."""
1562 # The non-monolithic build is not supported yet
1563 write_to_bazelrc('build --config monolithic')
1564 # Suppress warning messages
1565 write_to_bazelrc('build --copt=-w --host_copt=-w')
Loo Rong Jie31f10d22019-02-02 10:03:20 +08001566 # Fix winsock2.h conflicts
TensorFlower Gardener345cccf2019-02-28 15:22:59 -08001567 write_to_bazelrc(
1568 'build --copt=-DWIN32_LEAN_AND_MEAN --host_copt=-DWIN32_LEAN_AND_MEAN')
A. Unique TensorFlower1b212352018-07-19 13:48:50 -07001569 # Output more verbose information when something goes wrong
1570 write_to_bazelrc('build --verbose_failures')
1571 # The host and target platforms are the same in Windows build. So we don't
1572 # have to distinct them. This avoids building the same targets twice.
1573 write_to_bazelrc('build --distinct_host_configuration=false')
A. Unique TensorFlower1b212352018-07-19 13:48:50 -07001574
1575 if get_var(
1576 environ_cp, 'TF_OVERRIDE_EIGEN_STRONG_INLINE', 'Eigen strong inline',
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -07001577 True, ('Would you like to override eigen strong inline for some C++ '
1578 'compilation to reduce the compilation time?'),
1579 'Eigen strong inline overridden.', 'Not overriding eigen strong inline, '
A. Unique TensorFlower1b212352018-07-19 13:48:50 -07001580 'some compilations could take more than 20 mins.'):
1581 # Due to a known MSVC compiler issue
1582 # https://github.com/tensorflow/tensorflow/issues/10521
1583 # Overriding eigen strong inline speeds up the compiling of
1584 # conv_grad_ops_3d.cc and conv_ops_3d.cc by 20 minutes,
1585 # but this also hurts the performance. Let users decide what they want.
1586 write_to_bazelrc('build --define=override_eigen_strong_inline=true')
Dandelion Man?90e42f32017-12-15 18:15:07 -08001587
A. Unique TensorFlower061c3592017-11-13 14:21:04 -08001588
Michael Cased31531a2018-01-05 14:09:41 -08001589def config_info_line(name, help_text):
1590 """Helper function to print formatted help text for Bazel config options."""
1591 print('\t--config=%-12s\t# %s' % (name, help_text))
1592
1593
A. Unique TensorFlower76e879d2019-03-22 00:25:36 -07001594def configure_ios():
1595 """Configures TensorFlow for iOS builds.
A. Unique TensorFlower93e70732019-02-14 16:45:32 -08001596
A. Unique TensorFlower76e879d2019-03-22 00:25:36 -07001597 This function will only be executed if `is_macos()` is true.
A. Unique TensorFlower93e70732019-02-14 16:45:32 -08001598 """
1599 if not is_macos():
1600 return
A. Unique TensorFlowered297342019-03-15 11:25:28 -07001601 if _TF_CURRENT_BAZEL_VERSION is None or _TF_CURRENT_BAZEL_VERSION < 23000:
1602 print(
1603 'Building Bazel rules on Apple platforms requires Bazel 0.23 or later.')
A. Unique TensorFlower76e879d2019-03-22 00:25:36 -07001604 for filepath in APPLE_BAZEL_FILES:
1605 existing_filepath = os.path.join(_TF_WORKSPACE_ROOT, filepath + '.apple')
1606 renamed_filepath = os.path.join(_TF_WORKSPACE_ROOT, filepath)
1607 symlink_force(existing_filepath, renamed_filepath)
1608 for filepath in IOS_FILES:
1609 filename = os.path.basename(filepath)
1610 new_filepath = os.path.join(_TF_WORKSPACE_ROOT, filename)
1611 symlink_force(filepath, new_filepath)
A. Unique TensorFlower93e70732019-02-14 16:45:32 -08001612
1613
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001614def main():
A. Unique TensorFlower7c5eb352018-10-01 07:15:23 -07001615 global _TF_WORKSPACE_ROOT
1616 global _TF_BAZELRC
A. Unique TensorFlowered297342019-03-15 11:25:28 -07001617 global _TF_CURRENT_BAZEL_VERSION
A. Unique TensorFlower7c5eb352018-10-01 07:15:23 -07001618
Shanqing Cai71445712018-03-12 19:33:52 -07001619 parser = argparse.ArgumentParser()
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -07001620 parser.add_argument(
1621 '--workspace',
1622 type=str,
A. Unique TensorFlower7c5eb352018-10-01 07:15:23 -07001623 default=os.path.abspath(os.path.dirname(__file__)),
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -07001624 help='The absolute path to your active Bazel workspace.')
Shanqing Cai71445712018-03-12 19:33:52 -07001625 args = parser.parse_args()
1626
A. Unique TensorFlower7c5eb352018-10-01 07:15:23 -07001627 _TF_WORKSPACE_ROOT = args.workspace
1628 _TF_BAZELRC = os.path.join(_TF_WORKSPACE_ROOT, _TF_BAZELRC_FILENAME)
1629
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001630 # Make a copy of os.environ to be clear when functions and getting and setting
1631 # environment variables.
1632 environ_cp = dict(os.environ)
1633
A. Unique TensorFlowered297342019-03-15 11:25:28 -07001634 current_bazel_version = check_bazel_version('0.19.0', '0.23.2')
1635 _TF_CURRENT_BAZEL_VERSION = convert_version_to_int(current_bazel_version)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001636
A. Unique TensorFlower7c5eb352018-10-01 07:15:23 -07001637 reset_tf_configure_bazelrc()
Yun Peng03e63a22018-11-07 11:18:53 +01001638
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001639 cleanup_makefile()
Gunhan Gulsoyed89a2b2017-09-19 18:36:26 -07001640 setup_python(environ_cp)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001641
1642 if is_windows():
Yifei Fengb1d8c592017-11-22 13:42:21 -08001643 environ_cp['TF_NEED_OPENCL_SYCL'] = '0'
1644 environ_cp['TF_NEED_COMPUTECPP'] = '0'
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001645 environ_cp['TF_NEED_OPENCL'] = '0'
1646 environ_cp['TF_CUDA_CLANG'] = '0'
Guangda Lai76f69382018-01-25 23:59:19 -08001647 environ_cp['TF_NEED_TENSORRT'] = '0'
Ilya Biryukov9e651e42018-03-22 05:33:42 -07001648 # TODO(ibiryukov): Investigate using clang as a cpu or cuda compiler on
1649 # Windows.
1650 environ_cp['TF_DOWNLOAD_CLANG'] = '0'
A. Unique TensorFlower6e97fb32018-07-16 14:07:29 -07001651 environ_cp['TF_NEED_MPI'] = '0'
1652 environ_cp['TF_SET_ANDROID_WORKSPACE'] = '0'
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001653
1654 if is_macos():
Guangda Lai76f69382018-01-25 23:59:19 -08001655 environ_cp['TF_NEED_TENSORRT'] = '0'
A. Unique TensorFlower93e70732019-02-14 16:45:32 -08001656 else:
A. Unique TensorFlower76e879d2019-03-22 00:25:36 -07001657 environ_cp['TF_CONFIGURE_IOS'] = '0'
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001658
Jon Triebenbach6896a742018-06-27 13:29:53 -05001659 # The numpy package on ppc64le uses OpenBLAS which has multi-threading
1660 # issues that lead to incorrect answers. Set OMP_NUM_THREADS=1 at
1661 # runtime to allow the Tensorflow testcases which compare numpy
1662 # results to Tensorflow results to succeed.
1663 if is_ppc64le():
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -07001664 write_action_env_to_bazelrc('OMP_NUM_THREADS', 1)
Jon Triebenbach6896a742018-06-27 13:29:53 -05001665
Grzegorz Pawelczakec82efd2018-10-09 15:03:46 +01001666 xla_enabled_by_default = is_linux()
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001667 set_build_var(environ_cp, 'TF_ENABLE_XLA', 'XLA JIT', 'with_xla_support',
Grzegorz Pawelczakec82efd2018-10-09 15:03:46 +01001668 xla_enabled_by_default, 'xla')
Gunhan Gulsoy3da0dff2018-09-26 11:55:50 -07001669
Yifei Fengb1d8c592017-11-22 13:42:21 -08001670 set_action_env_var(environ_cp, 'TF_NEED_OPENCL_SYCL', 'OpenCL SYCL', False)
1671 if environ_cp.get('TF_NEED_OPENCL_SYCL') == '1':
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001672 set_host_cxx_compiler(environ_cp)
1673 set_host_c_compiler(environ_cp)
Yifei Fengb1d8c592017-11-22 13:42:21 -08001674 set_action_env_var(environ_cp, 'TF_NEED_COMPUTECPP', 'ComputeCPP', True)
1675 if environ_cp.get('TF_NEED_COMPUTECPP') == '1':
1676 set_computecpp_toolkit_path(environ_cp)
1677 else:
1678 set_trisycl_include_dir(environ_cp)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001679
Wen-Heng (Jack) Chung69d3b8f2018-06-22 23:09:43 -05001680 set_action_env_var(environ_cp, 'TF_NEED_ROCM', 'ROCm', False)
1681 if (environ_cp.get('TF_NEED_ROCM') == '1' and
TensorFlower Gardener62e60162018-09-27 10:22:55 -07001682 'LD_LIBRARY_PATH' in environ_cp and
1683 environ_cp.get('LD_LIBRARY_PATH') != '1'):
1684 write_action_env_to_bazelrc('LD_LIBRARY_PATH',
1685 environ_cp.get('LD_LIBRARY_PATH'))
Wen-Heng (Jack) Chung69d3b8f2018-06-22 23:09:43 -05001686
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001687 set_action_env_var(environ_cp, 'TF_NEED_CUDA', 'CUDA', False)
A. Unique TensorFlower24cbb2a2017-09-08 07:45:44 -07001688 if (environ_cp.get('TF_NEED_CUDA') == '1' and
1689 'TF_CUDA_CONFIG_REPO' not in environ_cp):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001690 set_tf_cuda_version(environ_cp)
Yifei Fengb1d8c592017-11-22 13:42:21 -08001691 set_tf_cudnn_version(environ_cp)
Guangda Lai76f69382018-01-25 23:59:19 -08001692 if is_linux():
1693 set_tf_tensorrt_install_path(environ_cp)
Michael Case0073d132018-04-11 09:34:44 -07001694 set_tf_nccl_install_path(environ_cp)
1695
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001696 set_tf_cuda_compute_capabilities(environ_cp)
Ankur Taly0e6f39d2018-02-16 18:22:55 -08001697 if 'LD_LIBRARY_PATH' in environ_cp and environ_cp.get(
1698 'LD_LIBRARY_PATH') != '1':
1699 write_action_env_to_bazelrc('LD_LIBRARY_PATH',
1700 environ_cp.get('LD_LIBRARY_PATH'))
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001701
1702 set_tf_cuda_clang(environ_cp)
1703 if environ_cp.get('TF_CUDA_CLANG') == '1':
Ilya Biryukov9e651e42018-03-22 05:33:42 -07001704 # Ask whether we should download the clang toolchain.
1705 set_tf_download_clang(environ_cp)
A. Unique TensorFlowerfd29e952017-12-22 03:07:51 -08001706 if environ_cp.get('TF_DOWNLOAD_CLANG') != '1':
1707 # Set up which clang we should use as the cuda / host compiler.
1708 set_clang_cuda_compiler_path(environ_cp)
Ilya Biryukov1c3d02e2018-09-04 03:09:52 -07001709 else:
1710 # Use downloaded LLD for linking.
1711 write_to_bazelrc('build:cuda_clang --config=download_clang_use_lld')
1712 write_to_bazelrc('test:cuda_clang --config=download_clang_use_lld')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001713 else:
1714 # Set up which gcc nvcc should use as the host compiler
1715 # No need to set this on Windows
1716 if not is_windows():
1717 set_gcc_host_compiler_path(environ_cp)
1718 set_other_cuda_vars(environ_cp)
Ilya Biryukov9e651e42018-03-22 05:33:42 -07001719 else:
1720 # CUDA not required. Ask whether we should download the clang toolchain and
1721 # use it for the CPU build.
1722 set_tf_download_clang(environ_cp)
1723 if environ_cp.get('TF_DOWNLOAD_CLANG') == '1':
1724 write_to_bazelrc('build --config=download_clang')
1725 write_to_bazelrc('test --config=download_clang')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001726
Wen-Heng (Jack) Chung69d3b8f2018-06-22 23:09:43 -05001727 # SYCL / ROCm / CUDA are mutually exclusive.
1728 # At most 1 GPU platform can be configured.
1729 gpu_platform_count = 0
1730 if environ_cp.get('TF_NEED_OPENCL_SYCL') == '1':
1731 gpu_platform_count += 1
1732 if environ_cp.get('TF_NEED_ROCM') == '1':
1733 gpu_platform_count += 1
1734 if environ_cp.get('TF_NEED_CUDA') == '1':
1735 gpu_platform_count += 1
1736 if gpu_platform_count >= 2:
1737 raise UserInputError('SYCL / CUDA / ROCm are mututally exclusive. '
1738 'At most 1 GPU platform can be configured.')
1739
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001740 set_build_var(environ_cp, 'TF_NEED_MPI', 'MPI', 'with_mpi_support', False)
1741 if environ_cp.get('TF_NEED_MPI') == '1':
1742 set_mpi_home(environ_cp)
1743 set_other_mpi_vars(environ_cp)
1744
1745 set_cc_opt_flags(environ_cp)
Yifei Feng5198cb82018-08-17 13:53:06 -07001746 set_system_libs_flag(environ_cp)
A. Unique TensorFlower1b212352018-07-19 13:48:50 -07001747 if is_windows():
1748 set_windows_build_flags(environ_cp)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001749
Anna Ra9a1d5a2018-09-14 12:44:31 -07001750 # Add a config option to build TensorFlow 2.0 API.
1751 write_to_bazelrc('build:v2 --define=tf_api_version=2')
1752
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -07001753 if get_var(environ_cp, 'TF_SET_ANDROID_WORKSPACE', 'android workspace', False,
1754 ('Would you like to interactively configure ./WORKSPACE for '
1755 'Android builds?'), 'Searching for NDK and SDK installations.',
1756 'Not configuring the WORKSPACE for Android builds.'):
Michael Case51053502018-06-05 17:47:19 -07001757 create_android_ndk_rule(environ_cp)
1758 create_android_sdk_rule(environ_cp)
Austin Anderson6afface2017-12-05 11:59:17 -08001759
A. Unique TensorFlower7bd86372019-03-21 15:19:30 -07001760 system_specific_config(os.environ)
Gunhan Gulsoyfff66962019-02-20 15:28:43 -08001761
A. Unique TensorFlower76e879d2019-03-22 00:25:36 -07001762 if get_var(environ_cp, 'TF_CONFIGURE_IOS', 'Configure TensorFlow for iOS',
1763 False, ('Would you like to configure TensorFlow for iOS builds?'),
1764 'Configuring TensorFlow for iOS builds.',
1765 'Not configuring TensorFlow for iOS builds.'):
1766 configure_ios()
A. Unique TensorFlower93e70732019-02-14 16:45:32 -08001767
Gunhan Gulsoy34370982018-10-12 15:26:01 -07001768 print('Preconfigured Bazel build configs. You can use any of the below by '
1769 'adding "--config=<>" to your build command. See .bazelrc for more '
1770 'details.')
1771 config_info_line('mkl', 'Build with MKL support.')
1772 config_info_line('monolithic', 'Config for mostly static monolithic build.')
1773 config_info_line('gdr', 'Build with GDR support.')
1774 config_info_line('verbs', 'Build with libverbs support.')
1775 config_info_line('ngraph', 'Build with Intel nGraph support.')
A. Unique TensorFlowera6bf9c82019-02-26 10:08:35 -08001776 config_info_line('numa', 'Build with NUMA support.')
TensorFlower Gardenerabb763b2019-02-06 16:23:03 -08001777 config_info_line(
1778 'dynamic_kernels',
1779 '(Experimental) Build kernels into separate shared objects.')
Gunhan Gulsoy34370982018-10-12 15:26:01 -07001780
1781 print('Preconfigured Bazel build configs to DISABLE default on features:')
1782 config_info_line('noaws', 'Disable AWS S3 filesystem support.')
1783 config_info_line('nogcp', 'Disable GCP support.')
1784 config_info_line('nohdfs', 'Disable HDFS support.')
Penporn Koanantakool489f1dc2019-01-10 22:07:22 -08001785 config_info_line('noignite', 'Disable Apache Ignite support.')
Gunhan Gulsoy34370982018-10-12 15:26:01 -07001786 config_info_line('nokafka', 'Disable Apache Kafka support.')
Gunhan Gulsoyeea81682018-11-26 16:51:23 -08001787 config_info_line('nonccl', 'Disable NVIDIA NCCL support.')
Austin Anderson6afface2017-12-05 11:59:17 -08001788
Gunhan Gulsoyffa90fc2018-09-26 01:38:55 -07001789
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001790if __name__ == '__main__':
1791 main()