StyleFeatureEditor
169 строк · 7.1 Кб
1# Copyright (c) 2019, NVIDIA Corporation. All rights reserved.
2#
3# This work is made available under the Nvidia Source Code License-NC.
4# To view a copy of this license, visit
5# https://nvlabs.github.io/stylegan2/license.html
6
7"""TensorFlow custom ops builder.
8"""
9
10import os
11import re
12import uuid
13import hashlib
14import tempfile
15import shutil
16import tensorflow as tf
17from tensorflow.python.client import device_lib # pylint: disable=no-name-in-module
18
19#----------------------------------------------------------------------------
20# Global options.
21
22cuda_cache_path = os.path.join(os.path.dirname(__file__), '_cudacache')
23cuda_cache_version_tag = 'v1'
24do_not_hash_included_headers = False # Speed up compilation by assuming that headers included by the CUDA code never change. Unsafe!
25verbose = True # Print status messages to stdout.
26
27compiler_bindir_search_path = [
28'C:/Program Files (x86)/Microsoft Visual Studio/2017/Community/VC/Tools/MSVC/14.14.26428/bin/Hostx64/x64',
29'C:/Program Files (x86)/Microsoft Visual Studio/2019/Community/VC/Tools/MSVC/14.23.28105/bin/Hostx64/x64',
30'C:/Program Files (x86)/Microsoft Visual Studio 14.0/vc/bin',
31]
32
33#----------------------------------------------------------------------------
34# Internal helper funcs.
35
36def _find_compiler_bindir():
37for compiler_path in compiler_bindir_search_path:
38if os.path.isdir(compiler_path):
39return compiler_path
40return None
41
42def _get_compute_cap(device):
43caps_str = device.physical_device_desc
44m = re.search('compute capability: (\\d+).(\\d+)', caps_str)
45major = m.group(1)
46minor = m.group(2)
47return (major, minor)
48
49def _get_cuda_gpu_arch_string():
50gpus = [x for x in device_lib.list_local_devices() if x.device_type == 'GPU']
51if len(gpus) == 0:
52raise RuntimeError('No GPU devices found')
53(major, minor) = _get_compute_cap(gpus[0])
54return 'sm_%s%s' % (major, minor)
55
56def _run_cmd(cmd):
57with os.popen(cmd) as pipe:
58output = pipe.read()
59status = pipe.close()
60if status is not None:
61raise RuntimeError('NVCC returned an error. See below for full command line and output log:\n\n%s\n\n%s' % (cmd, output))
62
63def _prepare_nvcc_cli(opts):
64cmd = 'nvcc ' + opts.strip()
65cmd += ' --disable-warnings'
66cmd += ' --include-path "%s"' % tf.sysconfig.get_include()
67cmd += ' --include-path "%s"' % os.path.join(tf.sysconfig.get_include(), 'external', 'protobuf_archive', 'src')
68cmd += ' --include-path "%s"' % os.path.join(tf.sysconfig.get_include(), 'external', 'com_google_absl')
69cmd += ' --include-path "%s"' % os.path.join(tf.sysconfig.get_include(), 'external', 'eigen_archive')
70
71compiler_bindir = _find_compiler_bindir()
72if compiler_bindir is None:
73# Require that _find_compiler_bindir succeeds on Windows. Allow
74# nvcc to use whatever is the default on Linux.
75if os.name == 'nt':
76raise RuntimeError('Could not find MSVC/GCC/CLANG installation on this computer. Check compiler_bindir_search_path list in "%s".' % __file__)
77else:
78cmd += ' --compiler-bindir "%s"' % compiler_bindir
79cmd += ' 2>&1'
80return cmd
81
82#----------------------------------------------------------------------------
83# Main entry point.
84
85_plugin_cache = dict()
86
87def get_plugin(cuda_file):
88cuda_file_base = os.path.basename(cuda_file)
89cuda_file_name, cuda_file_ext = os.path.splitext(cuda_file_base)
90
91# Already in cache?
92if cuda_file in _plugin_cache:
93return _plugin_cache[cuda_file]
94
95# Setup plugin.
96if verbose:
97print('Setting up TensorFlow plugin "%s": ' % cuda_file_base, end='', flush=True)
98try:
99# Hash CUDA source.
100md5 = hashlib.md5()
101with open(cuda_file, 'rb') as f:
102md5.update(f.read())
103md5.update(b'\n')
104
105# Hash headers included by the CUDA code by running it through the preprocessor.
106if not do_not_hash_included_headers:
107if verbose:
108print('Preprocessing... ', end='', flush=True)
109with tempfile.TemporaryDirectory() as tmp_dir:
110tmp_file = os.path.join(tmp_dir, cuda_file_name + '_tmp' + cuda_file_ext)
111_run_cmd(_prepare_nvcc_cli('"%s" --preprocess -o "%s" --keep --keep-dir "%s"' % (cuda_file, tmp_file, tmp_dir)))
112with open(tmp_file, 'rb') as f:
113bad_file_str = ('"' + cuda_file.replace('\\', '/') + '"').encode('utf-8') # __FILE__ in error check macros
114good_file_str = ('"' + cuda_file_base + '"').encode('utf-8')
115for ln in f:
116if not ln.startswith(b'# ') and not ln.startswith(b'#line '): # ignore line number pragmas
117ln = ln.replace(bad_file_str, good_file_str)
118md5.update(ln)
119md5.update(b'\n')
120
121# Select compiler options.
122compile_opts = ''
123if os.name == 'nt':
124compile_opts += '"%s"' % os.path.join(tf.sysconfig.get_lib(), 'python', '_pywrap_tensorflow_internal.lib')
125elif os.name == 'posix':
126compile_opts += '"%s"' % os.path.join(tf.sysconfig.get_lib(), 'python', '_pywrap_tensorflow_internal.so')
127compile_opts += ' --compiler-options \'-fPIC -D_GLIBCXX_USE_CXX11_ABI=0\''
128else:
129assert False # not Windows or Linux, w00t?
130compile_opts += ' --gpu-architecture=%s' % _get_cuda_gpu_arch_string()
131compile_opts += ' --use_fast_math'
132nvcc_cmd = _prepare_nvcc_cli(compile_opts)
133
134# Hash build configuration.
135md5.update(('nvcc_cmd: ' + nvcc_cmd).encode('utf-8') + b'\n')
136md5.update(('tf.VERSION: ' + tf.VERSION).encode('utf-8') + b'\n')
137md5.update(('cuda_cache_version_tag: ' + cuda_cache_version_tag).encode('utf-8') + b'\n')
138
139# Compile if not already compiled.
140bin_file_ext = '.dll' if os.name == 'nt' else '.so'
141bin_file = os.path.join(cuda_cache_path, cuda_file_name + '_' + md5.hexdigest() + bin_file_ext)
142if not os.path.isfile(bin_file):
143if verbose:
144print('Compiling... ', end='', flush=True)
145with tempfile.TemporaryDirectory() as tmp_dir:
146tmp_file = os.path.join(tmp_dir, cuda_file_name + '_tmp' + bin_file_ext)
147_run_cmd(nvcc_cmd + ' "%s" --shared -o "%s" --keep --keep-dir "%s"' % (cuda_file, tmp_file, tmp_dir))
148os.makedirs(cuda_cache_path, exist_ok=True)
149intermediate_file = os.path.join(cuda_cache_path, cuda_file_name + '_' + uuid.uuid4().hex + '_tmp' + bin_file_ext)
150shutil.copyfile(tmp_file, intermediate_file)
151os.rename(intermediate_file, bin_file) # atomic
152
153# Load.
154if verbose:
155print('Loading... ', end='', flush=True)
156plugin = tf.load_op_library(bin_file)
157
158# Add to cache.
159_plugin_cache[cuda_file] = plugin
160if verbose:
161print('Done.', flush=True)
162return plugin
163
164except:
165if verbose:
166print('Failed!', flush=True)
167raise
168
169#----------------------------------------------------------------------------
170