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