blob: 26eff5767e4328890ac90c243b7dc647fc72fa75 [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
Dandelion Man?90e42f32017-12-15 18:15:07 -080036_DEFAULT_CUDA_VERSION = '9.0'
37_DEFAULT_CUDNN_VERSION = '7'
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -070038_DEFAULT_CUDA_COMPUTE_CAPABILITIES = '3.5,5.2'
39_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)
Benoit Steiner0dadbfe2018-03-22 18:54:27 -070043_DEFAULT_TENSORRT_PATH_LINUX = '/usr/lib/%s-linux-gnu' % platform.machine()
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -070044_TF_OPENCL_VERSION = '1.2'
45_DEFAULT_COMPUTECPP_TOOLKIT_PATH = '/usr/local/computecpp'
Yifei Fengb1d8c592017-11-22 13:42:21 -080046_DEFAULT_TRISYCL_INCLUDE_DIR = '/usr/local/triSYCL/include'
Austin Anderson6afface2017-12-05 11:59:17 -080047_SUPPORTED_ANDROID_NDK_VERSIONS = [10, 11, 12, 13, 14, 15]
48
49_DEFAULT_PROMPT_ASK_ATTEMPTS = 10
50
Shanqing Cai71445712018-03-12 19:33:52 -070051_TF_WORKSPACE_ROOT = os.path.abspath(os.path.dirname(__file__))
52_TF_BAZELRC_FILENAME = '.tf_configure.bazelrc'
53_TF_BAZELRC = os.path.join(_TF_WORKSPACE_ROOT, _TF_BAZELRC_FILENAME)
54_TF_WORKSPACE = os.path.join(_TF_WORKSPACE_ROOT, 'WORKSPACE')
55
Austin Anderson6afface2017-12-05 11:59:17 -080056
57class UserInputError(Exception):
58 pass
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -070059
60
61def is_windows():
62 return platform.system() == 'Windows'
63
64
65def is_linux():
66 return platform.system() == 'Linux'
67
68
69def is_macos():
70 return platform.system() == 'Darwin'
71
72
73def is_ppc64le():
74 return platform.machine() == 'ppc64le'
75
76
Jonathan Hseu008910f2017-08-25 14:01:05 -070077def is_cygwin():
78 return platform.system().startswith('CYGWIN_NT')
79
80
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -070081def get_input(question):
82 try:
83 try:
84 answer = raw_input(question)
85 except NameError:
86 answer = input(question) # pylint: disable=bad-builtin
87 except EOFError:
88 answer = ''
89 return answer
90
91
92def symlink_force(target, link_name):
93 """Force symlink, equivalent of 'ln -sf'.
94
95 Args:
96 target: items to link to.
97 link_name: name of the link.
98 """
99 try:
100 os.symlink(target, link_name)
101 except OSError as e:
102 if e.errno == errno.EEXIST:
103 os.remove(link_name)
104 os.symlink(target, link_name)
105 else:
106 raise e
107
108
109def sed_in_place(filename, old, new):
110 """Replace old string with new string in file.
111
112 Args:
113 filename: string for filename.
114 old: string to replace.
115 new: new string to replace to.
116 """
117 with open(filename, 'r') as f:
118 filedata = f.read()
119 newdata = filedata.replace(old, new)
120 with open(filename, 'w') as f:
121 f.write(newdata)
122
123
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700124def write_to_bazelrc(line):
125 with open(_TF_BAZELRC, 'a') as f:
126 f.write(line + '\n')
127
128
129def write_action_env_to_bazelrc(var_name, var):
130 write_to_bazelrc('build --action_env %s="%s"' % (var_name, str(var)))
131
132
Jonathan Hseu008910f2017-08-25 14:01:05 -0700133def run_shell(cmd, allow_non_zero=False):
134 if allow_non_zero:
135 try:
136 output = subprocess.check_output(cmd)
137 except subprocess.CalledProcessError as e:
138 output = e.output
139 else:
140 output = subprocess.check_output(cmd)
141 return output.decode('UTF-8').strip()
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700142
143
144def cygpath(path):
145 """Convert path from posix to windows."""
Martin Wicked57572e2017-09-02 19:21:45 -0700146 return os.path.abspath(path).replace('\\', '/')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700147
148
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700149def get_python_path(environ_cp, python_bin_path):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700150 """Get the python site package paths."""
151 python_paths = []
152 if environ_cp.get('PYTHONPATH'):
153 python_paths = environ_cp.get('PYTHONPATH').split(':')
154 try:
Jonathan Hseu008910f2017-08-25 14:01:05 -0700155 library_paths = run_shell(
156 [python_bin_path, '-c',
Austin Anderson6afface2017-12-05 11:59:17 -0800157 'import site; print("\\n".join(site.getsitepackages()))']).split('\n')
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700158 except subprocess.CalledProcessError:
Jonathan Hseu008910f2017-08-25 14:01:05 -0700159 library_paths = [run_shell(
160 [python_bin_path, '-c',
161 'from distutils.sysconfig import get_python_lib;'
162 'print(get_python_lib())'])]
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700163
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700164 all_paths = set(python_paths + library_paths)
165
166 paths = []
167 for path in all_paths:
168 if os.path.isdir(path):
169 paths.append(path)
170 return paths
171
172
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700173def get_python_major_version(python_bin_path):
174 """Get the python major version."""
Jonathan Hseu008910f2017-08-25 14:01:05 -0700175 return run_shell([python_bin_path, '-c', 'import sys; print(sys.version[0])'])
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700176
177
Gunhan Gulsoyed89a2b2017-09-19 18:36:26 -0700178def setup_python(environ_cp):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700179 """Setup python related env variables."""
180 # Get PYTHON_BIN_PATH, default is the current running python.
181 default_python_bin_path = sys.executable
182 ask_python_bin_path = ('Please specify the location of python. [Default is '
183 '%s]: ') % default_python_bin_path
184 while True:
185 python_bin_path = get_from_env_or_user_or_default(
186 environ_cp, 'PYTHON_BIN_PATH', ask_python_bin_path,
187 default_python_bin_path)
188 # Check if the path is valid
Jonathan Hseu008910f2017-08-25 14:01:05 -0700189 if os.path.isfile(python_bin_path) and os.access(
190 python_bin_path, os.X_OK):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700191 break
192 elif not os.path.exists(python_bin_path):
193 print('Invalid python path: %s cannot be found.' % python_bin_path)
194 else:
195 print('%s is not executable. Is it the python binary?' % python_bin_path)
196 environ_cp['PYTHON_BIN_PATH'] = ''
197
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700198 # Convert python path to Windows style before checking lib and version
Martin Wicked57572e2017-09-02 19:21:45 -0700199 if is_windows() or is_cygwin():
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700200 python_bin_path = cygpath(python_bin_path)
201
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700202 # Get PYTHON_LIB_PATH
203 python_lib_path = environ_cp.get('PYTHON_LIB_PATH')
204 if not python_lib_path:
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700205 python_lib_paths = get_python_path(environ_cp, python_bin_path)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700206 if environ_cp.get('USE_DEFAULT_PYTHON_LIB_PATH') == '1':
Vijay Vasudevana1fba7f2017-07-28 10:58:56 -0700207 python_lib_path = python_lib_paths[0]
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700208 else:
Jonathan Hseu008910f2017-08-25 14:01:05 -0700209 print('Found possible Python library paths:\n %s' %
210 '\n '.join(python_lib_paths))
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700211 default_python_lib_path = python_lib_paths[0]
212 python_lib_path = get_input(
Jonathan Hseu008910f2017-08-25 14:01:05 -0700213 'Please input the desired Python library path to use. '
214 'Default is [%s]\n' % python_lib_paths[0])
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700215 if not python_lib_path:
216 python_lib_path = default_python_lib_path
Vijay Vasudevana1fba7f2017-07-28 10:58:56 -0700217 environ_cp['PYTHON_LIB_PATH'] = python_lib_path
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700218
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700219 python_major_version = get_python_major_version(python_bin_path)
220
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700221 # Convert python path to Windows style before writing into bazel.rc
Martin Wicked57572e2017-09-02 19:21:45 -0700222 if is_windows() or is_cygwin():
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700223 python_lib_path = cygpath(python_lib_path)
224
225 # Set-up env variables used by python_configure.bzl
226 write_action_env_to_bazelrc('PYTHON_BIN_PATH', python_bin_path)
227 write_action_env_to_bazelrc('PYTHON_LIB_PATH', python_lib_path)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700228 write_to_bazelrc('build --force_python=py%s' % python_major_version)
229 write_to_bazelrc('build --host_force_python=py%s' % python_major_version)
Gunhan Gulsoyed89a2b2017-09-19 18:36:26 -0700230 write_to_bazelrc('build --python_path=\"%s"' % python_bin_path)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700231 environ_cp['PYTHON_BIN_PATH'] = python_bin_path
232
233 # Write tools/python_bin_path.sh
Shanqing Cai71445712018-03-12 19:33:52 -0700234 with open(os.path.join(
235 _TF_WORKSPACE_ROOT, 'tools', 'python_bin_path.sh'), 'w') as f:
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700236 f.write('export PYTHON_BIN_PATH="%s"' % python_bin_path)
237
238
Shanqing Cai71445712018-03-12 19:33:52 -0700239def reset_tf_configure_bazelrc(workspace_path):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700240 """Reset file that contains customized config settings."""
241 open(_TF_BAZELRC, 'w').close()
Shanqing Cai71445712018-03-12 19:33:52 -0700242 bazelrc_path = os.path.join(workspace_path, '.bazelrc')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700243
Shanqing Cai71445712018-03-12 19:33:52 -0700244 data = []
245 if os.path.exists(bazelrc_path):
246 with open(bazelrc_path, 'r') as f:
247 data = f.read().splitlines()
248 with open(bazelrc_path, 'w') as f:
249 for l in data:
250 if _TF_BAZELRC_FILENAME in l:
251 continue
252 f.write('%s\n' % l)
253 if is_windows():
254 tf_bazelrc_path = _TF_BAZELRC.replace("\\", "/")
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700255 else:
Shanqing Cai71445712018-03-12 19:33:52 -0700256 tf_bazelrc_path = _TF_BAZELRC
257 f.write('import %s\n' % tf_bazelrc_path)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700258
259
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700260def cleanup_makefile():
261 """Delete any leftover BUILD files from the Makefile build.
262
263 These files could interfere with Bazel parsing.
264 """
Shanqing Cai71445712018-03-12 19:33:52 -0700265 makefile_download_dir = os.path.join(
266 _TF_WORKSPACE_ROOT, 'tensorflow', 'contrib', 'makefile', 'downloads')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700267 if os.path.isdir(makefile_download_dir):
268 for root, _, filenames in os.walk(makefile_download_dir):
269 for f in filenames:
270 if f.endswith('BUILD'):
271 os.remove(os.path.join(root, f))
272
273
274def get_var(environ_cp,
275 var_name,
276 query_item,
277 enabled_by_default,
278 question=None,
279 yes_reply=None,
280 no_reply=None):
281 """Get boolean input from user.
282
283 If var_name is not set in env, ask user to enable query_item or not. If the
284 response is empty, use the default.
285
286 Args:
287 environ_cp: copy of the os.environ.
288 var_name: string for name of environment variable, e.g. "TF_NEED_HDFS".
289 query_item: string for feature related to the variable, e.g. "Hadoop File
290 System".
291 enabled_by_default: boolean for default behavior.
292 question: optional string for how to ask for user input.
Michael Cased90054e2018-02-07 14:36:00 -0800293 yes_reply: optional string for reply when feature is enabled.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700294 no_reply: optional string for reply when feature is disabled.
295
296 Returns:
297 boolean value of the variable.
Frank Chenc4ef9272018-01-10 11:36:52 -0800298
299 Raises:
300 UserInputError: if an environment variable is set, but it cannot be
301 interpreted as a boolean indicator, assume that the user has made a
302 scripting error, and will continue to provide invalid input.
303 Raise the error to avoid infinitely looping.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700304 """
305 if not question:
306 question = 'Do you wish to build TensorFlow with %s support?' % query_item
307 if not yes_reply:
308 yes_reply = '%s support will be enabled for TensorFlow.' % query_item
309 if not no_reply:
310 no_reply = 'No %s' % yes_reply
311
312 yes_reply += '\n'
313 no_reply += '\n'
314
315 if enabled_by_default:
316 question += ' [Y/n]: '
317 else:
318 question += ' [y/N]: '
319
320 var = environ_cp.get(var_name)
Frank Chenc4ef9272018-01-10 11:36:52 -0800321 if var is not None:
322 var_content = var.strip().lower()
323 true_strings = ('1', 't', 'true', 'y', 'yes')
324 false_strings = ('0', 'f', 'false', 'n', 'no')
325 if var_content in true_strings:
326 var = True
327 elif var_content in false_strings:
328 var = False
329 else:
330 raise UserInputError(
331 'Environment variable %s must be set as a boolean indicator.\n'
332 'The following are accepted as TRUE : %s.\n'
333 'The following are accepted as FALSE: %s.\n'
334 'Current value is %s.' % (
335 var_name, ', '.join(true_strings), ', '.join(false_strings),
336 var))
337
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700338 while var is None:
339 user_input_origin = get_input(question)
340 user_input = user_input_origin.strip().lower()
341 if user_input == 'y':
342 print(yes_reply)
343 var = True
344 elif user_input == 'n':
345 print(no_reply)
346 var = False
347 elif not user_input:
348 if enabled_by_default:
349 print(yes_reply)
350 var = True
351 else:
352 print(no_reply)
353 var = False
354 else:
355 print('Invalid selection: %s' % user_input_origin)
356 return var
357
358
359def set_build_var(environ_cp, var_name, query_item, option_name,
Michael Case98850a52017-09-14 13:35:57 -0700360 enabled_by_default, bazel_config_name=None):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700361 """Set if query_item will be enabled for the build.
362
363 Ask user if query_item will be enabled. Default is used if no input is given.
364 Set subprocess environment variable and write to .bazelrc if enabled.
365
366 Args:
367 environ_cp: copy of the os.environ.
368 var_name: string for name of environment variable, e.g. "TF_NEED_HDFS".
369 query_item: string for feature related to the variable, e.g. "Hadoop File
370 System".
371 option_name: string for option to define in .bazelrc.
372 enabled_by_default: boolean for default behavior.
Michael Case98850a52017-09-14 13:35:57 -0700373 bazel_config_name: Name for Bazel --config argument to enable build feature.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700374 """
375
376 var = str(int(get_var(environ_cp, var_name, query_item, enabled_by_default)))
377 environ_cp[var_name] = var
378 if var == '1':
379 write_to_bazelrc('build --define %s=true' % option_name)
Michael Case98850a52017-09-14 13:35:57 -0700380 elif bazel_config_name is not None:
381 # TODO(mikecase): Migrate all users of configure.py to use --config Bazel
382 # options and not to set build configs through environment variables.
383 write_to_bazelrc('build:%s --define %s=true'
384 % (bazel_config_name, option_name))
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700385
386
387def set_action_env_var(environ_cp,
388 var_name,
389 query_item,
390 enabled_by_default,
391 question=None,
392 yes_reply=None,
393 no_reply=None):
394 """Set boolean action_env variable.
395
396 Ask user if query_item will be enabled. Default is used if no input is given.
397 Set environment variable and write to .bazelrc.
398
399 Args:
400 environ_cp: copy of the os.environ.
401 var_name: string for name of environment variable, e.g. "TF_NEED_HDFS".
402 query_item: string for feature related to the variable, e.g. "Hadoop File
403 System".
404 enabled_by_default: boolean for default behavior.
405 question: optional string for how to ask for user input.
Michael Cased90054e2018-02-07 14:36:00 -0800406 yes_reply: optional string for reply when feature is enabled.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700407 no_reply: optional string for reply when feature is disabled.
408 """
409 var = int(
410 get_var(environ_cp, var_name, query_item, enabled_by_default, question,
411 yes_reply, no_reply))
412
413 write_action_env_to_bazelrc(var_name, var)
414 environ_cp[var_name] = str(var)
415
416
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700417def convert_version_to_int(version):
418 """Convert a version number to a integer that can be used to compare.
419
A. Unique TensorFlower28ce1d12017-08-15 12:08:29 -0700420 Version strings of the form X.YZ and X.Y.Z-xxxxx are supported. The
421 'xxxxx' part, for instance 'homebrew' on OS/X, is ignored.
422
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700423 Args:
A. Unique TensorFlower28ce1d12017-08-15 12:08:29 -0700424 version: a version to be converted
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700425
426 Returns:
427 An integer if converted successfully, otherwise return None.
428 """
A. Unique TensorFlower28ce1d12017-08-15 12:08:29 -0700429 version = version.split('-')[0]
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700430 version_segments = version.split('.')
431 for seg in version_segments:
432 if not seg.isdigit():
433 return None
434
435 version_str = ''.join(['%03d' % int(seg) for seg in version_segments])
436 return int(version_str)
437
438
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700439def check_bazel_version(min_version):
Yifei Fengdce9a492018-02-22 14:24:57 -0800440 """Check installed bazel version is at least min_version.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700441
442 Args:
443 min_version: string for minimum bazel version.
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700444
445 Returns:
446 The bazel version detected.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700447 """
Jonathan Hseu008910f2017-08-25 14:01:05 -0700448 if which('bazel') is None:
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700449 print('Cannot find bazel. Please install bazel.')
450 sys.exit(0)
Shanqing Cai71445712018-03-12 19:33:52 -0700451 curr_version = run_shell(['bazel', '--batch', '--bazelrc=/dev/null', 'version'])
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700452
453 for line in curr_version.split('\n'):
454 if 'Build label: ' in line:
455 curr_version = line.split('Build label: ')[1]
456 break
457
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700458 min_version_int = convert_version_to_int(min_version)
459 curr_version_int = convert_version_to_int(curr_version)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700460
461 # Check if current bazel version can be detected properly.
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700462 if not curr_version_int:
463 print('WARNING: current bazel installation is not a release version.')
464 print('Make sure you are running at least bazel %s' % min_version)
465 return curr_version
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700466
Michael Cased94271a2017-08-22 17:26:52 -0700467 print('You have bazel %s installed.' % curr_version)
A. Unique TensorFlower28ce1d12017-08-15 12:08:29 -0700468
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700469 if curr_version_int < min_version_int:
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700470 print('Please upgrade your bazel installation to version %s or higher to '
471 'build TensorFlow!' % min_version)
472 sys.exit(0)
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700473 return curr_version
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700474
475
476def set_cc_opt_flags(environ_cp):
477 """Set up architecture-dependent optimization flags.
478
479 Also append CC optimization flags to bazel.rc..
480
481 Args:
482 environ_cp: copy of the os.environ.
483 """
484 if is_ppc64le():
485 # gcc on ppc64le does not support -march, use mcpu instead
486 default_cc_opt_flags = '-mcpu=native'
A. Unique TensorFlower1bba94a2018-04-04 15:45:20 -0700487 elif is_windows():
488 default_cc_opt_flags = '/arch:AVX'
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700489 else:
490 default_cc_opt_flags = '-march=native'
491 question = ('Please specify optimization flags to use during compilation when'
492 ' bazel option "--config=opt" is specified [Default is %s]: '
493 ) % default_cc_opt_flags
494 cc_opt_flags = get_from_env_or_user_or_default(environ_cp, 'CC_OPT_FLAGS',
495 question, default_cc_opt_flags)
496 for opt in cc_opt_flags.split():
Michael Case00177422017-11-10 13:14:03 -0800497 write_to_bazelrc('build:opt --copt=%s' % opt)
498 # It should be safe on the same build host.
A. Unique TensorFlower1bba94a2018-04-04 15:45:20 -0700499 if not is_ppc64le() and not is_windows():
Shanqing Cai71445712018-03-12 19:33:52 -0700500 write_to_bazelrc('build:opt --host_copt=-march=native')
Michael Casebb3355d2017-11-09 08:46:31 -0800501 write_to_bazelrc('build:opt --define with_default_optimizations=true')
Michael Case00177422017-11-10 13:14:03 -0800502 # TODO(mikecase): Remove these default defines once we are able to get
503 # TF Lite targets building without them.
Andrew Selle0b154392017-11-10 10:35:35 -0800504 write_to_bazelrc('build --copt=-DGEMMLOWP_ALLOW_SLOW_SCALAR_FALLBACK')
505 write_to_bazelrc('build --host_copt=-DGEMMLOWP_ALLOW_SLOW_SCALAR_FALLBACK')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700506
507
508def set_tf_cuda_clang(environ_cp):
509 """set TF_CUDA_CLANG action_env.
510
511 Args:
512 environ_cp: copy of the os.environ.
513 """
514 question = 'Do you want to use clang as CUDA compiler?'
515 yes_reply = 'Clang will be used as CUDA compiler.'
516 no_reply = 'nvcc will be used as CUDA compiler.'
517 set_action_env_var(
518 environ_cp,
519 'TF_CUDA_CLANG',
520 None,
521 False,
522 question=question,
523 yes_reply=yes_reply,
524 no_reply=no_reply)
525
526
A. Unique TensorFlowerfd29e952017-12-22 03:07:51 -0800527def set_tf_download_clang(environ_cp):
528 """Set TF_DOWNLOAD_CLANG action_env."""
Ilya Biryukov9e651e42018-03-22 05:33:42 -0700529 question = 'Do you wish to download a fresh release of clang? (Experimental)'
A. Unique TensorFlowerfd29e952017-12-22 03:07:51 -0800530 yes_reply = 'Clang will be downloaded and used to compile tensorflow.'
531 no_reply = 'Clang will not be downloaded.'
532 set_action_env_var(
533 environ_cp,
534 'TF_DOWNLOAD_CLANG',
535 None,
536 False,
537 question=question,
538 yes_reply=yes_reply,
539 no_reply=no_reply)
540
541
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700542def get_from_env_or_user_or_default(environ_cp, var_name, ask_for_var,
543 var_default):
544 """Get var_name either from env, or user or default.
545
546 If var_name has been set as environment variable, use the preset value, else
547 ask for user input. If no input is provided, the default is used.
548
549 Args:
550 environ_cp: copy of the os.environ.
551 var_name: string for name of environment variable, e.g. "TF_NEED_HDFS".
552 ask_for_var: string for how to ask for user input.
553 var_default: default value string.
554
555 Returns:
556 string value for var_name
557 """
558 var = environ_cp.get(var_name)
559 if not var:
560 var = get_input(ask_for_var)
Michael Cased94271a2017-08-22 17:26:52 -0700561 print('\n')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700562 if not var:
563 var = var_default
564 return var
565
566
567def set_clang_cuda_compiler_path(environ_cp):
568 """Set CLANG_CUDA_COMPILER_PATH."""
Jonathan Hseu008910f2017-08-25 14:01:05 -0700569 default_clang_path = which('clang') or ''
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700570 ask_clang_path = ('Please specify which clang should be used as device and '
571 'host compiler. [Default is %s]: ') % default_clang_path
572
573 while True:
574 clang_cuda_compiler_path = get_from_env_or_user_or_default(
575 environ_cp, 'CLANG_CUDA_COMPILER_PATH', ask_clang_path,
576 default_clang_path)
577 if os.path.exists(clang_cuda_compiler_path):
578 break
579
580 # Reset and retry
581 print('Invalid clang path: %s cannot be found.' % clang_cuda_compiler_path)
582 environ_cp['CLANG_CUDA_COMPILER_PATH'] = ''
583
584 # Set CLANG_CUDA_COMPILER_PATH
585 environ_cp['CLANG_CUDA_COMPILER_PATH'] = clang_cuda_compiler_path
586 write_action_env_to_bazelrc('CLANG_CUDA_COMPILER_PATH',
587 clang_cuda_compiler_path)
588
589
Austin Anderson6afface2017-12-05 11:59:17 -0800590def prompt_loop_or_load_from_env(
591 environ_cp,
592 var_name,
593 var_default,
594 ask_for_var,
595 check_success,
596 error_msg,
597 suppress_default_error=False,
598 n_ask_attempts=_DEFAULT_PROMPT_ASK_ATTEMPTS
599):
600 """Loop over user prompts for an ENV param until receiving a valid response.
601
602 For the env param var_name, read from the environment or verify user input
603 until receiving valid input. When done, set var_name in the environ_cp to its
604 new value.
605
606 Args:
607 environ_cp: (Dict) copy of the os.environ.
608 var_name: (String) string for name of environment variable, e.g. "TF_MYVAR".
609 var_default: (String) default value string.
610 ask_for_var: (String) string for how to ask for user input.
611 check_success: (Function) function that takes one argument and returns a
612 boolean. Should return True if the value provided is considered valid. May
613 contain a complex error message if error_msg does not provide enough
614 information. In that case, set suppress_default_error to True.
615 error_msg: (String) String with one and only one '%s'. Formatted with each
616 invalid response upon check_success(input) failure.
617 suppress_default_error: (Bool) Suppress the above error message in favor of
618 one from the check_success function.
619 n_ask_attempts: (Integer) Number of times to query for valid input before
620 raising an error and quitting.
621
622 Returns:
623 [String] The value of var_name after querying for input.
624
625 Raises:
626 UserInputError: if a query has been attempted n_ask_attempts times without
Frank Chenc4ef9272018-01-10 11:36:52 -0800627 success, assume that the user has made a scripting error, and will
628 continue to provide invalid input. Raise the error to avoid infinitely
629 looping.
Austin Anderson6afface2017-12-05 11:59:17 -0800630 """
631 default = environ_cp.get(var_name) or var_default
632 full_query = '%s [Default is %s]: ' % (
633 ask_for_var,
634 default,
635 )
636
637 for _ in range(n_ask_attempts):
638 val = get_from_env_or_user_or_default(environ_cp,
639 var_name,
640 full_query,
641 default)
642 if check_success(val):
643 break
644 if not suppress_default_error:
645 print(error_msg % val)
646 environ_cp[var_name] = ''
647 else:
648 raise UserInputError('Invalid %s setting was provided %d times in a row. '
649 'Assuming to be a scripting mistake.' %
650 (var_name, n_ask_attempts))
651
652 environ_cp[var_name] = val
653 return val
654
655
656def create_android_ndk_rule(environ_cp):
657 """Set ANDROID_NDK_HOME and write Android NDK WORKSPACE rule."""
658 if is_windows() or is_cygwin():
659 default_ndk_path = cygpath('%s/Android/Sdk/ndk-bundle' %
660 environ_cp['APPDATA'])
661 elif is_macos():
662 default_ndk_path = '%s/library/Android/Sdk/ndk-bundle' % environ_cp['HOME']
663 else:
664 default_ndk_path = '%s/Android/Sdk/ndk-bundle' % environ_cp['HOME']
665
666 def valid_ndk_path(path):
667 return (os.path.exists(path) and
668 os.path.exists(os.path.join(path, 'source.properties')))
669
670 android_ndk_home_path = prompt_loop_or_load_from_env(
671 environ_cp,
672 var_name='ANDROID_NDK_HOME',
673 var_default=default_ndk_path,
674 ask_for_var='Please specify the home path of the Android NDK to use.',
675 check_success=valid_ndk_path,
676 error_msg=('The path %s or its child file "source.properties" '
677 'does not exist.')
678 )
679
680 write_android_ndk_workspace_rule(android_ndk_home_path)
681
682
683def create_android_sdk_rule(environ_cp):
684 """Set Android variables and write Android SDK WORKSPACE rule."""
685 if is_windows() or is_cygwin():
686 default_sdk_path = cygpath('%s/Android/Sdk' % environ_cp['APPDATA'])
687 elif is_macos():
688 default_sdk_path = '%s/library/Android/Sdk/ndk-bundle' % environ_cp['HOME']
689 else:
690 default_sdk_path = '%s/Android/Sdk' % environ_cp['HOME']
691
692 def valid_sdk_path(path):
693 return (os.path.exists(path) and
694 os.path.exists(os.path.join(path, 'platforms')) and
695 os.path.exists(os.path.join(path, 'build-tools')))
696
697 android_sdk_home_path = prompt_loop_or_load_from_env(
698 environ_cp,
699 var_name='ANDROID_SDK_HOME',
700 var_default=default_sdk_path,
701 ask_for_var='Please specify the home path of the Android SDK to use.',
702 check_success=valid_sdk_path,
703 error_msg=('Either %s does not exist, or it does not contain the '
704 'subdirectories "platforms" and "build-tools".'))
705
706 platforms = os.path.join(android_sdk_home_path, 'platforms')
707 api_levels = sorted(os.listdir(platforms))
708 api_levels = [x.replace('android-', '') for x in api_levels]
709
710 def valid_api_level(api_level):
711 return os.path.exists(os.path.join(android_sdk_home_path,
712 'platforms',
713 'android-' + api_level))
714
715 android_api_level = prompt_loop_or_load_from_env(
716 environ_cp,
717 var_name='ANDROID_API_LEVEL',
718 var_default=api_levels[-1],
719 ask_for_var=('Please specify the Android SDK API level to use. '
720 '[Available levels: %s]') % api_levels,
721 check_success=valid_api_level,
722 error_msg='Android-%s is not present in the SDK path.')
723
724 build_tools = os.path.join(android_sdk_home_path, 'build-tools')
725 versions = sorted(os.listdir(build_tools))
726
727 def valid_build_tools(version):
728 return os.path.exists(os.path.join(android_sdk_home_path,
729 'build-tools',
730 version))
731
732 android_build_tools_version = prompt_loop_or_load_from_env(
733 environ_cp,
734 var_name='ANDROID_BUILD_TOOLS_VERSION',
735 var_default=versions[-1],
736 ask_for_var=('Please specify an Android build tools version to use. '
737 '[Available versions: %s]') % versions,
738 check_success=valid_build_tools,
739 error_msg=('The selected SDK does not have build-tools version %s '
740 'available.'))
741
742 write_android_sdk_workspace_rule(android_sdk_home_path,
743 android_build_tools_version,
744 android_api_level)
745
746
747def write_android_sdk_workspace_rule(android_sdk_home_path,
748 android_build_tools_version,
749 android_api_level):
750 print('Writing android_sdk_workspace rule.\n')
751 with open(_TF_WORKSPACE, 'a') as f:
752 f.write("""
753android_sdk_repository(
754 name="androidsdk",
755 api_level=%s,
756 path="%s",
757 build_tools_version="%s")\n
758""" % (android_api_level, android_sdk_home_path, android_build_tools_version))
759
760
761def write_android_ndk_workspace_rule(android_ndk_home_path):
762 print('Writing android_ndk_workspace rule.')
763 ndk_api_level = check_ndk_level(android_ndk_home_path)
764 if int(ndk_api_level) not in _SUPPORTED_ANDROID_NDK_VERSIONS:
765 print('WARNING: The API level of the NDK in %s is %s, which is not '
766 'supported by Bazel (officially supported versions: %s). Please use '
767 'another version. Compiling Android targets may result in confusing '
768 'errors.\n' % (android_ndk_home_path, ndk_api_level,
769 _SUPPORTED_ANDROID_NDK_VERSIONS))
770 with open(_TF_WORKSPACE, 'a') as f:
771 f.write("""
772android_ndk_repository(
773 name="androidndk",
774 path="%s",
775 api_level=%s)\n
776""" % (android_ndk_home_path, ndk_api_level))
777
778
779def check_ndk_level(android_ndk_home_path):
780 """Check the revision number of an Android NDK path."""
781 properties_path = '%s/source.properties' % android_ndk_home_path
782 if is_windows() or is_cygwin():
783 properties_path = cygpath(properties_path)
784 with open(properties_path, 'r') as f:
785 filedata = f.read()
786
787 revision = re.search(r'Pkg.Revision = (\d+)', filedata)
788 if revision:
789 return revision.group(1)
790 return None
791
792
793def workspace_has_any_android_rule():
794 """Check the WORKSPACE for existing android_*_repository rules."""
795 with open(_TF_WORKSPACE, 'r') as f:
796 workspace = f.read()
797 has_any_rule = re.search(r'^android_[ns]dk_repository',
798 workspace,
799 re.MULTILINE)
800 return has_any_rule
801
802
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700803def set_gcc_host_compiler_path(environ_cp):
804 """Set GCC_HOST_COMPILER_PATH."""
Jonathan Hseu008910f2017-08-25 14:01:05 -0700805 default_gcc_host_compiler_path = which('gcc') or ''
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700806 cuda_bin_symlink = '%s/bin/gcc' % environ_cp.get('CUDA_TOOLKIT_PATH')
807
808 if os.path.islink(cuda_bin_symlink):
809 # os.readlink is only available in linux
Jonathan Hseu008910f2017-08-25 14:01:05 -0700810 default_gcc_host_compiler_path = os.path.realpath(cuda_bin_symlink)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700811
Austin Anderson6afface2017-12-05 11:59:17 -0800812 gcc_host_compiler_path = prompt_loop_or_load_from_env(
813 environ_cp,
814 var_name='GCC_HOST_COMPILER_PATH',
815 var_default=default_gcc_host_compiler_path,
816 ask_for_var=
817 'Please specify which gcc should be used by nvcc as the host compiler.',
818 check_success=os.path.exists,
819 error_msg='Invalid gcc path. %s cannot be found.',
820 )
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700821
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700822 write_action_env_to_bazelrc('GCC_HOST_COMPILER_PATH', gcc_host_compiler_path)
823
824
Ankur Taly0e6f39d2018-02-16 18:22:55 -0800825def reformat_version_sequence(version_str, sequence_count):
826 """Reformat the version string to have the given number of sequences.
827
828 For example:
829 Given (7, 2) -> 7.0
830 (7.0.1, 2) -> 7.0
831 (5, 1) -> 5
832 (5.0.3.2, 1) -> 5
833
834 Args:
835 version_str: String, the version string.
836 sequence_count: int, an integer.
837 Returns:
838 string, reformatted version string.
839 """
840 v = version_str.split('.')
841 if len(v) < sequence_count:
842 v = v + (['0'] * (sequence_count - len(v)))
843
844 return '.'.join(v[:sequence_count])
845
846
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700847def set_tf_cuda_version(environ_cp):
848 """Set CUDA_TOOLKIT_PATH and TF_CUDA_VERSION."""
849 ask_cuda_version = (
850 'Please specify the CUDA SDK version you want to use, '
851 'e.g. 7.0. [Leave empty to default to CUDA %s]: ') % _DEFAULT_CUDA_VERSION
852
Austin Andersonf9a88f82017-12-13 11:49:40 -0800853 for _ in range(_DEFAULT_PROMPT_ASK_ATTEMPTS):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700854 # Configure the Cuda SDK version to use.
855 tf_cuda_version = get_from_env_or_user_or_default(
856 environ_cp, 'TF_CUDA_VERSION', ask_cuda_version, _DEFAULT_CUDA_VERSION)
Ankur Taly0e6f39d2018-02-16 18:22:55 -0800857 tf_cuda_version = reformat_version_sequence(str(tf_cuda_version), 2)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700858
859 # Find out where the CUDA toolkit is installed
860 default_cuda_path = _DEFAULT_CUDA_PATH
Martin Wicked57572e2017-09-02 19:21:45 -0700861 if is_windows() or is_cygwin():
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700862 default_cuda_path = cygpath(
863 environ_cp.get('CUDA_PATH', _DEFAULT_CUDA_PATH_WIN))
864 elif is_linux():
865 # If the default doesn't exist, try an alternative default.
866 if (not os.path.exists(default_cuda_path)
867 ) and os.path.exists(_DEFAULT_CUDA_PATH_LINUX):
868 default_cuda_path = _DEFAULT_CUDA_PATH_LINUX
869 ask_cuda_path = ('Please specify the location where CUDA %s toolkit is'
870 ' installed. Refer to README.md for more details. '
871 '[Default is %s]: ') % (tf_cuda_version, default_cuda_path)
872 cuda_toolkit_path = get_from_env_or_user_or_default(
873 environ_cp, 'CUDA_TOOLKIT_PATH', ask_cuda_path, default_cuda_path)
874
875 if is_windows():
876 cuda_rt_lib_path = 'lib/x64/cudart.lib'
877 elif is_linux():
878 cuda_rt_lib_path = 'lib64/libcudart.so.%s' % tf_cuda_version
879 elif is_macos():
880 cuda_rt_lib_path = 'lib/libcudart.%s.dylib' % tf_cuda_version
881
882 cuda_toolkit_path_full = os.path.join(cuda_toolkit_path, cuda_rt_lib_path)
883 if os.path.exists(cuda_toolkit_path_full):
884 break
885
886 # Reset and retry
887 print('Invalid path to CUDA %s toolkit. %s cannot be found' %
888 (tf_cuda_version, cuda_toolkit_path_full))
889 environ_cp['TF_CUDA_VERSION'] = ''
890 environ_cp['CUDA_TOOLKIT_PATH'] = ''
891
Austin Andersonf9a88f82017-12-13 11:49:40 -0800892 else:
893 raise UserInputError('Invalid TF_CUDA_SETTING setting was provided %d '
894 'times in a row. Assuming to be a scripting mistake.' %
895 _DEFAULT_PROMPT_ASK_ATTEMPTS)
896
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700897 # Set CUDA_TOOLKIT_PATH and TF_CUDA_VERSION
898 environ_cp['CUDA_TOOLKIT_PATH'] = cuda_toolkit_path
899 write_action_env_to_bazelrc('CUDA_TOOLKIT_PATH', cuda_toolkit_path)
900 environ_cp['TF_CUDA_VERSION'] = tf_cuda_version
901 write_action_env_to_bazelrc('TF_CUDA_VERSION', tf_cuda_version)
902
903
Yifei Fengb1d8c592017-11-22 13:42:21 -0800904def set_tf_cudnn_version(environ_cp):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700905 """Set CUDNN_INSTALL_PATH and TF_CUDNN_VERSION."""
906 ask_cudnn_version = (
Jonathan Hseu008910f2017-08-25 14:01:05 -0700907 'Please specify the cuDNN version you want to use. '
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700908 '[Leave empty to default to cuDNN %s.0]: ') % _DEFAULT_CUDNN_VERSION
909
Austin Andersonf9a88f82017-12-13 11:49:40 -0800910 for _ in range(_DEFAULT_PROMPT_ASK_ATTEMPTS):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700911 tf_cudnn_version = get_from_env_or_user_or_default(
912 environ_cp, 'TF_CUDNN_VERSION', ask_cudnn_version,
913 _DEFAULT_CUDNN_VERSION)
Ankur Taly0e6f39d2018-02-16 18:22:55 -0800914 tf_cudnn_version = reformat_version_sequence(str(tf_cudnn_version), 1)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700915
916 default_cudnn_path = environ_cp.get('CUDA_TOOLKIT_PATH')
917 ask_cudnn_path = (r'Please specify the location where cuDNN %s library is '
918 'installed. Refer to README.md for more details. [Default'
919 ' is %s]:') % (tf_cudnn_version, default_cudnn_path)
920 cudnn_install_path = get_from_env_or_user_or_default(
921 environ_cp, 'CUDNN_INSTALL_PATH', ask_cudnn_path, default_cudnn_path)
922
923 # Result returned from "read" will be used unexpanded. That make "~"
924 # unusable. Going through one more level of expansion to handle that.
925 cudnn_install_path = os.path.realpath(
926 os.path.expanduser(cudnn_install_path))
Martin Wicked57572e2017-09-02 19:21:45 -0700927 if is_windows() or is_cygwin():
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700928 cudnn_install_path = cygpath(cudnn_install_path)
929
930 if is_windows():
931 cuda_dnn_lib_path = 'lib/x64/cudnn.lib'
932 cuda_dnn_lib_alt_path = 'lib/x64/cudnn.lib'
933 elif is_linux():
934 cuda_dnn_lib_path = 'lib64/libcudnn.so.%s' % tf_cudnn_version
935 cuda_dnn_lib_alt_path = 'libcudnn.so.%s' % tf_cudnn_version
936 elif is_macos():
937 cuda_dnn_lib_path = 'lib/libcudnn.%s.dylib' % tf_cudnn_version
938 cuda_dnn_lib_alt_path = 'libcudnn.%s.dylib' % tf_cudnn_version
939
940 cuda_dnn_lib_path_full = os.path.join(cudnn_install_path, cuda_dnn_lib_path)
941 cuda_dnn_lib_alt_path_full = os.path.join(cudnn_install_path,
942 cuda_dnn_lib_alt_path)
943 if os.path.exists(cuda_dnn_lib_path_full) or os.path.exists(
944 cuda_dnn_lib_alt_path_full):
945 break
946
947 # Try another alternative for Linux
948 if is_linux():
Jonathan Hseu008910f2017-08-25 14:01:05 -0700949 ldconfig_bin = which('ldconfig') or '/sbin/ldconfig'
950 cudnn_path_from_ldconfig = run_shell([ldconfig_bin, '-p'])
951 cudnn_path_from_ldconfig = re.search('.*libcudnn.so .* => (.*)',
A. Unique TensorFlowere7223582017-09-06 17:57:04 -0700952 cudnn_path_from_ldconfig)
953 if cudnn_path_from_ldconfig:
954 cudnn_path_from_ldconfig = cudnn_path_from_ldconfig.group(1)
955 if os.path.exists('%s.%s' % (cudnn_path_from_ldconfig,
956 tf_cudnn_version)):
957 cudnn_install_path = os.path.dirname(cudnn_path_from_ldconfig)
958 break
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700959
960 # Reset and Retry
961 print(
962 'Invalid path to cuDNN %s toolkit. None of the following files can be '
963 'found:' % tf_cudnn_version)
964 print(cuda_dnn_lib_path_full)
965 print(cuda_dnn_lib_alt_path_full)
966 if is_linux():
967 print('%s.%s' % (cudnn_path_from_ldconfig, tf_cudnn_version))
968
969 environ_cp['TF_CUDNN_VERSION'] = ''
Austin Andersonf9a88f82017-12-13 11:49:40 -0800970 else:
971 raise UserInputError('Invalid TF_CUDNN setting was provided %d '
972 'times in a row. Assuming to be a scripting mistake.' %
973 _DEFAULT_PROMPT_ASK_ATTEMPTS)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700974
975 # Set CUDNN_INSTALL_PATH and TF_CUDNN_VERSION
976 environ_cp['CUDNN_INSTALL_PATH'] = cudnn_install_path
977 write_action_env_to_bazelrc('CUDNN_INSTALL_PATH', cudnn_install_path)
978 environ_cp['TF_CUDNN_VERSION'] = tf_cudnn_version
979 write_action_env_to_bazelrc('TF_CUDNN_VERSION', tf_cudnn_version)
980
981
Guangda Lai76f69382018-01-25 23:59:19 -0800982def set_tf_tensorrt_install_path(environ_cp):
983 """Set TENSORRT_INSTALL_PATH and TF_TENSORRT_VERSION.
984
985 Adapted from code contributed by Sami Kama (https://github.com/samikama).
986
987 Args:
988 environ_cp: copy of the os.environ.
989
990 Raises:
991 ValueError: if this method was called under non-Linux platform.
992 UserInputError: if user has provided invalid input multiple times.
993 """
994 if not is_linux():
995 raise ValueError('Currently TensorRT is only supported on Linux platform.')
996
997 # Ask user whether to add TensorRT support.
998 if str(int(get_var(
999 environ_cp, 'TF_NEED_TENSORRT', 'TensorRT', False))) != '1':
1000 return
1001
1002 for _ in range(_DEFAULT_PROMPT_ASK_ATTEMPTS):
1003 ask_tensorrt_path = (r'Please specify the location where TensorRT is '
1004 'installed. [Default is %s]:') % (
1005 _DEFAULT_TENSORRT_PATH_LINUX)
1006 trt_install_path = get_from_env_or_user_or_default(
1007 environ_cp, 'TENSORRT_INSTALL_PATH', ask_tensorrt_path,
1008 _DEFAULT_TENSORRT_PATH_LINUX)
1009
1010 # Result returned from "read" will be used unexpanded. That make "~"
1011 # unusable. Going through one more level of expansion to handle that.
1012 trt_install_path = os.path.realpath(
1013 os.path.expanduser(trt_install_path))
1014
1015 def find_libs(search_path):
1016 """Search for libnvinfer.so in "search_path"."""
1017 fl = set()
1018 if os.path.exists(search_path) and os.path.isdir(search_path):
1019 fl.update([os.path.realpath(os.path.join(search_path, x))
1020 for x in os.listdir(search_path) if 'libnvinfer.so' in x])
1021 return fl
1022
1023 possible_files = find_libs(trt_install_path)
1024 possible_files.update(find_libs(os.path.join(trt_install_path, 'lib')))
1025 possible_files.update(find_libs(os.path.join(trt_install_path, 'lib64')))
1026
1027 def is_compatible(tensorrt_lib, cuda_ver, cudnn_ver):
1028 """Check the compatibility between tensorrt and cudnn/cudart libraries."""
1029 ldd_bin = which('ldd') or '/usr/bin/ldd'
1030 ldd_out = run_shell([ldd_bin, tensorrt_lib]).split(os.linesep)
1031 cudnn_pattern = re.compile('.*libcudnn.so\\.?(.*) =>.*$')
1032 cuda_pattern = re.compile('.*libcudart.so\\.?(.*) =>.*$')
1033 cudnn = None
1034 cudart = None
1035 for line in ldd_out:
1036 if 'libcudnn.so' in line:
1037 cudnn = cudnn_pattern.search(line)
1038 elif 'libcudart.so' in line:
1039 cudart = cuda_pattern.search(line)
1040 if cudnn and len(cudnn.group(1)):
1041 cudnn = convert_version_to_int(cudnn.group(1))
1042 if cudart and len(cudart.group(1)):
1043 cudart = convert_version_to_int(cudart.group(1))
1044 return (cudnn == cudnn_ver) and (cudart == cuda_ver)
1045
1046 cuda_ver = convert_version_to_int(environ_cp['TF_CUDA_VERSION'])
1047 cudnn_ver = convert_version_to_int(environ_cp['TF_CUDNN_VERSION'])
1048 nvinfer_pattern = re.compile('.*libnvinfer.so.?(.*)$')
1049 highest_ver = [0, None, None]
1050
1051 for lib_file in possible_files:
1052 if is_compatible(lib_file, cuda_ver, cudnn_ver):
Jacques Pienaar2d0531d2018-03-21 12:07:51 -07001053 matches = nvinfer_pattern.search(lib_file)
1054 if len(matches.groups()) == 0:
1055 continue
1056 ver_str = matches.group(1)
Guangda Lai76f69382018-01-25 23:59:19 -08001057 ver = convert_version_to_int(ver_str) if len(ver_str) else 0
1058 if ver > highest_ver[0]:
1059 highest_ver = [ver, ver_str, lib_file]
1060 if highest_ver[1] is not None:
1061 trt_install_path = os.path.dirname(highest_ver[2])
1062 tf_tensorrt_version = highest_ver[1]
1063 break
1064
1065 # Try another alternative from ldconfig.
1066 ldconfig_bin = which('ldconfig') or '/sbin/ldconfig'
1067 ldconfig_output = run_shell([ldconfig_bin, '-p'])
1068 search_result = re.search(
1069 '.*libnvinfer.so\\.?([0-9.]*).* => (.*)', ldconfig_output)
1070 if search_result:
1071 libnvinfer_path_from_ldconfig = search_result.group(2)
1072 if os.path.exists(libnvinfer_path_from_ldconfig):
1073 if is_compatible(libnvinfer_path_from_ldconfig, cuda_ver, cudnn_ver):
1074 trt_install_path = os.path.dirname(libnvinfer_path_from_ldconfig)
1075 tf_tensorrt_version = search_result.group(1)
1076 break
1077
1078 # Reset and Retry
Yifei Fengdce9a492018-02-22 14:24:57 -08001079 if possible_files:
1080 print('TensorRT libraries found in one the following directories',
1081 'are not compatible with selected cuda and cudnn installations')
1082 print(trt_install_path)
1083 print(os.path.join(trt_install_path, 'lib'))
1084 print(os.path.join(trt_install_path, 'lib64'))
1085 if search_result:
1086 print(libnvinfer_path_from_ldconfig)
1087 else:
1088 print(
1089 'Invalid path to TensorRT. None of the following files can be found:')
1090 print(trt_install_path)
1091 print(os.path.join(trt_install_path, 'lib'))
1092 print(os.path.join(trt_install_path, 'lib64'))
1093 if search_result:
1094 print(libnvinfer_path_from_ldconfig)
Guangda Lai76f69382018-01-25 23:59:19 -08001095
1096 else:
1097 raise UserInputError('Invalid TF_TENSORRT setting was provided %d '
1098 'times in a row. Assuming to be a scripting mistake.' %
1099 _DEFAULT_PROMPT_ASK_ATTEMPTS)
1100
1101 # Set TENSORRT_INSTALL_PATH and TF_TENSORRT_VERSION
1102 environ_cp['TENSORRT_INSTALL_PATH'] = trt_install_path
1103 write_action_env_to_bazelrc('TENSORRT_INSTALL_PATH', trt_install_path)
1104 environ_cp['TF_TENSORRT_VERSION'] = tf_tensorrt_version
1105 write_action_env_to_bazelrc('TF_TENSORRT_VERSION', tf_tensorrt_version)
1106
1107
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001108def get_native_cuda_compute_capabilities(environ_cp):
1109 """Get native cuda compute capabilities.
1110
1111 Args:
1112 environ_cp: copy of the os.environ.
1113 Returns:
1114 string of native cuda compute capabilities, separated by comma.
1115 """
1116 device_query_bin = os.path.join(
1117 environ_cp.get('CUDA_TOOLKIT_PATH'), 'extras/demo_suite/deviceQuery')
Jonathan Hseu008910f2017-08-25 14:01:05 -07001118 if os.path.isfile(device_query_bin) and os.access(device_query_bin, os.X_OK):
1119 try:
1120 output = run_shell(device_query_bin).split('\n')
1121 pattern = re.compile('[0-9]*\\.[0-9]*')
1122 output = [pattern.search(x) for x in output if 'Capability' in x]
1123 output = ','.join(x.group() for x in output if x is not None)
1124 except subprocess.CalledProcessError:
1125 output = ''
1126 else:
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001127 output = ''
1128 return output
1129
1130
1131def set_tf_cuda_compute_capabilities(environ_cp):
1132 """Set TF_CUDA_COMPUTE_CAPABILITIES."""
1133 while True:
1134 native_cuda_compute_capabilities = get_native_cuda_compute_capabilities(
1135 environ_cp)
1136 if not native_cuda_compute_capabilities:
1137 default_cuda_compute_capabilities = _DEFAULT_CUDA_COMPUTE_CAPABILITIES
1138 else:
1139 default_cuda_compute_capabilities = native_cuda_compute_capabilities
1140
1141 ask_cuda_compute_capabilities = (
1142 'Please specify a list of comma-separated '
1143 'Cuda compute capabilities you want to '
1144 'build with.\nYou can find the compute '
1145 'capability of your device at: '
1146 'https://developer.nvidia.com/cuda-gpus.\nPlease'
1147 ' note that each additional compute '
1148 'capability significantly increases your '
1149 'build time and binary size. [Default is: %s]' %
1150 default_cuda_compute_capabilities)
1151 tf_cuda_compute_capabilities = get_from_env_or_user_or_default(
1152 environ_cp, 'TF_CUDA_COMPUTE_CAPABILITIES',
1153 ask_cuda_compute_capabilities, default_cuda_compute_capabilities)
1154 # Check whether all capabilities from the input is valid
1155 all_valid = True
1156 for compute_capability in tf_cuda_compute_capabilities.split(','):
Andrew Harp6e3e7d12017-08-21 12:10:44 -07001157 m = re.match('[0-9]+.[0-9]+', compute_capability)
1158 if not m:
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001159 print('Invalid compute capability: ' % compute_capability)
1160 all_valid = False
Andrew Harp6e3e7d12017-08-21 12:10:44 -07001161 else:
1162 ver = int(m.group(0).split('.')[0])
1163 if ver < 3:
1164 print('Only compute capabilities 3.0 or higher are supported.')
1165 all_valid = False
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001166
1167 if all_valid:
1168 break
1169
1170 # Reset and Retry
1171 environ_cp['TF_CUDA_COMPUTE_CAPABILITIES'] = ''
1172
1173 # Set TF_CUDA_COMPUTE_CAPABILITIES
1174 environ_cp['TF_CUDA_COMPUTE_CAPABILITIES'] = tf_cuda_compute_capabilities
1175 write_action_env_to_bazelrc('TF_CUDA_COMPUTE_CAPABILITIES',
1176 tf_cuda_compute_capabilities)
1177
1178
1179def set_other_cuda_vars(environ_cp):
1180 """Set other CUDA related variables."""
1181 if is_windows():
1182 # The following three variables are needed for MSVC toolchain configuration
1183 # in Bazel
1184 environ_cp['CUDA_PATH'] = environ_cp.get('CUDA_TOOLKIT_PATH')
1185 environ_cp['CUDA_COMPUTE_CAPABILITIES'] = environ_cp.get(
1186 'TF_CUDA_COMPUTE_CAPABILITIES')
1187 environ_cp['NO_WHOLE_ARCHIVE_OPTION'] = 1
1188 write_action_env_to_bazelrc('CUDA_PATH', environ_cp.get('CUDA_PATH'))
1189 write_action_env_to_bazelrc('CUDA_COMPUTE_CAPABILITIE',
1190 environ_cp.get('CUDA_COMPUTE_CAPABILITIE'))
1191 write_action_env_to_bazelrc('NO_WHOLE_ARCHIVE_OPTION',
1192 environ_cp.get('NO_WHOLE_ARCHIVE_OPTION'))
1193 write_to_bazelrc('build --config=win-cuda')
1194 write_to_bazelrc('test --config=win-cuda')
1195 else:
1196 # If CUDA is enabled, always use GPU during build and test.
1197 if environ_cp.get('TF_CUDA_CLANG') == '1':
1198 write_to_bazelrc('build --config=cuda_clang')
1199 write_to_bazelrc('test --config=cuda_clang')
1200 else:
1201 write_to_bazelrc('build --config=cuda')
1202 write_to_bazelrc('test --config=cuda')
1203
1204
1205def set_host_cxx_compiler(environ_cp):
1206 """Set HOST_CXX_COMPILER."""
Jonathan Hseu008910f2017-08-25 14:01:05 -07001207 default_cxx_host_compiler = which('g++') or ''
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001208
Austin Anderson6afface2017-12-05 11:59:17 -08001209 host_cxx_compiler = prompt_loop_or_load_from_env(
1210 environ_cp,
1211 var_name='HOST_CXX_COMPILER',
1212 var_default=default_cxx_host_compiler,
1213 ask_for_var=('Please specify which C++ compiler should be used as the '
1214 'host C++ compiler.'),
1215 check_success=os.path.exists,
1216 error_msg='Invalid C++ compiler path. %s cannot be found.',
1217 )
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001218
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001219 write_action_env_to_bazelrc('HOST_CXX_COMPILER', host_cxx_compiler)
1220
1221
1222def set_host_c_compiler(environ_cp):
1223 """Set HOST_C_COMPILER."""
Jonathan Hseu008910f2017-08-25 14:01:05 -07001224 default_c_host_compiler = which('gcc') or ''
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001225
Austin Anderson6afface2017-12-05 11:59:17 -08001226 host_c_compiler = prompt_loop_or_load_from_env(
1227 environ_cp,
1228 var_name='HOST_C_COMPILER',
1229 var_default=default_c_host_compiler,
Shanqing Cai71445712018-03-12 19:33:52 -07001230 ask_for_var=('Please specify which C compiler should be used as the host '
Austin Anderson6afface2017-12-05 11:59:17 -08001231 'C compiler.'),
1232 check_success=os.path.exists,
1233 error_msg='Invalid C compiler path. %s cannot be found.',
1234 )
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001235
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001236 write_action_env_to_bazelrc('HOST_C_COMPILER', host_c_compiler)
1237
1238
1239def set_computecpp_toolkit_path(environ_cp):
1240 """Set COMPUTECPP_TOOLKIT_PATH."""
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001241
Austin Anderson6afface2017-12-05 11:59:17 -08001242 def toolkit_exists(toolkit_path):
1243 """Check if a computecpp toolkit path is valid."""
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001244 if is_linux():
1245 sycl_rt_lib_path = 'lib/libComputeCpp.so'
1246 else:
1247 sycl_rt_lib_path = ''
1248
Austin Anderson6afface2017-12-05 11:59:17 -08001249 sycl_rt_lib_path_full = os.path.join(toolkit_path,
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001250 sycl_rt_lib_path)
Austin Anderson6afface2017-12-05 11:59:17 -08001251 exists = os.path.exists(sycl_rt_lib_path_full)
1252 if not exists:
1253 print('Invalid SYCL %s library path. %s cannot be found' %
1254 (_TF_OPENCL_VERSION, sycl_rt_lib_path_full))
1255 return exists
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001256
Austin Anderson6afface2017-12-05 11:59:17 -08001257 computecpp_toolkit_path = prompt_loop_or_load_from_env(
1258 environ_cp,
1259 var_name='COMPUTECPP_TOOLKIT_PATH',
1260 var_default=_DEFAULT_COMPUTECPP_TOOLKIT_PATH,
1261 ask_for_var=(
1262 'Please specify the location where ComputeCpp for SYCL %s is '
1263 'installed.' % _TF_OPENCL_VERSION),
1264 check_success=toolkit_exists,
1265 error_msg='Invalid SYCL compiler path. %s cannot be found.',
1266 suppress_default_error=True)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001267
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001268 write_action_env_to_bazelrc('COMPUTECPP_TOOLKIT_PATH',
1269 computecpp_toolkit_path)
1270
Michael Cased31531a2018-01-05 14:09:41 -08001271
Dandelion Man?90e42f32017-12-15 18:15:07 -08001272def set_trisycl_include_dir(environ_cp):
Michael Cased31531a2018-01-05 14:09:41 -08001273 """Set TRISYCL_INCLUDE_DIR."""
Frank Chenc4ef9272018-01-10 11:36:52 -08001274
Dandelion Man?90e42f32017-12-15 18:15:07 -08001275 ask_trisycl_include_dir = ('Please specify the location of the triSYCL '
1276 'include directory. (Use --config=sycl_trisycl '
1277 'when building with Bazel) '
1278 '[Default is %s]: '
Michael Cased31531a2018-01-05 14:09:41 -08001279 ) % (_DEFAULT_TRISYCL_INCLUDE_DIR)
Frank Chenc4ef9272018-01-10 11:36:52 -08001280
Dandelion Man?90e42f32017-12-15 18:15:07 -08001281 while True:
1282 trisycl_include_dir = get_from_env_or_user_or_default(
Michael Cased31531a2018-01-05 14:09:41 -08001283 environ_cp, 'TRISYCL_INCLUDE_DIR', ask_trisycl_include_dir,
1284 _DEFAULT_TRISYCL_INCLUDE_DIR)
Dandelion Man?90e42f32017-12-15 18:15:07 -08001285 if os.path.exists(trisycl_include_dir):
1286 break
1287
1288 print('Invalid triSYCL include directory, %s cannot be found'
1289 % (trisycl_include_dir))
1290
1291 # Set TRISYCL_INCLUDE_DIR
1292 environ_cp['TRISYCL_INCLUDE_DIR'] = trisycl_include_dir
1293 write_action_env_to_bazelrc('TRISYCL_INCLUDE_DIR',
1294 trisycl_include_dir)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001295
Yifei Fengb1d8c592017-11-22 13:42:21 -08001296
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001297def set_mpi_home(environ_cp):
1298 """Set MPI_HOME."""
Austin Anderson6afface2017-12-05 11:59:17 -08001299
Jonathan Hseu008910f2017-08-25 14:01:05 -07001300 default_mpi_home = which('mpirun') or which('mpiexec') or ''
1301 default_mpi_home = os.path.dirname(os.path.dirname(default_mpi_home))
1302
Austin Anderson6afface2017-12-05 11:59:17 -08001303 def valid_mpi_path(mpi_home):
1304 exists = (os.path.exists(os.path.join(mpi_home, 'include')) and
1305 os.path.exists(os.path.join(mpi_home, 'lib')))
1306 if not exists:
1307 print('Invalid path to the MPI Toolkit. %s or %s cannot be found' %
1308 (os.path.join(mpi_home, 'include'),
1309 os.path.exists(os.path.join(mpi_home, 'lib'))))
1310 return exists
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001311
Austin Anderson6afface2017-12-05 11:59:17 -08001312 _ = prompt_loop_or_load_from_env(
1313 environ_cp,
1314 var_name='MPI_HOME',
1315 var_default=default_mpi_home,
1316 ask_for_var='Please specify the MPI toolkit folder.',
1317 check_success=valid_mpi_path,
1318 error_msg='',
1319 suppress_default_error=True)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001320
1321
1322def set_other_mpi_vars(environ_cp):
1323 """Set other MPI related variables."""
1324 # Link the MPI header files
1325 mpi_home = environ_cp.get('MPI_HOME')
1326 symlink_force('%s/include/mpi.h' % mpi_home, 'third_party/mpi/mpi.h')
1327
1328 # Determine if we use OpenMPI or MVAPICH, these require different header files
1329 # to be included here to make bazel dependency checker happy
1330 if os.path.exists(os.path.join(mpi_home, 'include/mpi_portable_platform.h')):
1331 symlink_force(
1332 os.path.join(mpi_home, 'include/mpi_portable_platform.h'),
1333 'third_party/mpi/mpi_portable_platform.h')
1334 # TODO(gunan): avoid editing files in configure
1335 sed_in_place('third_party/mpi/mpi.bzl', 'MPI_LIB_IS_OPENMPI=False',
1336 'MPI_LIB_IS_OPENMPI=True')
1337 else:
1338 # MVAPICH / MPICH
1339 symlink_force(
1340 os.path.join(mpi_home, 'include/mpio.h'), 'third_party/mpi/mpio.h')
1341 symlink_force(
1342 os.path.join(mpi_home, 'include/mpicxx.h'), 'third_party/mpi/mpicxx.h')
1343 # TODO(gunan): avoid editing files in configure
1344 sed_in_place('third_party/mpi/mpi.bzl', 'MPI_LIB_IS_OPENMPI=True',
1345 'MPI_LIB_IS_OPENMPI=False')
1346
1347 if os.path.exists(os.path.join(mpi_home, 'lib/libmpi.so')):
1348 symlink_force(
1349 os.path.join(mpi_home, 'lib/libmpi.so'), 'third_party/mpi/libmpi.so')
1350 else:
1351 raise ValueError('Cannot find the MPI library file in %s/lib' % mpi_home)
1352
1353
A. Unique TensorFlower061c3592017-11-13 14:21:04 -08001354def set_grpc_build_flags():
1355 write_to_bazelrc('build --define grpc_no_ares=true')
1356
Michael Cased31531a2018-01-05 14:09:41 -08001357
Dandelion Man?90e42f32017-12-15 18:15:07 -08001358def set_windows_build_flags():
1359 if is_windows():
1360 # The non-monolithic build is not supported yet
1361 write_to_bazelrc('build --config monolithic')
1362 # Suppress warning messages
1363 write_to_bazelrc('build --copt=-w --host_copt=-w')
1364 # Output more verbose information when something goes wrong
1365 write_to_bazelrc('build --verbose_failures')
1366
A. Unique TensorFlower061c3592017-11-13 14:21:04 -08001367
Michael Cased31531a2018-01-05 14:09:41 -08001368def config_info_line(name, help_text):
1369 """Helper function to print formatted help text for Bazel config options."""
1370 print('\t--config=%-12s\t# %s' % (name, help_text))
1371
1372
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001373def main():
Shanqing Cai71445712018-03-12 19:33:52 -07001374 parser = argparse.ArgumentParser()
1375 parser.add_argument("--workspace",
1376 type=str,
1377 default=_TF_WORKSPACE_ROOT,
1378 help="The absolute path to your active Bazel workspace.")
1379 args = parser.parse_args()
1380
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001381 # Make a copy of os.environ to be clear when functions and getting and setting
1382 # environment variables.
1383 environ_cp = dict(os.environ)
1384
Ilya Biryukov9e651e42018-03-22 05:33:42 -07001385 check_bazel_version('0.10.0')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001386
Shanqing Cai71445712018-03-12 19:33:52 -07001387 reset_tf_configure_bazelrc(args.workspace)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001388 cleanup_makefile()
Gunhan Gulsoyed89a2b2017-09-19 18:36:26 -07001389 setup_python(environ_cp)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001390
1391 if is_windows():
Benoit Steiner355e25e2017-10-24 19:47:46 -07001392 environ_cp['TF_NEED_S3'] = '0'
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001393 environ_cp['TF_NEED_GCP'] = '0'
1394 environ_cp['TF_NEED_HDFS'] = '0'
1395 environ_cp['TF_NEED_JEMALLOC'] = '0'
Michael Cased90054e2018-02-07 14:36:00 -08001396 environ_cp['TF_NEED_KAFKA'] = '0'
Yifei Fengb1d8c592017-11-22 13:42:21 -08001397 environ_cp['TF_NEED_OPENCL_SYCL'] = '0'
1398 environ_cp['TF_NEED_COMPUTECPP'] = '0'
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001399 environ_cp['TF_NEED_OPENCL'] = '0'
1400 environ_cp['TF_CUDA_CLANG'] = '0'
Guangda Lai76f69382018-01-25 23:59:19 -08001401 environ_cp['TF_NEED_TENSORRT'] = '0'
Ilya Biryukov9e651e42018-03-22 05:33:42 -07001402 # TODO(ibiryukov): Investigate using clang as a cpu or cuda compiler on
1403 # Windows.
1404 environ_cp['TF_DOWNLOAD_CLANG'] = '0'
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001405
1406 if is_macos():
1407 environ_cp['TF_NEED_JEMALLOC'] = '0'
Guangda Lai76f69382018-01-25 23:59:19 -08001408 environ_cp['TF_NEED_TENSORRT'] = '0'
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001409
1410 set_build_var(environ_cp, 'TF_NEED_JEMALLOC', 'jemalloc as malloc',
1411 'with_jemalloc', True)
1412 set_build_var(environ_cp, 'TF_NEED_GCP', 'Google Cloud Platform',
Benoit Steiner355e25e2017-10-24 19:47:46 -07001413 'with_gcp_support', True, 'gcp')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001414 set_build_var(environ_cp, 'TF_NEED_HDFS', 'Hadoop File System',
Benoit Steiner355e25e2017-10-24 19:47:46 -07001415 'with_hdfs_support', True, 'hdfs')
Michael Case7e4e3362017-10-09 13:31:15 -07001416 set_build_var(environ_cp, 'TF_NEED_S3', 'Amazon S3 File System',
1417 'with_s3_support', True, 's3')
Michael Cased90054e2018-02-07 14:36:00 -08001418 set_build_var(environ_cp, 'TF_NEED_KAFKA', 'Apache Kafka Platform',
Jianwei Xie63dffd52018-03-29 10:50:46 -07001419 'with_kafka_support', True, 'kafka')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001420 set_build_var(environ_cp, 'TF_ENABLE_XLA', 'XLA JIT', 'with_xla_support',
Michael Case98850a52017-09-14 13:35:57 -07001421 False, 'xla')
A. Unique TensorFlower28ce1d12017-08-15 12:08:29 -07001422 set_build_var(environ_cp, 'TF_NEED_GDR', 'GDR', 'with_gdr_support',
Michael Case98850a52017-09-14 13:35:57 -07001423 False, 'gdr')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001424 set_build_var(environ_cp, 'TF_NEED_VERBS', 'VERBS', 'with_verbs_support',
Michael Case98850a52017-09-14 13:35:57 -07001425 False, 'verbs')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001426
Yifei Fengb1d8c592017-11-22 13:42:21 -08001427 set_action_env_var(environ_cp, 'TF_NEED_OPENCL_SYCL', 'OpenCL SYCL', False)
1428 if environ_cp.get('TF_NEED_OPENCL_SYCL') == '1':
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001429 set_host_cxx_compiler(environ_cp)
1430 set_host_c_compiler(environ_cp)
Yifei Fengb1d8c592017-11-22 13:42:21 -08001431 set_action_env_var(environ_cp, 'TF_NEED_COMPUTECPP', 'ComputeCPP', True)
1432 if environ_cp.get('TF_NEED_COMPUTECPP') == '1':
1433 set_computecpp_toolkit_path(environ_cp)
1434 else:
1435 set_trisycl_include_dir(environ_cp)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001436
1437 set_action_env_var(environ_cp, 'TF_NEED_CUDA', 'CUDA', False)
A. Unique TensorFlower24cbb2a2017-09-08 07:45:44 -07001438 if (environ_cp.get('TF_NEED_CUDA') == '1' and
1439 'TF_CUDA_CONFIG_REPO' not in environ_cp):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001440 set_tf_cuda_version(environ_cp)
Yifei Fengb1d8c592017-11-22 13:42:21 -08001441 set_tf_cudnn_version(environ_cp)
Guangda Lai76f69382018-01-25 23:59:19 -08001442 if is_linux():
1443 set_tf_tensorrt_install_path(environ_cp)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001444 set_tf_cuda_compute_capabilities(environ_cp)
Ankur Taly0e6f39d2018-02-16 18:22:55 -08001445 if 'LD_LIBRARY_PATH' in environ_cp and environ_cp.get(
1446 'LD_LIBRARY_PATH') != '1':
1447 write_action_env_to_bazelrc('LD_LIBRARY_PATH',
1448 environ_cp.get('LD_LIBRARY_PATH'))
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001449
1450 set_tf_cuda_clang(environ_cp)
1451 if environ_cp.get('TF_CUDA_CLANG') == '1':
Ilya Biryukov9e651e42018-03-22 05:33:42 -07001452 # Ask whether we should download the clang toolchain.
1453 set_tf_download_clang(environ_cp)
A. Unique TensorFlowerfd29e952017-12-22 03:07:51 -08001454 if environ_cp.get('TF_DOWNLOAD_CLANG') != '1':
1455 # Set up which clang we should use as the cuda / host compiler.
1456 set_clang_cuda_compiler_path(environ_cp)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001457 else:
1458 # Set up which gcc nvcc should use as the host compiler
1459 # No need to set this on Windows
1460 if not is_windows():
1461 set_gcc_host_compiler_path(environ_cp)
1462 set_other_cuda_vars(environ_cp)
Ilya Biryukov9e651e42018-03-22 05:33:42 -07001463 else:
1464 # CUDA not required. Ask whether we should download the clang toolchain and
1465 # use it for the CPU build.
1466 set_tf_download_clang(environ_cp)
1467 if environ_cp.get('TF_DOWNLOAD_CLANG') == '1':
1468 write_to_bazelrc('build --config=download_clang')
1469 write_to_bazelrc('test --config=download_clang')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001470
1471 set_build_var(environ_cp, 'TF_NEED_MPI', 'MPI', 'with_mpi_support', False)
1472 if environ_cp.get('TF_NEED_MPI') == '1':
1473 set_mpi_home(environ_cp)
1474 set_other_mpi_vars(environ_cp)
1475
A. Unique TensorFlower061c3592017-11-13 14:21:04 -08001476 set_grpc_build_flags()
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001477 set_cc_opt_flags(environ_cp)
Dandelion Man?90e42f32017-12-15 18:15:07 -08001478 set_windows_build_flags()
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001479
Austin Anderson6afface2017-12-05 11:59:17 -08001480 if workspace_has_any_android_rule():
1481 print('The WORKSPACE file has at least one of ["android_sdk_repository", '
1482 '"android_ndk_repository"] already set. Will not ask to help '
1483 'configure the WORKSPACE. Please delete the existing rules to '
1484 'activate the helper.\n')
1485 else:
1486 if get_var(
1487 environ_cp, 'TF_SET_ANDROID_WORKSPACE', 'android workspace',
1488 False,
1489 ('Would you like to interactively configure ./WORKSPACE for '
1490 'Android builds?'),
1491 'Searching for NDK and SDK installations.',
1492 'Not configuring the WORKSPACE for Android builds.'):
1493 create_android_ndk_rule(environ_cp)
1494 create_android_sdk_rule(environ_cp)
1495
Michael Cased31531a2018-01-05 14:09:41 -08001496 print('Preconfigured Bazel build configs. You can use any of the below by '
1497 'adding "--config=<>" to your build command. See tools/bazel.rc for '
1498 'more details.')
1499 config_info_line('mkl', 'Build with MKL support.')
1500 config_info_line('monolithic', 'Config for mostly static monolithic build.')
Austin Anderson6afface2017-12-05 11:59:17 -08001501
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001502if __name__ == '__main__':
1503 main()