blob: a78399079aa4b710fd9a3174dd0b9f5301f19995 [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
387 Args:
388 version: a version to be covnerted
389
390 Returns:
391 An integer if converted successfully, otherwise return None.
392 """
393 version_segments = version.split('.')
394 for seg in version_segments:
395 if not seg.isdigit():
396 return None
397
398 version_str = ''.join(['%03d' % int(seg) for seg in version_segments])
399 return int(version_str)
400
401
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700402def check_bazel_version(min_version):
403 """Check installed bezel version is at least min_version.
404
405 Args:
406 min_version: string for minimum bazel version.
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700407
408 Returns:
409 The bazel version detected.
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700410 """
411 try:
Vijay Vasudevana1fba7f2017-07-28 10:58:56 -0700412 curr_version = run_shell('bazel --batch version')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700413 except subprocess.CalledProcessError:
414 print('Cannot find bazel. Please install bazel.')
415 sys.exit(0)
416
417 for line in curr_version.split('\n'):
418 if 'Build label: ' in line:
419 curr_version = line.split('Build label: ')[1]
420 break
421
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700422 min_version_int = convert_version_to_int(min_version)
423 curr_version_int = convert_version_to_int(curr_version)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700424
425 # Check if current bazel version can be detected properly.
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700426 if not curr_version_int:
427 print('WARNING: current bazel installation is not a release version.')
428 print('Make sure you are running at least bazel %s' % min_version)
429 return curr_version
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700430
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700431 if curr_version_int < min_version_int:
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700432 print('Please upgrade your bazel installation to version %s or higher to '
433 'build TensorFlow!' % min_version)
434 sys.exit(0)
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700435 return curr_version
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700436
437
438def set_cc_opt_flags(environ_cp):
439 """Set up architecture-dependent optimization flags.
440
441 Also append CC optimization flags to bazel.rc..
442
443 Args:
444 environ_cp: copy of the os.environ.
445 """
446 if is_ppc64le():
447 # gcc on ppc64le does not support -march, use mcpu instead
448 default_cc_opt_flags = '-mcpu=native'
449 else:
450 default_cc_opt_flags = '-march=native'
451 question = ('Please specify optimization flags to use during compilation when'
452 ' bazel option "--config=opt" is specified [Default is %s]: '
453 ) % default_cc_opt_flags
454 cc_opt_flags = get_from_env_or_user_or_default(environ_cp, 'CC_OPT_FLAGS',
455 question, default_cc_opt_flags)
456 for opt in cc_opt_flags.split():
457 write_to_bazelrc('build:opt --cxxopt=%s --copt=%s' % (opt, opt))
458
459
460def set_tf_cuda_clang(environ_cp):
461 """set TF_CUDA_CLANG action_env.
462
463 Args:
464 environ_cp: copy of the os.environ.
465 """
466 question = 'Do you want to use clang as CUDA compiler?'
467 yes_reply = 'Clang will be used as CUDA compiler.'
468 no_reply = 'nvcc will be used as CUDA compiler.'
469 set_action_env_var(
470 environ_cp,
471 'TF_CUDA_CLANG',
472 None,
473 False,
474 question=question,
475 yes_reply=yes_reply,
476 no_reply=no_reply)
477
478
479def get_from_env_or_user_or_default(environ_cp, var_name, ask_for_var,
480 var_default):
481 """Get var_name either from env, or user or default.
482
483 If var_name has been set as environment variable, use the preset value, else
484 ask for user input. If no input is provided, the default is used.
485
486 Args:
487 environ_cp: copy of the os.environ.
488 var_name: string for name of environment variable, e.g. "TF_NEED_HDFS".
489 ask_for_var: string for how to ask for user input.
490 var_default: default value string.
491
492 Returns:
493 string value for var_name
494 """
495 var = environ_cp.get(var_name)
496 if not var:
497 var = get_input(ask_for_var)
498 if not var:
499 var = var_default
500 return var
501
502
503def set_clang_cuda_compiler_path(environ_cp):
504 """Set CLANG_CUDA_COMPILER_PATH."""
505 default_clang_path = run_shell('which clang || true')
506 ask_clang_path = ('Please specify which clang should be used as device and '
507 'host compiler. [Default is %s]: ') % default_clang_path
508
509 while True:
510 clang_cuda_compiler_path = get_from_env_or_user_or_default(
511 environ_cp, 'CLANG_CUDA_COMPILER_PATH', ask_clang_path,
512 default_clang_path)
513 if os.path.exists(clang_cuda_compiler_path):
514 break
515
516 # Reset and retry
517 print('Invalid clang path: %s cannot be found.' % clang_cuda_compiler_path)
518 environ_cp['CLANG_CUDA_COMPILER_PATH'] = ''
519
520 # Set CLANG_CUDA_COMPILER_PATH
521 environ_cp['CLANG_CUDA_COMPILER_PATH'] = clang_cuda_compiler_path
522 write_action_env_to_bazelrc('CLANG_CUDA_COMPILER_PATH',
523 clang_cuda_compiler_path)
524
525
526def set_gcc_host_compiler_path(environ_cp):
527 """Set GCC_HOST_COMPILER_PATH."""
528 default_gcc_host_compiler_path = run_shell('which gcc || true')
529 cuda_bin_symlink = '%s/bin/gcc' % environ_cp.get('CUDA_TOOLKIT_PATH')
530
531 if os.path.islink(cuda_bin_symlink):
532 # os.readlink is only available in linux
533 default_gcc_host_compiler_path = run_shell('readlink %s' % cuda_bin_symlink)
534
535 ask_gcc_path = (
536 'Please specify which gcc should be used by nvcc as the '
537 'host compiler. [Default is %s]: ') % default_gcc_host_compiler_path
538 while True:
539 gcc_host_compiler_path = get_from_env_or_user_or_default(
540 environ_cp, 'GCC_HOST_COMPILER_PATH', ask_gcc_path,
541 default_gcc_host_compiler_path)
542
543 if os.path.exists(gcc_host_compiler_path):
544 break
545
546 # Reset and retry
547 print('Invalid gcc path. %s cannot be found' % gcc_host_compiler_path)
548 environ_cp['GCC_HOST_COMPILER_PATH'] = ''
549
550 # Set GCC_HOST_COMPILER_PATH
551 environ_cp['GCC_HOST_COMPILER_PATH'] = gcc_host_compiler_path
552 write_action_env_to_bazelrc('GCC_HOST_COMPILER_PATH', gcc_host_compiler_path)
553
554
555def set_tf_cuda_version(environ_cp):
556 """Set CUDA_TOOLKIT_PATH and TF_CUDA_VERSION."""
557 ask_cuda_version = (
558 'Please specify the CUDA SDK version you want to use, '
559 'e.g. 7.0. [Leave empty to default to CUDA %s]: ') % _DEFAULT_CUDA_VERSION
560
561 while True:
562 # Configure the Cuda SDK version to use.
563 tf_cuda_version = get_from_env_or_user_or_default(
564 environ_cp, 'TF_CUDA_VERSION', ask_cuda_version, _DEFAULT_CUDA_VERSION)
565
566 # Find out where the CUDA toolkit is installed
567 default_cuda_path = _DEFAULT_CUDA_PATH
568 if is_windows():
569 default_cuda_path = cygpath(
570 environ_cp.get('CUDA_PATH', _DEFAULT_CUDA_PATH_WIN))
571 elif is_linux():
572 # If the default doesn't exist, try an alternative default.
573 if (not os.path.exists(default_cuda_path)
574 ) and os.path.exists(_DEFAULT_CUDA_PATH_LINUX):
575 default_cuda_path = _DEFAULT_CUDA_PATH_LINUX
576 ask_cuda_path = ('Please specify the location where CUDA %s toolkit is'
577 ' installed. Refer to README.md for more details. '
578 '[Default is %s]: ') % (tf_cuda_version, default_cuda_path)
579 cuda_toolkit_path = get_from_env_or_user_or_default(
580 environ_cp, 'CUDA_TOOLKIT_PATH', ask_cuda_path, default_cuda_path)
581
582 if is_windows():
583 cuda_rt_lib_path = 'lib/x64/cudart.lib'
584 elif is_linux():
585 cuda_rt_lib_path = 'lib64/libcudart.so.%s' % tf_cuda_version
586 elif is_macos():
587 cuda_rt_lib_path = 'lib/libcudart.%s.dylib' % tf_cuda_version
588
589 cuda_toolkit_path_full = os.path.join(cuda_toolkit_path, cuda_rt_lib_path)
590 if os.path.exists(cuda_toolkit_path_full):
591 break
592
593 # Reset and retry
594 print('Invalid path to CUDA %s toolkit. %s cannot be found' %
595 (tf_cuda_version, cuda_toolkit_path_full))
596 environ_cp['TF_CUDA_VERSION'] = ''
597 environ_cp['CUDA_TOOLKIT_PATH'] = ''
598
599 # Set CUDA_TOOLKIT_PATH and TF_CUDA_VERSION
600 environ_cp['CUDA_TOOLKIT_PATH'] = cuda_toolkit_path
601 write_action_env_to_bazelrc('CUDA_TOOLKIT_PATH', cuda_toolkit_path)
602 environ_cp['TF_CUDA_VERSION'] = tf_cuda_version
603 write_action_env_to_bazelrc('TF_CUDA_VERSION', tf_cuda_version)
604
605
606def set_tf_cunn_version(environ_cp):
607 """Set CUDNN_INSTALL_PATH and TF_CUDNN_VERSION."""
608 ask_cudnn_version = (
609 '"Please specify the cuDNN version you want to use. '
610 '[Leave empty to default to cuDNN %s.0]: ') % _DEFAULT_CUDNN_VERSION
611
612 while True:
613 tf_cudnn_version = get_from_env_or_user_or_default(
614 environ_cp, 'TF_CUDNN_VERSION', ask_cudnn_version,
615 _DEFAULT_CUDNN_VERSION)
616
617 default_cudnn_path = environ_cp.get('CUDA_TOOLKIT_PATH')
618 ask_cudnn_path = (r'Please specify the location where cuDNN %s library is '
619 'installed. Refer to README.md for more details. [Default'
620 ' is %s]:') % (tf_cudnn_version, default_cudnn_path)
621 cudnn_install_path = get_from_env_or_user_or_default(
622 environ_cp, 'CUDNN_INSTALL_PATH', ask_cudnn_path, default_cudnn_path)
623
624 # Result returned from "read" will be used unexpanded. That make "~"
625 # unusable. Going through one more level of expansion to handle that.
626 cudnn_install_path = os.path.realpath(
627 os.path.expanduser(cudnn_install_path))
628 if is_windows():
629 cudnn_install_path = cygpath(cudnn_install_path)
630
631 if is_windows():
632 cuda_dnn_lib_path = 'lib/x64/cudnn.lib'
633 cuda_dnn_lib_alt_path = 'lib/x64/cudnn.lib'
634 elif is_linux():
635 cuda_dnn_lib_path = 'lib64/libcudnn.so.%s' % tf_cudnn_version
636 cuda_dnn_lib_alt_path = 'libcudnn.so.%s' % tf_cudnn_version
637 elif is_macos():
638 cuda_dnn_lib_path = 'lib/libcudnn.%s.dylib' % tf_cudnn_version
639 cuda_dnn_lib_alt_path = 'libcudnn.%s.dylib' % tf_cudnn_version
640
641 cuda_dnn_lib_path_full = os.path.join(cudnn_install_path, cuda_dnn_lib_path)
642 cuda_dnn_lib_alt_path_full = os.path.join(cudnn_install_path,
643 cuda_dnn_lib_alt_path)
644 if os.path.exists(cuda_dnn_lib_path_full) or os.path.exists(
645 cuda_dnn_lib_alt_path_full):
646 break
647
648 # Try another alternative for Linux
649 if is_linux():
650 if subprocess.call(['which', 'ldconfig']):
651 ldconfig_bin = '/sbin/ldconfig'
652 else:
653 ldconfig_bin = 'ldconfig'
654 cudnn_path_from_ldconfig = run_shell(
655 r'%s -p | sed -n "s/.*libcudnn.so .* => \(.*\)/\\1/p"' % ldconfig_bin)
656 if os.path.exists('%s.%s' % (cudnn_path_from_ldconfig, tf_cudnn_version)):
657 cudnn_install_path = os.path.dirname(cudnn_path_from_ldconfig)
658 break
659
660 # Reset and Retry
661 print(
662 'Invalid path to cuDNN %s toolkit. None of the following files can be '
663 'found:' % tf_cudnn_version)
664 print(cuda_dnn_lib_path_full)
665 print(cuda_dnn_lib_alt_path_full)
666 if is_linux():
667 print('%s.%s' % (cudnn_path_from_ldconfig, tf_cudnn_version))
668
669 environ_cp['TF_CUDNN_VERSION'] = ''
670
671 # Set CUDNN_INSTALL_PATH and TF_CUDNN_VERSION
672 environ_cp['CUDNN_INSTALL_PATH'] = cudnn_install_path
673 write_action_env_to_bazelrc('CUDNN_INSTALL_PATH', cudnn_install_path)
674 environ_cp['TF_CUDNN_VERSION'] = tf_cudnn_version
675 write_action_env_to_bazelrc('TF_CUDNN_VERSION', tf_cudnn_version)
676
677
678def get_native_cuda_compute_capabilities(environ_cp):
679 """Get native cuda compute capabilities.
680
681 Args:
682 environ_cp: copy of the os.environ.
683 Returns:
684 string of native cuda compute capabilities, separated by comma.
685 """
686 device_query_bin = os.path.join(
687 environ_cp.get('CUDA_TOOLKIT_PATH'), 'extras/demo_suite/deviceQuery')
688 cmd = (r'"%s" | grep "Capability" | grep -o "[0-9]*\.[0-9]*" | sed '
689 '":a;{N;s/\\n/,/};ba"') % device_query_bin
690 try:
691 output = run_shell(cmd)
692 except subprocess.CalledProcessError:
693 output = ''
694 return output
695
696
697def set_tf_cuda_compute_capabilities(environ_cp):
698 """Set TF_CUDA_COMPUTE_CAPABILITIES."""
699 while True:
700 native_cuda_compute_capabilities = get_native_cuda_compute_capabilities(
701 environ_cp)
702 if not native_cuda_compute_capabilities:
703 default_cuda_compute_capabilities = _DEFAULT_CUDA_COMPUTE_CAPABILITIES
704 else:
705 default_cuda_compute_capabilities = native_cuda_compute_capabilities
706
707 ask_cuda_compute_capabilities = (
708 'Please specify a list of comma-separated '
709 'Cuda compute capabilities you want to '
710 'build with.\nYou can find the compute '
711 'capability of your device at: '
712 'https://developer.nvidia.com/cuda-gpus.\nPlease'
713 ' note that each additional compute '
714 'capability significantly increases your '
715 'build time and binary size. [Default is: %s]' %
716 default_cuda_compute_capabilities)
717 tf_cuda_compute_capabilities = get_from_env_or_user_or_default(
718 environ_cp, 'TF_CUDA_COMPUTE_CAPABILITIES',
719 ask_cuda_compute_capabilities, default_cuda_compute_capabilities)
720 # Check whether all capabilities from the input is valid
721 all_valid = True
722 for compute_capability in tf_cuda_compute_capabilities.split(','):
723 if not re.match('[0-9]+.[0-9]+', compute_capability):
724 print('Invalid compute capability: ' % compute_capability)
725 all_valid = False
726
727 if all_valid:
728 break
729
730 # Reset and Retry
731 environ_cp['TF_CUDA_COMPUTE_CAPABILITIES'] = ''
732
733 # Set TF_CUDA_COMPUTE_CAPABILITIES
734 environ_cp['TF_CUDA_COMPUTE_CAPABILITIES'] = tf_cuda_compute_capabilities
735 write_action_env_to_bazelrc('TF_CUDA_COMPUTE_CAPABILITIES',
736 tf_cuda_compute_capabilities)
737
738
739def set_other_cuda_vars(environ_cp):
740 """Set other CUDA related variables."""
741 if is_windows():
742 # The following three variables are needed for MSVC toolchain configuration
743 # in Bazel
744 environ_cp['CUDA_PATH'] = environ_cp.get('CUDA_TOOLKIT_PATH')
745 environ_cp['CUDA_COMPUTE_CAPABILITIES'] = environ_cp.get(
746 'TF_CUDA_COMPUTE_CAPABILITIES')
747 environ_cp['NO_WHOLE_ARCHIVE_OPTION'] = 1
748 write_action_env_to_bazelrc('CUDA_PATH', environ_cp.get('CUDA_PATH'))
749 write_action_env_to_bazelrc('CUDA_COMPUTE_CAPABILITIE',
750 environ_cp.get('CUDA_COMPUTE_CAPABILITIE'))
751 write_action_env_to_bazelrc('NO_WHOLE_ARCHIVE_OPTION',
752 environ_cp.get('NO_WHOLE_ARCHIVE_OPTION'))
753 write_to_bazelrc('build --config=win-cuda')
754 write_to_bazelrc('test --config=win-cuda')
755 else:
756 # If CUDA is enabled, always use GPU during build and test.
757 if environ_cp.get('TF_CUDA_CLANG') == '1':
758 write_to_bazelrc('build --config=cuda_clang')
759 write_to_bazelrc('test --config=cuda_clang')
760 else:
761 write_to_bazelrc('build --config=cuda')
762 write_to_bazelrc('test --config=cuda')
763
764
765def set_host_cxx_compiler(environ_cp):
766 """Set HOST_CXX_COMPILER."""
767 default_cxx_host_compiler = run_shell('which g++ || true')
768 ask_cxx_host_compiler = (
769 'Please specify which C++ compiler should be used as'
770 ' the host C++ compiler. [Default is %s]: ') % default_cxx_host_compiler
771
772 while True:
773 host_cxx_compiler = get_from_env_or_user_or_default(
774 environ_cp, 'HOST_CXX_COMPILER', ask_cxx_host_compiler,
775 default_cxx_host_compiler)
776 if os.path.exists(host_cxx_compiler):
777 break
778
779 # Reset and retry
780 print('Invalid C++ compiler path. %s cannot be found' % host_cxx_compiler)
781 environ_cp['HOST_CXX_COMPILER'] = ''
782
783 # Set HOST_CXX_COMPILER
784 environ_cp['HOST_CXX_COMPILER'] = host_cxx_compiler
785 write_action_env_to_bazelrc('HOST_CXX_COMPILER', host_cxx_compiler)
786
787
788def set_host_c_compiler(environ_cp):
789 """Set HOST_C_COMPILER."""
790 default_c_host_compiler = run_shell('which gcc || true')
791 ask_c_host_compiler = (
792 'Please specify which C compiler should be used as the'
793 ' host C compiler. [Default is %s]: ') % default_c_host_compiler
794
795 while True:
796 host_c_compiler = get_from_env_or_user_or_default(
797 environ_cp, 'HOST_C_COMPILER', ask_c_host_compiler,
798 default_c_host_compiler)
799 if os.path.exists(host_c_compiler):
800 break
801
802 # Reset and retry
803 print('Invalid C compiler path. %s cannot be found' % host_c_compiler)
804 environ_cp['HOST_C_COMPILER'] = ''
805
806 # Set HOST_C_COMPILER
807 environ_cp['HOST_C_COMPILER'] = host_c_compiler
808 write_action_env_to_bazelrc('HOST_C_COMPILER', host_c_compiler)
809
810
811def set_computecpp_toolkit_path(environ_cp):
812 """Set COMPUTECPP_TOOLKIT_PATH."""
813 ask_computecpp_toolkit_path = ('Please specify the location where ComputeCpp '
814 'for SYCL %s is installed. [Default is %s]: '
815 ) % (_TF_OPENCL_VERSION,
816 _DEFAULT_COMPUTECPP_TOOLKIT_PATH)
817
818 while True:
819 computecpp_toolkit_path = get_from_env_or_user_or_default(
820 environ_cp, 'COMPUTECPP_TOOLKIT_PATH', ask_computecpp_toolkit_path,
821 _DEFAULT_COMPUTECPP_TOOLKIT_PATH)
822 if is_linux():
823 sycl_rt_lib_path = 'lib/libComputeCpp.so'
824 else:
825 sycl_rt_lib_path = ''
826
827 sycl_rt_lib_path_full = os.path.join(computecpp_toolkit_path,
828 sycl_rt_lib_path)
829 if os.path.exists(sycl_rt_lib_path_full):
830 break
831
832 print('Invalid SYCL %s library path. %s cannot be found' %
833 (_TF_OPENCL_VERSION, sycl_rt_lib_path_full))
834 environ_cp['COMPUTECPP_TOOLKIT_PATH'] = ''
835
836 # Set COMPUTECPP_TOOLKIT_PATH
837 environ_cp['COMPUTECPP_TOOLKIT_PATH'] = computecpp_toolkit_path
838 write_action_env_to_bazelrc('COMPUTECPP_TOOLKIT_PATH',
839 computecpp_toolkit_path)
840
841
842def set_mpi_home(environ_cp):
843 """Set MPI_HOME."""
844 cmd = ('dirname $(dirname $(which mpirun)) || dirname $(dirname $(which '
845 'mpiexec)) || true')
846 default_mpi_home = run_shell(cmd)
847 ask_mpi_home = ('Please specify the MPI toolkit folder. [Default is %s]: '
848 ) % default_mpi_home
849 while True:
850 mpi_home = get_from_env_or_user_or_default(environ_cp, 'MPI_HOME',
851 ask_mpi_home, default_mpi_home)
852
853 if os.path.exists(os.path.join(mpi_home, 'include')) and os.path.exists(
854 os.path.join(mpi_home, 'lib')):
855 break
856
857 print('Invalid path to the MPI Toolkit. %s or %s cannot be found' %
858 (os.path.join(mpi_home, 'include'),
859 os.path.exists(os.path.join(mpi_home, 'lib'))))
860 environ_cp['MPI_HOME'] = ''
861
862 # Set MPI_HOME
863 environ_cp['MPI_HOME'] = str(mpi_home)
864
865
866def set_other_mpi_vars(environ_cp):
867 """Set other MPI related variables."""
868 # Link the MPI header files
869 mpi_home = environ_cp.get('MPI_HOME')
870 symlink_force('%s/include/mpi.h' % mpi_home, 'third_party/mpi/mpi.h')
871
872 # Determine if we use OpenMPI or MVAPICH, these require different header files
873 # to be included here to make bazel dependency checker happy
874 if os.path.exists(os.path.join(mpi_home, 'include/mpi_portable_platform.h')):
875 symlink_force(
876 os.path.join(mpi_home, 'include/mpi_portable_platform.h'),
877 'third_party/mpi/mpi_portable_platform.h')
878 # TODO(gunan): avoid editing files in configure
879 sed_in_place('third_party/mpi/mpi.bzl', 'MPI_LIB_IS_OPENMPI=False',
880 'MPI_LIB_IS_OPENMPI=True')
881 else:
882 # MVAPICH / MPICH
883 symlink_force(
884 os.path.join(mpi_home, 'include/mpio.h'), 'third_party/mpi/mpio.h')
885 symlink_force(
886 os.path.join(mpi_home, 'include/mpicxx.h'), 'third_party/mpi/mpicxx.h')
887 # TODO(gunan): avoid editing files in configure
888 sed_in_place('third_party/mpi/mpi.bzl', 'MPI_LIB_IS_OPENMPI=True',
889 'MPI_LIB_IS_OPENMPI=False')
890
891 if os.path.exists(os.path.join(mpi_home, 'lib/libmpi.so')):
892 symlink_force(
893 os.path.join(mpi_home, 'lib/libmpi.so'), 'third_party/mpi/libmpi.so')
894 else:
895 raise ValueError('Cannot find the MPI library file in %s/lib' % mpi_home)
896
897
898def set_mkl():
899 write_to_bazelrc('build:mkl --define with_mkl_support=true')
900 write_to_bazelrc('build:mkl --define using_mkl=true')
901 write_to_bazelrc('build:mkl -c opt')
902 write_to_bazelrc('build:mkl --copt="-DEIGEN_USE_VML"')
903 print(
904 'Add "--config=mkl" to your bazel command to build with MKL '
905 'support.\nPlease note that MKL on MacOS or windows is still not '
906 'supported.\nIf you would like to use a local MKL instead of '
907 'downloading, please set the environment variable \"TF_MKL_ROOT\" every '
908 'time before build.')
909
910
911def main():
912 # Make a copy of os.environ to be clear when functions and getting and setting
913 # environment variables.
914 environ_cp = dict(os.environ)
915
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700916 bazel_version = check_bazel_version('0.4.5')
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700917
918 reset_tf_configure_bazelrc()
919 cleanup_makefile()
A. Unique TensorFlower6252d292017-08-04 00:52:34 -0700920 setup_python(environ_cp, bazel_version)
A. Unique TensorFlower73ea2872017-07-25 13:30:03 -0700921 run_gen_git_source(environ_cp)
922
923 if is_windows():
924 environ_cp['TF_NEED_GCP'] = '0'
925 environ_cp['TF_NEED_HDFS'] = '0'
926 environ_cp['TF_NEED_JEMALLOC'] = '0'
927 environ_cp['TF_NEED_OPENCL'] = '0'
928 environ_cp['TF_CUDA_CLANG'] = '0'
929
930 if is_macos():
931 environ_cp['TF_NEED_JEMALLOC'] = '0'
932
933 set_build_var(environ_cp, 'TF_NEED_JEMALLOC', 'jemalloc as malloc',
934 'with_jemalloc', True)
935 set_build_var(environ_cp, 'TF_NEED_GCP', 'Google Cloud Platform',
936 'with_gcp_support', False)
937 set_build_var(environ_cp, 'TF_NEED_HDFS', 'Hadoop File System',
938 'with_hdfs_support', False)
939 set_build_var(environ_cp, 'TF_ENABLE_XLA', 'XLA JIT', 'with_xla_support',
940 False)
941 set_build_var(environ_cp, 'TF_NEED_VERBS', 'VERBS', 'with_verbs_support',
942 False)
943
944 set_action_env_var(environ_cp, 'TF_NEED_OPENCL', 'OpenCL', False)
945 if environ_cp.get('TF_NEED_OPENCL') == '1':
946 set_host_cxx_compiler(environ_cp)
947 set_host_c_compiler(environ_cp)
948 set_computecpp_toolkit_path(environ_cp)
949
950 set_action_env_var(environ_cp, 'TF_NEED_CUDA', 'CUDA', False)
951 if environ_cp.get('TF_NEED_CUDA') == '1':
952 set_tf_cuda_version(environ_cp)
953 set_tf_cunn_version(environ_cp)
954 set_tf_cuda_compute_capabilities(environ_cp)
955
956 set_tf_cuda_clang(environ_cp)
957 if environ_cp.get('TF_CUDA_CLANG') == '1':
958 # Set up which clang we should use as the cuda / host compiler.
959 set_clang_cuda_compiler_path(environ_cp)
960 else:
961 # Set up which gcc nvcc should use as the host compiler
962 # No need to set this on Windows
963 if not is_windows():
964 set_gcc_host_compiler_path(environ_cp)
965 set_other_cuda_vars(environ_cp)
966
967 set_build_var(environ_cp, 'TF_NEED_MPI', 'MPI', 'with_mpi_support', False)
968 if environ_cp.get('TF_NEED_MPI') == '1':
969 set_mpi_home(environ_cp)
970 set_other_mpi_vars(environ_cp)
971
972 set_cc_opt_flags(environ_cp)
973 set_mkl()
974
975
976if __name__ == '__main__':
977 main()