-
Notifications
You must be signed in to change notification settings - Fork 0
/
setup.py
394 lines (322 loc) · 13.1 KB
/
setup.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import distutils
from distutils.spawn import find_executable
from distutils import sysconfig, dep_util, log
import setuptools
import setuptools.command.build_py
import setuptools.command.develop
import setuptools.command.build_ext
from contextlib import contextmanager
import platform
import fnmatch
from collections import namedtuple
import os
import subprocess
import sys
from textwrap import dedent
from tools.ninja_builder import NinjaBuilder, ninja_build_ext
import glob
import json
try:
import ninja
WITH_NINJA = True
except ImportError:
WITH_NINJA = False
TOP_DIR = os.path.realpath(os.path.dirname(__file__))
SRC_DIR = os.path.join(TOP_DIR, 'onnx')
TP_DIR = os.path.join(TOP_DIR, 'third_party')
PROTOC = find_executable('protoc')
ONNX_ML = bool(os.getenv('ONNX_ML') == '1')
install_requires = ['six']
setup_requires = []
tests_require = []
################################################################################
# Version
################################################################################
try:
git_version = subprocess.check_output(['git', 'rev-parse', 'HEAD'],
cwd=TOP_DIR).decode('ascii').strip()
except subprocess.CalledProcessError:
git_version = None
with open(os.path.join(TOP_DIR, 'VERSION_NUMBER')) as version_file:
VersionInfo = namedtuple('VersionInfo', ['version', 'git_version'])(
version=version_file.read().strip(),
git_version=git_version
)
################################################################################
# Utilities
################################################################################
def die(msg):
log.error(msg)
sys.exit(1)
def true_or_die(b, msg):
if not b:
die(msg)
return b
def recursive_glob(directory, pattern):
return [os.path.join(dirpath, f)
for dirpath, dirnames, files in os.walk(directory)
for f in fnmatch.filter(files, pattern)]
################################################################################
# Pre Check
################################################################################
true_or_die(PROTOC, 'Could not find "protoc" executable!')
################################################################################
# Dependencies
################################################################################
class Dependency(object):
def __init__(self):
self.include_dirs = []
self.libraries = []
class Python(Dependency):
def __init__(self):
super(Python, self).__init__()
self.include_dirs = [sysconfig.get_python_inc()]
class Protobuf(Dependency):
def __init__(self):
super(Protobuf, self).__init__()
# TODO: allow user specify protobuf include_dirs libraries with flags
use_conda = os.getenv('CONDA_PREFIX') and platform.system() == 'Windows'
libs = []
if os.getenv('PROTOBUF_LIBDIR'):
libs.append(os.path.join(os.getenv('PROTOBUF_LIBDIR'), "libprotobuf"))
elif use_conda:
libs.append(os.path.join(os.getenv('CONDA_PREFIX'), "Library", "lib", "libprotobuf"))
else:
libs.append("protobuf")
includes = []
if os.getenv('PROTOBUF_INCDIR'):
includes.append(os.path.join(os.getenv('PROTOBUF_INCDIR')))
elif use_conda:
includes.append(os.path.join(os.getenv('CONDA_PREFIX'), "Library", "Include"))
self.libraries = libs
self.include_dirs = includes
class Pybind11(Dependency):
def __init__(self):
super(Pybind11, self).__init__()
self.include_dirs = [os.path.join(TP_DIR, 'pybind11', 'include')]
################################################################################
# Customized commands
################################################################################
class ONNXCommand(setuptools.Command):
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
class build_proto_in(ONNXCommand):
def run(self):
gen_script = os.path.join(SRC_DIR, 'gen_proto.py')
stems = ['onnx', 'onnx-operators']
in_files = [gen_script]
out_files = []
for stem in stems:
in_files.append(
os.path.join(SRC_DIR, '{}.in.proto'.format(stem)))
out_files.extend([
os.path.join(SRC_DIR, '{}.proto'.format(stem)),
os.path.join(SRC_DIR, '{}.proto3'.format(stem)),
os.path.join(SRC_DIR, '{}-ml.proto'.format(stem)),
os.path.join(SRC_DIR, '{}-ml.proto3'.format(stem)),
])
if self.force or any(dep_util.newer_group(in_files, o)
for o in out_files):
log.info('compiling *.in.proto')
subprocess.check_call([sys.executable, gen_script] + stems)
class build_proto(ONNXCommand):
def run(self):
self.run_command('build_proto_in')
stems = ['onnx', 'onnx-operators']
for stem in stems:
if ONNX_ML:
proto_base = '{}-ml'.format(stem)
else:
proto_base = stem
proto = os.path.join(SRC_DIR, '{}.proto'.format(proto_base))
# "-" is invalid in python module name, replaces '-' with '_'
pb_py = os.path.join(SRC_DIR, '{}_pb.py'.format(
stem.replace('-', '_')))
pb2_py = os.path.join(SRC_DIR, '{}_pb2.py'.format(
proto_base.replace('-', '_')))
outputs = [
pb_py,
pb2_py,
os.path.join(SRC_DIR, '{}.pb.cc'.format(proto_base)),
os.path.join(SRC_DIR, '{}.pb.h'.format(proto_base)),
]
if self.force or any(dep_util.newer(proto, o) for o in outputs):
log.info('compiling {}'.format(proto))
subprocess.check_call([
PROTOC,
'--proto_path', SRC_DIR,
'--python_out', SRC_DIR,
'--cpp_out', SRC_DIR,
proto
])
log.info('generating {}'.format(pb_py))
with open(pb_py, 'w') as f:
f.write(dedent('''\
# This file is generated by setup.py. DO NOT EDIT!
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from .{} import * # noqa
'''.format(os.path.splitext(os.path.basename(pb2_py))[0])))
class create_version(ONNXCommand):
def run(self):
with open(os.path.join(SRC_DIR, 'version.py'), 'w') as f:
f.write(dedent('''\
# This file is generated by setup.py. DO NOT EDIT!
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
version = '{version}'
git_version = '{git_version}'
'''.format(**dict(VersionInfo._asdict()))))
class build_py(setuptools.command.build_py.build_py):
def run(self):
self.run_command('create_version')
self.run_command('build_proto')
return setuptools.command.build_py.build_py.run(self)
class develop(setuptools.command.develop.develop):
def run(self):
self.run_command('create_version')
setuptools.command.develop.develop.run(self)
self.create_compile_commands()
def create_compile_commands(self):
def load(filename):
with open(filename) as f:
return json.load(f)
ninja_files = glob.glob('build/*_compile_commands.json')
all_commands = [entry for f in ninja_files for entry in load(f)]
with open('compile_commands.json', 'w') as f:
json.dump(all_commands, f, indent=2)
build_ext_parent = ninja_build_ext if WITH_NINJA \
else setuptools.command.build_ext.build_ext
class build_ext(build_ext_parent):
def run(self):
self.run_command('build_proto')
for ext in self.extensions:
ext.pre_run()
return setuptools.command.build_ext.build_ext.run(self)
cmdclass = {
'build_proto': build_proto,
'build_proto_in': build_proto_in,
'create_version': create_version,
'build_py': build_py,
'develop': develop,
'build_ext': build_ext,
}
################################################################################
# Extensions
################################################################################
class ONNXExtension(setuptools.Extension):
def pre_run(self):
pass
def create_extension(ExtType, name, sources, dependencies, extra_link_args, extra_objects):
include_dirs = sum([dep.include_dirs for dep in dependencies], [TOP_DIR])
libraries = sum([dep.libraries for dep in dependencies], [])
extra_compile_args=['-std=c++11']
if sys.platform == 'darwin':
extra_compile_args.append('-stdlib=libc++')
if os.getenv('CONDA_PREFIX'):
include_dirs.append(os.path.join(os.getenv('CONDA_PREFIX'), "include"))
if platform.system() == 'Windows':
extra_compile_args.append('/MT')
macros = []
if ONNX_ML:
macros = [('ONNX_ML', '1')]
return ExtType(
name=name,
define_macros = macros,
sources=sources,
include_dirs=include_dirs,
libraries=libraries,
extra_compile_args=extra_compile_args,
extra_objects=extra_objects,
extra_link_args=extra_link_args,
language='c++',
)
class ONNXCpp2PyExtension(setuptools.Extension):
def pre_run(self):
self.sources = recursive_glob(SRC_DIR, '*.cc')
if ONNX_ML:
# Remove onnx.pb.cc, onnx-operators.pb.cc from sources.
sources_filter = [os.path.join(SRC_DIR, "onnx.pb.cc"), os.path.join(SRC_DIR, "onnx-operators.pb.cc")]
else:
# Remove onnx-ml.pb.cc, onnx-operators-ml.pb.cc from sources.
sources_filter = [os.path.join(SRC_DIR, "onnx-ml.pb.cc"), os.path.join(SRC_DIR, "onnx-operators-ml.pb.cc")]
for source_filter in sources_filter:
if source_filter in self.sources:
self.sources.remove(source_filter)
cpp2py_deps = [Pybind11(), Python()]
cpp2py_link_args = []
cpp2py_extra_objects = []
build_for_release = os.getenv('ONNX_BINARY_BUILD')
if build_for_release and platform.system() == 'Linux':
# Cribbed from PyTorch
# get path of libstdc++ and link manually.
# for reasons unknown, -static-libstdc++ doesn't fully link some symbols
CXXNAME = os.getenv('CXX', 'g++')
path = subprocess.check_output([CXXNAME, '-print-file-name=libstdc++.a'])
path = path[:-1]
if type(path) != str: # python 3
path = path.decode(sys.stdout.encoding)
cpp2py_link_args += [path]
# Hard coded look for the static libraries from Conda
assert os.getenv('CONDA_PREFIX')
cpp2py_extra_objects.extend([os.path.join(os.getenv('CONDA_PREFIX'), 'lib', 'libprotobuf.a'),
os.path.join(os.getenv('CONDA_PREFIX'), 'lib', 'libprotobuf-lite.a')])
else:
cpp2py_deps.append(Protobuf())
ext_modules = [
create_extension(ONNXCpp2PyExtension,
str('onnx.onnx_cpp2py_export'),
sources=[], # sources will be propagated in pre_run
dependencies=cpp2py_deps,
extra_link_args=cpp2py_link_args,
extra_objects=cpp2py_extra_objects)
]
################################################################################
# Packages
################################################################################
# no need to do fancy stuff so far
packages = setuptools.find_packages()
install_requires.extend(['protobuf', 'numpy'])
################################################################################
# Test
################################################################################
setup_requires.append('pytest-runner')
tests_require.append('pytest-cov')
tests_require.append('nbval')
tests_require.append('tabulate')
################################################################################
# Final
################################################################################
setuptools.setup(
name="onnx",
version=VersionInfo.version,
description="Open Neural Network Exchange",
ext_modules=ext_modules,
cmdclass=cmdclass,
packages=packages,
include_package_data=True,
install_requires=install_requires,
setup_requires=setup_requires,
tests_require=tests_require,
author='bddppq',
author_email='jbai@fb.com',
url='https://github.com/onnx/onnx',
entry_points={
'console_scripts': [
'check-model = onnx.bin.checker:check_model',
'check-node = onnx.bin.checker:check_node',
'backend-test-tools = onnx.backend.test.cmd_tools:main',
]
},
)