blob: 5a024fb0e4020daced85883cd61e5cc24069cff4 [file] [log] [blame]
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -07001# Copyright 2017 The TensorFlow Authors. All Rights Reserved.
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14# ==============================================================================
15"""configure script to get build parameters from user."""
16
17from __future__ import absolute_import
18from __future__ import division
19from __future__ import print_function
20
21import errno
22import os
23import platform
24import re
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -070025import subprocess
26import sys
27
28_TF_BAZELRC = '.tf_configure.bazelrc'
29_DEFAULT_CUDA_VERSION = '8.0'
30_DEFAULT_CUDNN_VERSION = '6'
31_DEFAULT_CUDA_COMPUTE_CAPABILITIES = '3.5,5.2'
32_DEFAULT_CUDA_PATH = '/usr/local/cuda'
33_DEFAULT_CUDA_PATH_LINUX = '/opt/cuda'
34_DEFAULT_CUDA_PATH_WIN = ('C:/Program Files/NVIDIA GPU Computing '
35 'Toolkit/CUDA/v%s' % _DEFAULT_CUDA_VERSION)
36_TF_OPENCL_VERSION = '1.2'
37_DEFAULT_COMPUTECPP_TOOLKIT_PATH = '/usr/local/computecpp'
38
39
40def is_windows():
41 return platform.system() == 'Windows'
42
43
44def is_linux():
45 return platform.system() == 'Linux'
46
47
48def is_macos():
49 return platform.system() == 'Darwin'
50
51
52def is_ppc64le():
53 return platform.machine() == 'ppc64le'
54
55
56def get_input(question):
57 try:
58 try:
59 answer = raw_input(question)
60 except NameError:
61 answer = input(question) # pylint: disable=bad-builtin
62 except EOFError:
63 answer = ''
64 return answer
65
66
67def symlink_force(target, link_name):
68 """Force symlink, equivalent of 'ln -sf'.
69
70 Args:
71 target: items to link to.
72 link_name: name of the link.
73 """
74 try:
75 os.symlink(target, link_name)
76 except OSError as e:
77 if e.errno == errno.EEXIST:
78 os.remove(link_name)
79 os.symlink(target, link_name)
80 else:
81 raise e
82
83
84def sed_in_place(filename, old, new):
85 """Replace old string with new string in file.
86
87 Args:
88 filename: string for filename.
89 old: string to replace.
90 new: new string to replace to.
91 """
92 with open(filename, 'r') as f:
93 filedata = f.read()
94 newdata = filedata.replace(old, new)
95 with open(filename, 'w') as f:
96 f.write(newdata)
97
98
99def remove_line_with(filename, token):
100 """Remove lines that contain token from file.
101
102 Args:
103 filename: string for filename.
104 token: string token to check if to remove a line from file or not.
105 """
106 with open(filename, 'r') as f:
107 filedata = f.read()
108
109 with open(filename, 'w') as f:
110 for line in filedata.strip().split('\n'):
111 if token not in line:
112 f.write(line + '\n')
113
114
115def write_to_bazelrc(line):
116 with open(_TF_BAZELRC, 'a') as f:
117 f.write(line + '\n')
118
119
120def write_action_env_to_bazelrc(var_name, var):
121 write_to_bazelrc('build --action_env %s="%s"' % (var_name, str(var)))
122
123
124def run_shell(cmd):
125 return subprocess.check_output(cmd, shell=True).decode('UTF-8').strip()
126
127
128def cygpath(path):
129 """Convert path from posix to windows."""
130 return run_shell('cygpath -m "%s"' % path)
131
132
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700133def get_python_path(environ_cp, python_bin_path):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700134 """Get the python site package paths."""
135 python_paths = []
136 if environ_cp.get('PYTHONPATH'):
137 python_paths = environ_cp.get('PYTHONPATH').split(':')
138 try:
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700139 check_input = [
140 python_bin_path, '-c',
141 'import site; print("\\n".join(site.getsitepackages()))'
142 ]
143 library_paths = subprocess.check_output(check_input).decode(
144 'UTF-8').strip().split('\n')
145 except subprocess.CalledProcessError:
146 check_input = [
147 python_bin_path, '-c', 'from distutils.sysconfig import get_python_lib;'
148 + 'print(get_python_lib())'
149 ]
150 library_paths = [
151 subprocess.check_output(check_input).decode('UTF-8').strip()
152 ]
153
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700154 all_paths = set(python_paths + library_paths)
155
156 paths = []
157 for path in all_paths:
158 if os.path.isdir(path):
159 paths.append(path)
160 return paths
161
162
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700163def get_python_major_version(python_bin_path):
164 """Get the python major version."""
165 check_input = [python_bin_path, '-c', 'import sys; print(sys.version[0])']
166 return subprocess.check_output(check_input).decode('UTF-8').strip()
167
168
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700169def setup_python(environ_cp, bazel_version):
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700170 """Setup python related env variables."""
171 # Get PYTHON_BIN_PATH, default is the current running python.
172 default_python_bin_path = sys.executable
173 ask_python_bin_path = ('Please specify the location of python. [Default is '
174 '%s]: ') % default_python_bin_path
175 while True:
176 python_bin_path = get_from_env_or_user_or_default(
177 environ_cp, 'PYTHON_BIN_PATH', ask_python_bin_path,
178 default_python_bin_path)
179 # Check if the path is valid
180 if (os.path.isfile(python_bin_path) and os.access(
181 python_bin_path, os.X_OK)) or (os.path.isdir(python_bin_path)):
182 break
183 elif not os.path.exists(python_bin_path):
184 print('Invalid python path: %s cannot be found.' % python_bin_path)
185 else:
186 print('%s is not executable. Is it the python binary?' % python_bin_path)
187 environ_cp['PYTHON_BIN_PATH'] = ''
188
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700189 # Convert python path to Windows style before checking lib and version
190 if is_windows():
191 python_bin_path = cygpath(python_bin_path)
192
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700193 # Get PYTHON_LIB_PATH
194 python_lib_path = environ_cp.get('PYTHON_LIB_PATH')
195 if not python_lib_path:
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700196 python_lib_paths = get_python_path(environ_cp, python_bin_path)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700197 if environ_cp.get('USE_DEFAULT_PYTHON_LIB_PATH') == '1':
Vijay Vasudevana1fba7f2017-07-28 10:58:56 -0700198 python_lib_path = python_lib_paths[0]
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700199 else:
200 print('Found possible Python library paths:\n%s' %
201 '\n'.join(python_lib_paths))
202 default_python_lib_path = python_lib_paths[0]
203 python_lib_path = get_input(
204 'Please input the desired Python library path to use. Default is %s'
205 % python_lib_paths[0])
206 if not python_lib_path:
207 python_lib_path = default_python_lib_path
Vijay Vasudevana1fba7f2017-07-28 10:58:56 -0700208 environ_cp['PYTHON_LIB_PATH'] = python_lib_path
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700209
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700210 python_major_version = get_python_major_version(python_bin_path)
211
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700212 # Convert python path to Windows style before writing into bazel.rc
213 if is_windows():
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700214 python_lib_path = cygpath(python_lib_path)
215
216 # Set-up env variables used by python_configure.bzl
217 write_action_env_to_bazelrc('PYTHON_BIN_PATH', python_bin_path)
218 write_action_env_to_bazelrc('PYTHON_LIB_PATH', python_lib_path)
219 write_to_bazelrc('build --define PYTHON_BIN_PATH="%s"' % python_bin_path)
220 write_to_bazelrc('build --define PYTHON_LIB_PATH="%s"' % python_lib_path)
221 write_to_bazelrc('build --force_python=py%s' % python_major_version)
222 write_to_bazelrc('build --host_force_python=py%s' % python_major_version)
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700223 bazel_version_int = convert_version_to_int(bazel_version)
224 version_0_5_3_int = convert_version_to_int('0.5.3')
225 # If bazel_version_int is None, we are testing a release Bazel, then the
226 # version should be higher than 0.5.3
227 # TODO(pcloudy): remove this after required min bazel version is higher
228 # than 0.5.3
229 if not bazel_version_int or bazel_version_int >= version_0_5_3_int:
230 write_to_bazelrc('build --python_path=\"%s"' % python_bin_path)
231 else:
232 write_to_bazelrc('build --python%s_path=\"%s"' % (python_major_version,
233 python_bin_path))
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700234 write_to_bazelrc('test --force_python=py%s' % python_major_version)
235 write_to_bazelrc('test --host_force_python=py%s' % python_major_version)
236 write_to_bazelrc('test --define PYTHON_BIN_PATH="%s"' % python_bin_path)
237 write_to_bazelrc('test --define PYTHON_LIB_PATH="%s"' % python_lib_path)
238 write_to_bazelrc('run --define PYTHON_BIN_PATH="%s"' % python_bin_path)
239 write_to_bazelrc('run --define PYTHON_LIB_PATH="%s"' % python_lib_path)
240 environ_cp['PYTHON_BIN_PATH'] = python_bin_path
241
242 # Write tools/python_bin_path.sh
243 with open('tools/python_bin_path.sh', 'w') as f:
244 f.write('export PYTHON_BIN_PATH="%s"' % python_bin_path)
245
246
247def reset_tf_configure_bazelrc():
248 """Reset file that contains customized config settings."""
249 open(_TF_BAZELRC, 'w').close()
250
251 home = os.path.expanduser('~')
252 if not os.path.exists('.bazelrc'):
253 if os.path.exists(os.path.join(home, '.bazelrc')):
254 with open('.bazelrc', 'a') as f:
255 f.write('import %s/.bazelrc\n' % home)
256 else:
257 open('.bazelrc', 'w').close()
258
259 remove_line_with('.bazelrc', 'tf_configure')
260 with open('.bazelrc', 'a') as f:
261 f.write('import %workspace%/.tf_configure.bazelrc\n')
262
263
264def run_gen_git_source(environ_cp):
265 """Run the gen_git_source to create links.
266
267 The links are for bazel to track dependencies for git hash propagation.
268
269 Args:
270 environ_cp: copy of the os.environ.
271 """
Vijay Vasudevana1fba7f2017-07-28 10:58:56 -0700272 cmd = '"%s" tensorflow/tools/git/gen_git_source.py --configure %s' % (
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700273 environ_cp.get('PYTHON_BIN_PATH'), os.getcwd())
274 os.system(cmd)
275
276
277def cleanup_makefile():
278 """Delete any leftover BUILD files from the Makefile build.
279
280 These files could interfere with Bazel parsing.
281 """
282 makefile_download_dir = 'tensorflow/contrib/makefile/downloads'
283 if os.path.isdir(makefile_download_dir):
284 for root, _, filenames in os.walk(makefile_download_dir):
285 for f in filenames:
286 if f.endswith('BUILD'):
287 os.remove(os.path.join(root, f))
288
289
290def get_var(environ_cp,
291 var_name,
292 query_item,
293 enabled_by_default,
294 question=None,
295 yes_reply=None,
296 no_reply=None):
297 """Get boolean input from user.
298
299 If var_name is not set in env, ask user to enable query_item or not. If the
300 response is empty, use the default.
301
302 Args:
303 environ_cp: copy of the os.environ.
304 var_name: string for name of environment variable, e.g. "TF_NEED_HDFS".
305 query_item: string for feature related to the variable, e.g. "Hadoop File
306 System".
307 enabled_by_default: boolean for default behavior.
308 question: optional string for how to ask for user input.
309 yes_reply: optionanl string for reply when feature is enabled.
310 no_reply: optional string for reply when feature is disabled.
311
312 Returns:
313 boolean value of the variable.
314 """
315 if not question:
316 question = 'Do you wish to build TensorFlow with %s support?' % query_item
317 if not yes_reply:
318 yes_reply = '%s support will be enabled for TensorFlow.' % query_item
319 if not no_reply:
320 no_reply = 'No %s' % yes_reply
321
322 yes_reply += '\n'
323 no_reply += '\n'
324
325 if enabled_by_default:
326 question += ' [Y/n]: '
327 else:
328 question += ' [y/N]: '
329
330 var = environ_cp.get(var_name)
331 while var is None:
332 user_input_origin = get_input(question)
333 user_input = user_input_origin.strip().lower()
334 if user_input == 'y':
335 print(yes_reply)
336 var = True
337 elif user_input == 'n':
338 print(no_reply)
339 var = False
340 elif not user_input:
341 if enabled_by_default:
342 print(yes_reply)
343 var = True
344 else:
345 print(no_reply)
346 var = False
347 else:
348 print('Invalid selection: %s' % user_input_origin)
349 return var
350
351
352def set_build_var(environ_cp, var_name, query_item, option_name,
353 enabled_by_default):
354 """Set if query_item will be enabled for the build.
355
356 Ask user if query_item will be enabled. Default is used if no input is given.
357 Set subprocess environment variable and write to .bazelrc if enabled.
358
359 Args:
360 environ_cp: copy of the os.environ.
361 var_name: string for name of environment variable, e.g. "TF_NEED_HDFS".
362 query_item: string for feature related to the variable, e.g. "Hadoop File
363 System".
364 option_name: string for option to define in .bazelrc.
365 enabled_by_default: boolean for default behavior.
366 """
367
368 var = str(int(get_var(environ_cp, var_name, query_item, enabled_by_default)))
369 environ_cp[var_name] = var
370 if var == '1':
371 write_to_bazelrc('build --define %s=true' % option_name)
372
373
374def set_action_env_var(environ_cp,
375 var_name,
376 query_item,
377 enabled_by_default,
378 question=None,
379 yes_reply=None,
380 no_reply=None):
381 """Set boolean action_env variable.
382
383 Ask user if query_item will be enabled. Default is used if no input is given.
384 Set environment variable and write to .bazelrc.
385
386 Args:
387 environ_cp: copy of the os.environ.
388 var_name: string for name of environment variable, e.g. "TF_NEED_HDFS".
389 query_item: string for feature related to the variable, e.g. "Hadoop File
390 System".
391 enabled_by_default: boolean for default behavior.
392 question: optional string for how to ask for user input.
393 yes_reply: optionanl string for reply when feature is enabled.
394 no_reply: optional string for reply when feature is disabled.
395 """
396 var = int(
397 get_var(environ_cp, var_name, query_item, enabled_by_default, question,
398 yes_reply, no_reply))
399
400 write_action_env_to_bazelrc(var_name, var)
401 environ_cp[var_name] = str(var)
402
403
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700404def convert_version_to_int(version):
405 """Convert a version number to a integer that can be used to compare.
406
A. Unique TensorFlower28ce1d12017-08-15 12:08:29 -0700407 Version strings of the form X.YZ and X.Y.Z-xxxxx are supported. The
408 'xxxxx' part, for instance 'homebrew' on OS/X, is ignored.
409
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700410 Args:
A. Unique TensorFlower28ce1d12017-08-15 12:08:29 -0700411 version: a version to be converted
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700412
413 Returns:
414 An integer if converted successfully, otherwise return None.
415 """
A. Unique TensorFlower28ce1d12017-08-15 12:08:29 -0700416 version = version.split('-')[0]
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700417 version_segments = version.split('.')
418 for seg in version_segments:
419 if not seg.isdigit():
420 return None
421
422 version_str = ''.join(['%03d' % int(seg) for seg in version_segments])
423 return int(version_str)
424
425
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700426def check_bazel_version(min_version):
427 """Check installed bezel version is at least min_version.
428
429 Args:
430 min_version: string for minimum bazel version.
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700431
432 Returns:
433 The bazel version detected.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700434 """
435 try:
Vijay Vasudevana1fba7f2017-07-28 10:58:56 -0700436 curr_version = run_shell('bazel --batch version')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700437 except subprocess.CalledProcessError:
438 print('Cannot find bazel. Please install bazel.')
439 sys.exit(0)
440
441 for line in curr_version.split('\n'):
442 if 'Build label: ' in line:
443 curr_version = line.split('Build label: ')[1]
444 break
445
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700446 min_version_int = convert_version_to_int(min_version)
447 curr_version_int = convert_version_to_int(curr_version)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700448
449 # Check if current bazel version can be detected properly.
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700450 if not curr_version_int:
451 print('WARNING: current bazel installation is not a release version.')
452 print('Make sure you are running at least bazel %s' % min_version)
453 return curr_version
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700454
A. Unique TensorFlower28ce1d12017-08-15 12:08:29 -0700455 print("You have bazel %s installed." % curr_version)
456
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700457 if curr_version_int < min_version_int:
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700458 print('Please upgrade your bazel installation to version %s or higher to '
459 'build TensorFlow!' % min_version)
460 sys.exit(0)
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700461 return curr_version
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700462
463
464def set_cc_opt_flags(environ_cp):
465 """Set up architecture-dependent optimization flags.
466
467 Also append CC optimization flags to bazel.rc..
468
469 Args:
470 environ_cp: copy of the os.environ.
471 """
472 if is_ppc64le():
473 # gcc on ppc64le does not support -march, use mcpu instead
474 default_cc_opt_flags = '-mcpu=native'
475 else:
476 default_cc_opt_flags = '-march=native'
477 question = ('Please specify optimization flags to use during compilation when'
478 ' bazel option "--config=opt" is specified [Default is %s]: '
479 ) % default_cc_opt_flags
480 cc_opt_flags = get_from_env_or_user_or_default(environ_cp, 'CC_OPT_FLAGS',
481 question, default_cc_opt_flags)
482 for opt in cc_opt_flags.split():
483 write_to_bazelrc('build:opt --cxxopt=%s --copt=%s' % (opt, opt))
484
485
486def set_tf_cuda_clang(environ_cp):
487 """set TF_CUDA_CLANG action_env.
488
489 Args:
490 environ_cp: copy of the os.environ.
491 """
492 question = 'Do you want to use clang as CUDA compiler?'
493 yes_reply = 'Clang will be used as CUDA compiler.'
494 no_reply = 'nvcc will be used as CUDA compiler.'
495 set_action_env_var(
496 environ_cp,
497 'TF_CUDA_CLANG',
498 None,
499 False,
500 question=question,
501 yes_reply=yes_reply,
502 no_reply=no_reply)
503
504
505def get_from_env_or_user_or_default(environ_cp, var_name, ask_for_var,
506 var_default):
507 """Get var_name either from env, or user or default.
508
509 If var_name has been set as environment variable, use the preset value, else
510 ask for user input. If no input is provided, the default is used.
511
512 Args:
513 environ_cp: copy of the os.environ.
514 var_name: string for name of environment variable, e.g. "TF_NEED_HDFS".
515 ask_for_var: string for how to ask for user input.
516 var_default: default value string.
517
518 Returns:
519 string value for var_name
520 """
521 var = environ_cp.get(var_name)
522 if not var:
523 var = get_input(ask_for_var)
524 if not var:
525 var = var_default
526 return var
527
528
529def set_clang_cuda_compiler_path(environ_cp):
530 """Set CLANG_CUDA_COMPILER_PATH."""
531 default_clang_path = run_shell('which clang || true')
532 ask_clang_path = ('Please specify which clang should be used as device and '
533 'host compiler. [Default is %s]: ') % default_clang_path
534
535 while True:
536 clang_cuda_compiler_path = get_from_env_or_user_or_default(
537 environ_cp, 'CLANG_CUDA_COMPILER_PATH', ask_clang_path,
538 default_clang_path)
539 if os.path.exists(clang_cuda_compiler_path):
540 break
541
542 # Reset and retry
543 print('Invalid clang path: %s cannot be found.' % clang_cuda_compiler_path)
544 environ_cp['CLANG_CUDA_COMPILER_PATH'] = ''
545
546 # Set CLANG_CUDA_COMPILER_PATH
547 environ_cp['CLANG_CUDA_COMPILER_PATH'] = clang_cuda_compiler_path
548 write_action_env_to_bazelrc('CLANG_CUDA_COMPILER_PATH',
549 clang_cuda_compiler_path)
550
551
552def set_gcc_host_compiler_path(environ_cp):
553 """Set GCC_HOST_COMPILER_PATH."""
554 default_gcc_host_compiler_path = run_shell('which gcc || true')
555 cuda_bin_symlink = '%s/bin/gcc' % environ_cp.get('CUDA_TOOLKIT_PATH')
556
557 if os.path.islink(cuda_bin_symlink):
558 # os.readlink is only available in linux
559 default_gcc_host_compiler_path = run_shell('readlink %s' % cuda_bin_symlink)
560
561 ask_gcc_path = (
562 'Please specify which gcc should be used by nvcc as the '
563 'host compiler. [Default is %s]: ') % default_gcc_host_compiler_path
564 while True:
565 gcc_host_compiler_path = get_from_env_or_user_or_default(
566 environ_cp, 'GCC_HOST_COMPILER_PATH', ask_gcc_path,
567 default_gcc_host_compiler_path)
568
569 if os.path.exists(gcc_host_compiler_path):
570 break
571
572 # Reset and retry
573 print('Invalid gcc path. %s cannot be found' % gcc_host_compiler_path)
574 environ_cp['GCC_HOST_COMPILER_PATH'] = ''
575
576 # Set GCC_HOST_COMPILER_PATH
577 environ_cp['GCC_HOST_COMPILER_PATH'] = gcc_host_compiler_path
578 write_action_env_to_bazelrc('GCC_HOST_COMPILER_PATH', gcc_host_compiler_path)
579
580
581def set_tf_cuda_version(environ_cp):
582 """Set CUDA_TOOLKIT_PATH and TF_CUDA_VERSION."""
583 ask_cuda_version = (
584 'Please specify the CUDA SDK version you want to use, '
585 'e.g. 7.0. [Leave empty to default to CUDA %s]: ') % _DEFAULT_CUDA_VERSION
586
587 while True:
588 # Configure the Cuda SDK version to use.
589 tf_cuda_version = get_from_env_or_user_or_default(
590 environ_cp, 'TF_CUDA_VERSION', ask_cuda_version, _DEFAULT_CUDA_VERSION)
591
592 # Find out where the CUDA toolkit is installed
593 default_cuda_path = _DEFAULT_CUDA_PATH
594 if is_windows():
595 default_cuda_path = cygpath(
596 environ_cp.get('CUDA_PATH', _DEFAULT_CUDA_PATH_WIN))
597 elif is_linux():
598 # If the default doesn't exist, try an alternative default.
599 if (not os.path.exists(default_cuda_path)
600 ) and os.path.exists(_DEFAULT_CUDA_PATH_LINUX):
601 default_cuda_path = _DEFAULT_CUDA_PATH_LINUX
602 ask_cuda_path = ('Please specify the location where CUDA %s toolkit is'
603 ' installed. Refer to README.md for more details. '
604 '[Default is %s]: ') % (tf_cuda_version, default_cuda_path)
605 cuda_toolkit_path = get_from_env_or_user_or_default(
606 environ_cp, 'CUDA_TOOLKIT_PATH', ask_cuda_path, default_cuda_path)
607
608 if is_windows():
609 cuda_rt_lib_path = 'lib/x64/cudart.lib'
610 elif is_linux():
611 cuda_rt_lib_path = 'lib64/libcudart.so.%s' % tf_cuda_version
612 elif is_macos():
613 cuda_rt_lib_path = 'lib/libcudart.%s.dylib' % tf_cuda_version
614
615 cuda_toolkit_path_full = os.path.join(cuda_toolkit_path, cuda_rt_lib_path)
616 if os.path.exists(cuda_toolkit_path_full):
617 break
618
619 # Reset and retry
620 print('Invalid path to CUDA %s toolkit. %s cannot be found' %
621 (tf_cuda_version, cuda_toolkit_path_full))
622 environ_cp['TF_CUDA_VERSION'] = ''
623 environ_cp['CUDA_TOOLKIT_PATH'] = ''
624
625 # Set CUDA_TOOLKIT_PATH and TF_CUDA_VERSION
626 environ_cp['CUDA_TOOLKIT_PATH'] = cuda_toolkit_path
627 write_action_env_to_bazelrc('CUDA_TOOLKIT_PATH', cuda_toolkit_path)
628 environ_cp['TF_CUDA_VERSION'] = tf_cuda_version
629 write_action_env_to_bazelrc('TF_CUDA_VERSION', tf_cuda_version)
630
631
632def set_tf_cunn_version(environ_cp):
633 """Set CUDNN_INSTALL_PATH and TF_CUDNN_VERSION."""
634 ask_cudnn_version = (
635 '"Please specify the cuDNN version you want to use. '
636 '[Leave empty to default to cuDNN %s.0]: ') % _DEFAULT_CUDNN_VERSION
637
638 while True:
639 tf_cudnn_version = get_from_env_or_user_or_default(
640 environ_cp, 'TF_CUDNN_VERSION', ask_cudnn_version,
641 _DEFAULT_CUDNN_VERSION)
642
643 default_cudnn_path = environ_cp.get('CUDA_TOOLKIT_PATH')
644 ask_cudnn_path = (r'Please specify the location where cuDNN %s library is '
645 'installed. Refer to README.md for more details. [Default'
646 ' is %s]:') % (tf_cudnn_version, default_cudnn_path)
647 cudnn_install_path = get_from_env_or_user_or_default(
648 environ_cp, 'CUDNN_INSTALL_PATH', ask_cudnn_path, default_cudnn_path)
649
650 # Result returned from "read" will be used unexpanded. That make "~"
651 # unusable. Going through one more level of expansion to handle that.
652 cudnn_install_path = os.path.realpath(
653 os.path.expanduser(cudnn_install_path))
654 if is_windows():
655 cudnn_install_path = cygpath(cudnn_install_path)
656
657 if is_windows():
658 cuda_dnn_lib_path = 'lib/x64/cudnn.lib'
659 cuda_dnn_lib_alt_path = 'lib/x64/cudnn.lib'
660 elif is_linux():
661 cuda_dnn_lib_path = 'lib64/libcudnn.so.%s' % tf_cudnn_version
662 cuda_dnn_lib_alt_path = 'libcudnn.so.%s' % tf_cudnn_version
663 elif is_macos():
664 cuda_dnn_lib_path = 'lib/libcudnn.%s.dylib' % tf_cudnn_version
665 cuda_dnn_lib_alt_path = 'libcudnn.%s.dylib' % tf_cudnn_version
666
667 cuda_dnn_lib_path_full = os.path.join(cudnn_install_path, cuda_dnn_lib_path)
668 cuda_dnn_lib_alt_path_full = os.path.join(cudnn_install_path,
669 cuda_dnn_lib_alt_path)
670 if os.path.exists(cuda_dnn_lib_path_full) or os.path.exists(
671 cuda_dnn_lib_alt_path_full):
672 break
673
674 # Try another alternative for Linux
675 if is_linux():
676 if subprocess.call(['which', 'ldconfig']):
677 ldconfig_bin = '/sbin/ldconfig'
678 else:
679 ldconfig_bin = 'ldconfig'
680 cudnn_path_from_ldconfig = run_shell(
681 r'%s -p | sed -n "s/.*libcudnn.so .* => \(.*\)/\\1/p"' % ldconfig_bin)
682 if os.path.exists('%s.%s' % (cudnn_path_from_ldconfig, tf_cudnn_version)):
683 cudnn_install_path = os.path.dirname(cudnn_path_from_ldconfig)
684 break
685
686 # Reset and Retry
687 print(
688 'Invalid path to cuDNN %s toolkit. None of the following files can be '
689 'found:' % tf_cudnn_version)
690 print(cuda_dnn_lib_path_full)
691 print(cuda_dnn_lib_alt_path_full)
692 if is_linux():
693 print('%s.%s' % (cudnn_path_from_ldconfig, tf_cudnn_version))
694
695 environ_cp['TF_CUDNN_VERSION'] = ''
696
697 # Set CUDNN_INSTALL_PATH and TF_CUDNN_VERSION
698 environ_cp['CUDNN_INSTALL_PATH'] = cudnn_install_path
699 write_action_env_to_bazelrc('CUDNN_INSTALL_PATH', cudnn_install_path)
700 environ_cp['TF_CUDNN_VERSION'] = tf_cudnn_version
701 write_action_env_to_bazelrc('TF_CUDNN_VERSION', tf_cudnn_version)
702
703
704def get_native_cuda_compute_capabilities(environ_cp):
705 """Get native cuda compute capabilities.
706
707 Args:
708 environ_cp: copy of the os.environ.
709 Returns:
710 string of native cuda compute capabilities, separated by comma.
711 """
712 device_query_bin = os.path.join(
713 environ_cp.get('CUDA_TOOLKIT_PATH'), 'extras/demo_suite/deviceQuery')
714 cmd = (r'"%s" | grep "Capability" | grep -o "[0-9]*\.[0-9]*" | sed '
715 '":a;{N;s/\\n/,/};ba"') % device_query_bin
716 try:
717 output = run_shell(cmd)
718 except subprocess.CalledProcessError:
719 output = ''
720 return output
721
722
723def set_tf_cuda_compute_capabilities(environ_cp):
724 """Set TF_CUDA_COMPUTE_CAPABILITIES."""
725 while True:
726 native_cuda_compute_capabilities = get_native_cuda_compute_capabilities(
727 environ_cp)
728 if not native_cuda_compute_capabilities:
729 default_cuda_compute_capabilities = _DEFAULT_CUDA_COMPUTE_CAPABILITIES
730 else:
731 default_cuda_compute_capabilities = native_cuda_compute_capabilities
732
733 ask_cuda_compute_capabilities = (
734 'Please specify a list of comma-separated '
735 'Cuda compute capabilities you want to '
736 'build with.\nYou can find the compute '
737 'capability of your device at: '
738 'https://developer.nvidia.com/cuda-gpus.\nPlease'
739 ' note that each additional compute '
740 'capability significantly increases your '
741 'build time and binary size. [Default is: %s]' %
742 default_cuda_compute_capabilities)
743 tf_cuda_compute_capabilities = get_from_env_or_user_or_default(
744 environ_cp, 'TF_CUDA_COMPUTE_CAPABILITIES',
745 ask_cuda_compute_capabilities, default_cuda_compute_capabilities)
746 # Check whether all capabilities from the input is valid
747 all_valid = True
748 for compute_capability in tf_cuda_compute_capabilities.split(','):
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700749 m = re.match('[0-9]+.[0-9]+', compute_capability)
750 if not m:
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700751 print('Invalid compute capability: ' % compute_capability)
752 all_valid = False
Andrew Harp6e3e7d12017-08-21 12:10:44 -0700753 else:
754 ver = int(m.group(0).split('.')[0])
755 if ver < 3:
756 print('Only compute capabilities 3.0 or higher are supported.')
757 all_valid = False
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700758
759 if all_valid:
760 break
761
762 # Reset and Retry
763 environ_cp['TF_CUDA_COMPUTE_CAPABILITIES'] = ''
764
765 # Set TF_CUDA_COMPUTE_CAPABILITIES
766 environ_cp['TF_CUDA_COMPUTE_CAPABILITIES'] = tf_cuda_compute_capabilities
767 write_action_env_to_bazelrc('TF_CUDA_COMPUTE_CAPABILITIES',
768 tf_cuda_compute_capabilities)
769
770
771def set_other_cuda_vars(environ_cp):
772 """Set other CUDA related variables."""
773 if is_windows():
774 # The following three variables are needed for MSVC toolchain configuration
775 # in Bazel
776 environ_cp['CUDA_PATH'] = environ_cp.get('CUDA_TOOLKIT_PATH')
777 environ_cp['CUDA_COMPUTE_CAPABILITIES'] = environ_cp.get(
778 'TF_CUDA_COMPUTE_CAPABILITIES')
779 environ_cp['NO_WHOLE_ARCHIVE_OPTION'] = 1
780 write_action_env_to_bazelrc('CUDA_PATH', environ_cp.get('CUDA_PATH'))
781 write_action_env_to_bazelrc('CUDA_COMPUTE_CAPABILITIE',
782 environ_cp.get('CUDA_COMPUTE_CAPABILITIE'))
783 write_action_env_to_bazelrc('NO_WHOLE_ARCHIVE_OPTION',
784 environ_cp.get('NO_WHOLE_ARCHIVE_OPTION'))
785 write_to_bazelrc('build --config=win-cuda')
786 write_to_bazelrc('test --config=win-cuda')
787 else:
788 # If CUDA is enabled, always use GPU during build and test.
789 if environ_cp.get('TF_CUDA_CLANG') == '1':
790 write_to_bazelrc('build --config=cuda_clang')
791 write_to_bazelrc('test --config=cuda_clang')
792 else:
793 write_to_bazelrc('build --config=cuda')
794 write_to_bazelrc('test --config=cuda')
795
796
797def set_host_cxx_compiler(environ_cp):
798 """Set HOST_CXX_COMPILER."""
799 default_cxx_host_compiler = run_shell('which g++ || true')
800 ask_cxx_host_compiler = (
801 'Please specify which C++ compiler should be used as'
802 ' the host C++ compiler. [Default is %s]: ') % default_cxx_host_compiler
803
804 while True:
805 host_cxx_compiler = get_from_env_or_user_or_default(
806 environ_cp, 'HOST_CXX_COMPILER', ask_cxx_host_compiler,
807 default_cxx_host_compiler)
808 if os.path.exists(host_cxx_compiler):
809 break
810
811 # Reset and retry
812 print('Invalid C++ compiler path. %s cannot be found' % host_cxx_compiler)
813 environ_cp['HOST_CXX_COMPILER'] = ''
814
815 # Set HOST_CXX_COMPILER
816 environ_cp['HOST_CXX_COMPILER'] = host_cxx_compiler
817 write_action_env_to_bazelrc('HOST_CXX_COMPILER', host_cxx_compiler)
818
819
820def set_host_c_compiler(environ_cp):
821 """Set HOST_C_COMPILER."""
822 default_c_host_compiler = run_shell('which gcc || true')
823 ask_c_host_compiler = (
824 'Please specify which C compiler should be used as the'
825 ' host C compiler. [Default is %s]: ') % default_c_host_compiler
826
827 while True:
828 host_c_compiler = get_from_env_or_user_or_default(
829 environ_cp, 'HOST_C_COMPILER', ask_c_host_compiler,
830 default_c_host_compiler)
831 if os.path.exists(host_c_compiler):
832 break
833
834 # Reset and retry
835 print('Invalid C compiler path. %s cannot be found' % host_c_compiler)
836 environ_cp['HOST_C_COMPILER'] = ''
837
838 # Set HOST_C_COMPILER
839 environ_cp['HOST_C_COMPILER'] = host_c_compiler
840 write_action_env_to_bazelrc('HOST_C_COMPILER', host_c_compiler)
841
842
843def set_computecpp_toolkit_path(environ_cp):
844 """Set COMPUTECPP_TOOLKIT_PATH."""
845 ask_computecpp_toolkit_path = ('Please specify the location where ComputeCpp '
846 'for SYCL %s is installed. [Default is %s]: '
847 ) % (_TF_OPENCL_VERSION,
848 _DEFAULT_COMPUTECPP_TOOLKIT_PATH)
849
850 while True:
851 computecpp_toolkit_path = get_from_env_or_user_or_default(
852 environ_cp, 'COMPUTECPP_TOOLKIT_PATH', ask_computecpp_toolkit_path,
853 _DEFAULT_COMPUTECPP_TOOLKIT_PATH)
854 if is_linux():
855 sycl_rt_lib_path = 'lib/libComputeCpp.so'
856 else:
857 sycl_rt_lib_path = ''
858
859 sycl_rt_lib_path_full = os.path.join(computecpp_toolkit_path,
860 sycl_rt_lib_path)
861 if os.path.exists(sycl_rt_lib_path_full):
862 break
863
864 print('Invalid SYCL %s library path. %s cannot be found' %
865 (_TF_OPENCL_VERSION, sycl_rt_lib_path_full))
866 environ_cp['COMPUTECPP_TOOLKIT_PATH'] = ''
867
868 # Set COMPUTECPP_TOOLKIT_PATH
869 environ_cp['COMPUTECPP_TOOLKIT_PATH'] = computecpp_toolkit_path
870 write_action_env_to_bazelrc('COMPUTECPP_TOOLKIT_PATH',
871 computecpp_toolkit_path)
872
873
874def set_mpi_home(environ_cp):
875 """Set MPI_HOME."""
876 cmd = ('dirname $(dirname $(which mpirun)) || dirname $(dirname $(which '
877 'mpiexec)) || true')
878 default_mpi_home = run_shell(cmd)
879 ask_mpi_home = ('Please specify the MPI toolkit folder. [Default is %s]: '
880 ) % default_mpi_home
881 while True:
882 mpi_home = get_from_env_or_user_or_default(environ_cp, 'MPI_HOME',
883 ask_mpi_home, default_mpi_home)
884
885 if os.path.exists(os.path.join(mpi_home, 'include')) and os.path.exists(
886 os.path.join(mpi_home, 'lib')):
887 break
888
889 print('Invalid path to the MPI Toolkit. %s or %s cannot be found' %
890 (os.path.join(mpi_home, 'include'),
891 os.path.exists(os.path.join(mpi_home, 'lib'))))
892 environ_cp['MPI_HOME'] = ''
893
894 # Set MPI_HOME
895 environ_cp['MPI_HOME'] = str(mpi_home)
896
897
898def set_other_mpi_vars(environ_cp):
899 """Set other MPI related variables."""
900 # Link the MPI header files
901 mpi_home = environ_cp.get('MPI_HOME')
902 symlink_force('%s/include/mpi.h' % mpi_home, 'third_party/mpi/mpi.h')
903
904 # Determine if we use OpenMPI or MVAPICH, these require different header files
905 # to be included here to make bazel dependency checker happy
906 if os.path.exists(os.path.join(mpi_home, 'include/mpi_portable_platform.h')):
907 symlink_force(
908 os.path.join(mpi_home, 'include/mpi_portable_platform.h'),
909 'third_party/mpi/mpi_portable_platform.h')
910 # TODO(gunan): avoid editing files in configure
911 sed_in_place('third_party/mpi/mpi.bzl', 'MPI_LIB_IS_OPENMPI=False',
912 'MPI_LIB_IS_OPENMPI=True')
913 else:
914 # MVAPICH / MPICH
915 symlink_force(
916 os.path.join(mpi_home, 'include/mpio.h'), 'third_party/mpi/mpio.h')
917 symlink_force(
918 os.path.join(mpi_home, 'include/mpicxx.h'), 'third_party/mpi/mpicxx.h')
919 # TODO(gunan): avoid editing files in configure
920 sed_in_place('third_party/mpi/mpi.bzl', 'MPI_LIB_IS_OPENMPI=True',
921 'MPI_LIB_IS_OPENMPI=False')
922
923 if os.path.exists(os.path.join(mpi_home, 'lib/libmpi.so')):
924 symlink_force(
925 os.path.join(mpi_home, 'lib/libmpi.so'), 'third_party/mpi/libmpi.so')
926 else:
927 raise ValueError('Cannot find the MPI library file in %s/lib' % mpi_home)
928
929
930def set_mkl():
931 write_to_bazelrc('build:mkl --define with_mkl_support=true')
932 write_to_bazelrc('build:mkl --define using_mkl=true')
933 write_to_bazelrc('build:mkl -c opt')
934 write_to_bazelrc('build:mkl --copt="-DEIGEN_USE_VML"')
935 print(
936 'Add "--config=mkl" to your bazel command to build with MKL '
937 'support.\nPlease note that MKL on MacOS or windows is still not '
938 'supported.\nIf you would like to use a local MKL instead of '
939 'downloading, please set the environment variable \"TF_MKL_ROOT\" every '
940 'time before build.')
941
942
943def main():
944 # Make a copy of os.environ to be clear when functions and getting and setting
945 # environment variables.
946 environ_cp = dict(os.environ)
947
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700948 bazel_version = check_bazel_version('0.4.5')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700949
950 reset_tf_configure_bazelrc()
951 cleanup_makefile()
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700952 setup_python(environ_cp, bazel_version)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700953 run_gen_git_source(environ_cp)
954
955 if is_windows():
956 environ_cp['TF_NEED_GCP'] = '0'
957 environ_cp['TF_NEED_HDFS'] = '0'
958 environ_cp['TF_NEED_JEMALLOC'] = '0'
959 environ_cp['TF_NEED_OPENCL'] = '0'
960 environ_cp['TF_CUDA_CLANG'] = '0'
961
962 if is_macos():
963 environ_cp['TF_NEED_JEMALLOC'] = '0'
964
965 set_build_var(environ_cp, 'TF_NEED_JEMALLOC', 'jemalloc as malloc',
966 'with_jemalloc', True)
967 set_build_var(environ_cp, 'TF_NEED_GCP', 'Google Cloud Platform',
968 'with_gcp_support', False)
969 set_build_var(environ_cp, 'TF_NEED_HDFS', 'Hadoop File System',
970 'with_hdfs_support', False)
971 set_build_var(environ_cp, 'TF_ENABLE_XLA', 'XLA JIT', 'with_xla_support',
972 False)
A. Unique TensorFlower28ce1d12017-08-15 12:08:29 -0700973 set_build_var(environ_cp, 'TF_NEED_GDR', 'GDR', 'with_gdr_support',
974 False)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700975 set_build_var(environ_cp, 'TF_NEED_VERBS', 'VERBS', 'with_verbs_support',
976 False)
977
978 set_action_env_var(environ_cp, 'TF_NEED_OPENCL', 'OpenCL', False)
979 if environ_cp.get('TF_NEED_OPENCL') == '1':
980 set_host_cxx_compiler(environ_cp)
981 set_host_c_compiler(environ_cp)
982 set_computecpp_toolkit_path(environ_cp)
983
984 set_action_env_var(environ_cp, 'TF_NEED_CUDA', 'CUDA', False)
985 if environ_cp.get('TF_NEED_CUDA') == '1':
986 set_tf_cuda_version(environ_cp)
987 set_tf_cunn_version(environ_cp)
988 set_tf_cuda_compute_capabilities(environ_cp)
989
990 set_tf_cuda_clang(environ_cp)
991 if environ_cp.get('TF_CUDA_CLANG') == '1':
992 # Set up which clang we should use as the cuda / host compiler.
993 set_clang_cuda_compiler_path(environ_cp)
994 else:
995 # Set up which gcc nvcc should use as the host compiler
996 # No need to set this on Windows
997 if not is_windows():
998 set_gcc_host_compiler_path(environ_cp)
999 set_other_cuda_vars(environ_cp)
1000
1001 set_build_var(environ_cp, 'TF_NEED_MPI', 'MPI', 'with_mpi_support', False)
1002 if environ_cp.get('TF_NEED_MPI') == '1':
1003 set_mpi_home(environ_cp)
1004 set_other_mpi_vars(environ_cp)
1005
1006 set_cc_opt_flags(environ_cp)
1007 set_mkl()
1008
1009
1010if __name__ == '__main__':
1011 main()