forked from triton-inference-server/server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
build.py
executable file
·1549 lines (1350 loc) · 55.9 KB
/
build.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
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# Copyright (c) 2020-2021, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of NVIDIA CORPORATION nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
# OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import argparse
import logging
import os.path
import multiprocessing
import pathlib
import platform
import shutil
import subprocess
import sys
import traceback
from distutils.dir_util import copy_tree
#
# Build Triton Inference Server.
#
# By default build.py builds the Triton container. The TRITON_VERSION
# file indicates the Triton version and TRITON_VERSION_MAP is used to
# determine the corresponding container version and upstream container
# version (upstream containers are dependencies required by
# Triton). These versions may be overridden. See docs/build.md for
# more information.
# Map from Triton version to corresponding container and component versions.
#
# triton version ->
# (triton container version,
# upstream container version,
# ORT version,
# ORT OpenVINO version (use None to disable OpenVINO in ORT),
# Standalone OpenVINO version,
# DCGM version
# )
#
# Currently the OpenVINO versions used in ORT and standalone must
# match because of the way dlopen works with loading the backends. If
# different versions are used then one backend or the other will
# incorrectly load the other version of the openvino libraries.
#
TRITON_VERSION_MAP = {
'2.15.0dev': (
'21.10dev', # triton container
'21.08', # upstream container
'1.8.1', # ORT
'2021.2.200', # ORT OpenVINO
'2021.2', # Standalone OpenVINO
'2.2.9') # DCGM version
}
EXAMPLE_BACKENDS = ['identity', 'square', 'repeat']
CORE_BACKENDS = ['ensemble']
NONCORE_BACKENDS = [
'tensorflow1', 'tensorflow2', 'onnxruntime', 'python', 'dali', 'pytorch',
'openvino', 'fil', 'fastertransformer', 'tensorrt', 'armnn_tflite'
]
EXAMPLE_REPOAGENTS = ['checksum']
FLAGS = None
def log(msg, force=False):
if force or not FLAGS.quiet:
try:
print(msg, file=sys.stderr)
except Exception:
print('<failed to log>', file=sys.stderr)
def log_verbose(msg):
if FLAGS.verbose:
log(msg, force=True)
def fail(msg):
fail_if(True, msg)
def target_platform():
if FLAGS.target_platform is not None:
return FLAGS.target_platform
return platform.system().lower()
def target_machine():
if FLAGS.target_machine is not None:
return FLAGS.target_machine
return platform.machine().lower()
def fail_if(p, msg):
if p:
print('error: {}'.format(msg), file=sys.stderr)
sys.exit(1)
def mkdir(path):
log_verbose('mkdir: {}'.format(path))
pathlib.Path(path).mkdir(parents=True, exist_ok=True)
def rmdir(path):
log_verbose('rmdir: {}'.format(path))
shutil.rmtree(path, ignore_errors=True)
def cpdir(src, dest):
log_verbose('cpdir: {} -> {}'.format(src, dest))
copy_tree(src, dest, preserve_symlinks=1)
def untar(targetdir, tarfile):
log_verbose('untar {} into {}'.format(tarfile, targetdir))
p = subprocess.Popen(['tar', '--strip-components=1', '-xf', tarfile],
cwd=targetdir)
p.wait()
fail_if(p.returncode != 0,
'untar {} into {} failed'.format(tarfile, targetdir))
def gitclone(cwd, repo, tag, subdir, org):
# If 'tag' starts with "pull/" then it must be of form
# "pull/<pr>/head". We just clone at "main" and then fetch the
# reference onto a new branch we name "tritonbuildref".
if tag.startswith("pull/"):
log_verbose('git clone of repo "{}" at ref "{}"'.format(repo, tag))
p = subprocess.Popen([
'git', 'clone', '--recursive', '--depth=1', '{}/{}.git'.format(
org, repo), subdir
],
cwd=cwd)
p.wait()
fail_if(p.returncode != 0,
'git clone of repo "{}" at branch "main" failed'.format(repo))
log_verbose('git fetch of ref "{}"'.format(tag))
p = subprocess.Popen(
['git', 'fetch', 'origin', '{}:tritonbuildref'.format(tag)],
cwd=os.path.join(cwd, subdir))
p.wait()
fail_if(p.returncode != 0, 'git fetch of ref "{}" failed'.format(tag))
log_verbose('git checkout of tritonbuildref')
p = subprocess.Popen(['git', 'checkout', 'tritonbuildref'],
cwd=os.path.join(cwd, subdir))
p.wait()
fail_if(p.returncode != 0,
'git checkout of branch "tritonbuildref" failed')
else:
log_verbose('git clone of repo "{}" at tag "{}"'.format(repo, tag))
p = subprocess.Popen([
'git', 'clone', '--recursive', '--single-branch', '--depth=1', '-b',
tag, '{}/{}.git'.format(org, repo), subdir
],
cwd=cwd)
p.wait()
fail_if(p.returncode != 0,
'git clone of repo "{}" at tag "{}" failed'.format(repo, tag))
def prebuild_command():
p = subprocess.Popen(FLAGS.container_prebuild_command.split())
p.wait()
fail_if(p.returncode != 0, 'container prebuild cmd failed')
def cmake(cwd, args):
log_verbose('cmake {}'.format(args))
p = subprocess.Popen([
'cmake',
] + args, cwd=cwd)
p.wait()
fail_if(p.returncode != 0, 'cmake failed')
def makeinstall(cwd, target='install'):
log_verbose('make {}'.format(target))
if target_platform() == 'windows':
verbose_flag = '-v:detailed' if FLAGS.verbose else '-clp:ErrorsOnly'
buildtype_flag = '-p:Configuration={}'.format(FLAGS.build_type)
p = subprocess.Popen([
'msbuild.exe', '-m:{}'.format(str(FLAGS.build_parallel)),
verbose_flag, buildtype_flag, '{}.vcxproj'.format(target)
],
cwd=cwd)
else:
verbose_flag = 'VERBOSE=1' if FLAGS.verbose else 'VERBOSE=0'
p = subprocess.Popen(
['make', '-j',
str(FLAGS.build_parallel), verbose_flag, target],
cwd=cwd)
p.wait()
fail_if(p.returncode != 0, 'make {} failed'.format(target))
def cmake_enable(flag):
return 'ON' if flag else 'OFF'
def core_cmake_args(components, backends, install_dir):
cargs = [
'-DCMAKE_BUILD_TYPE={}'.format(FLAGS.build_type),
'-DCMAKE_INSTALL_PREFIX:PATH={}'.format(install_dir),
'-DTRITON_COMMON_REPO_TAG:STRING={}'.format(components['common']),
'-DTRITON_CORE_REPO_TAG:STRING={}'.format(components['core']),
'-DTRITON_BACKEND_REPO_TAG:STRING={}'.format(components['backend']),
'-DTRITON_THIRD_PARTY_REPO_TAG:STRING={}'.format(
components['thirdparty'])
]
cargs.append('-DTRITON_ENABLE_LOGGING:BOOL={}'.format(
cmake_enable(FLAGS.enable_logging)))
cargs.append('-DTRITON_ENABLE_STATS:BOOL={}'.format(
cmake_enable(FLAGS.enable_stats)))
cargs.append('-DTRITON_ENABLE_METRICS:BOOL={}'.format(
cmake_enable(FLAGS.enable_metrics)))
cargs.append('-DTRITON_ENABLE_METRICS_GPU:BOOL={}'.format(
cmake_enable(FLAGS.enable_gpu_metrics)))
cargs.append('-DTRITON_ENABLE_TRACING:BOOL={}'.format(
cmake_enable(FLAGS.enable_tracing)))
cargs.append('-DTRITON_ENABLE_NVTX:BOOL={}'.format(
cmake_enable(FLAGS.enable_nvtx)))
cargs.append('-DTRITON_ENABLE_GPU:BOOL={}'.format(
cmake_enable(FLAGS.enable_gpu)))
cargs.append('-DTRITON_MIN_COMPUTE_CAPABILITY={}'.format(
FLAGS.min_compute_capability))
# If building the ArmNN TFLite backend set enable MALI GPU
if 'armnn_tflite' in backends:
cargs.append('-DTRITON_ENABLE_MALI_GPU:BOOL={}'.format(
cmake_enable(FLAGS.enable_mali_gpu)))
cargs.append('-DTRITON_ENABLE_GRPC:BOOL={}'.format(
cmake_enable('grpc' in FLAGS.endpoint)))
cargs.append('-DTRITON_ENABLE_HTTP:BOOL={}'.format(
cmake_enable('http' in FLAGS.endpoint)))
cargs.append('-DTRITON_ENABLE_SAGEMAKER:BOOL={}'.format(
cmake_enable('sagemaker' in FLAGS.endpoint)))
cargs.append('-DTRITON_ENABLE_GCS:BOOL={}'.format(
cmake_enable('gcs' in FLAGS.filesystem)))
cargs.append('-DTRITON_ENABLE_S3:BOOL={}'.format(
cmake_enable('s3' in FLAGS.filesystem)))
cargs.append('-DTRITON_ENABLE_AZURE_STORAGE:BOOL={}'.format(
cmake_enable('azure_storage' in FLAGS.filesystem)))
cargs.append('-DTRITON_ENABLE_TENSORFLOW={}'.format(
cmake_enable(('tensorflow1' in backends) or
('tensorflow2' in backends))))
for be in (CORE_BACKENDS + NONCORE_BACKENDS):
if not be.startswith('tensorflow'):
cargs.append('-DTRITON_ENABLE_{}={}'.format(
be.upper(), cmake_enable(be in backends)))
if be == 'tensorrt':
cargs += tensorrt_cmake_args()
if (be in CORE_BACKENDS) and (be in backends):
if be == 'ensemble':
pass
else:
fail('unknown core backend {}'.format(be))
# If TRITONBUILD_* is defined in the env then we use it to set
# corresponding cmake value.
for evar, eval in os.environ.items():
if evar.startswith('TRITONBUILD_'):
cargs.append('-D{}={}'.format(evar[len('TRITONBUILD_'):], eval))
cargs.append(FLAGS.cmake_dir)
return cargs
def repoagent_repo(ra):
return '{}_repository_agent'.format(ra)
def repoagent_cmake_args(images, components, ra, install_dir):
if ra in EXAMPLE_REPOAGENTS:
args = []
else:
fail('unknown agent {}'.format(ra))
cargs = args + [
'-DCMAKE_BUILD_TYPE={}'.format(FLAGS.build_type),
'-DCMAKE_INSTALL_PREFIX:PATH={}'.format(install_dir),
'-DTRITON_COMMON_REPO_TAG:STRING={}'.format(components['common']),
'-DTRITON_CORE_REPO_TAG:STRING={}'.format(components['core'])
]
cargs.append('-DTRITON_ENABLE_GPU:BOOL={}'.format(
cmake_enable(FLAGS.enable_gpu)))
# If TRITONBUILD_* is defined in the env then we use it to set
# corresponding cmake value.
for evar, eval in os.environ.items():
if evar.startswith('TRITONBUILD_'):
cargs.append('-D{}={}'.format(evar[len('TRITONBUILD_'):], eval))
cargs.append('..')
return cargs
def backend_repo(be):
if (be == 'tensorflow1') or (be == 'tensorflow2'):
return 'tensorflow_backend'
return '{}_backend'.format(be)
def backend_cmake_args(images, components, be, install_dir, library_paths):
if be == 'onnxruntime':
args = onnxruntime_cmake_args(images, library_paths)
elif be == 'openvino':
args = openvino_cmake_args()
elif be == 'tensorflow1':
args = tensorflow_cmake_args(1, images, library_paths)
elif be == 'tensorflow2':
args = tensorflow_cmake_args(2, images, library_paths)
elif be == 'python':
args = []
elif be == 'dali':
args = dali_cmake_args()
elif be == 'pytorch':
args = pytorch_cmake_args(images)
elif be == 'armnn_tflite':
args = armnn_tflite_cmake_args()
elif be == 'fil':
args = fil_cmake_args(images)
elif be == 'fastertransformer':
args = []
elif be == 'tensorrt':
args = tensorrt_cmake_args()
elif be in EXAMPLE_BACKENDS:
args = []
else:
fail('unknown backend {}'.format(be))
cargs = args + [
'-DCMAKE_BUILD_TYPE={}'.format(FLAGS.build_type),
'-DCMAKE_INSTALL_PREFIX:PATH={}'.format(install_dir),
'-DTRITON_COMMON_REPO_TAG:STRING={}'.format(components['common']),
'-DTRITON_CORE_REPO_TAG:STRING={}'.format(components['core']),
'-DTRITON_BACKEND_REPO_TAG:STRING={}'.format(components['backend'])
]
cargs.append('-DTRITON_ENABLE_GPU:BOOL={}'.format(
cmake_enable(FLAGS.enable_gpu)))
cargs.append('-DTRITON_ENABLE_MALI_GPU:BOOL={}'.format(
cmake_enable(FLAGS.enable_mali_gpu)))
# If TRITONBUILD_* is defined in the env then we use it to set
# corresponding cmake value.
for evar, eval in os.environ.items():
if evar.startswith('TRITONBUILD_'):
cargs.append('-D{}={}'.format(evar[len('TRITONBUILD_'):], eval))
cargs.append('..')
return cargs
def pytorch_cmake_args(images):
if "pytorch" in images:
image = images["pytorch"]
else:
image = 'nvcr.io/nvidia/pytorch:{}-py3'.format(
FLAGS.upstream_container_version)
return [
'-DTRITON_PYTORCH_DOCKER_IMAGE={}'.format(image),
]
def onnxruntime_cmake_args(images, library_paths):
cargs = [
'-DTRITON_BUILD_ONNXRUNTIME_VERSION={}'.format(
TRITON_VERSION_MAP[FLAGS.version][2])
]
if FLAGS.enable_gpu:
cargs.append('-DTRITON_ENABLE_ONNXRUNTIME_TENSORRT=ON')
else:
cargs.append('-DTRITON_ENABLE_GPU=OFF')
# If platform is jetpack do not use docker based build
if target_platform() == 'jetpack':
ort_lib_path = library_paths['onnxruntime'] + "/lib"
ort_include_path = library_paths['onnxruntime'] + "/include"
cargs += [
'-DTRITON_ONNXRUNTIME_INCLUDE_PATHS={}'.format(ort_include_path),
'-DTRITON_ONNXRUNTIME_LIB_PATHS={}'.format(ort_lib_path),
'-DTRITON_ENABLE_ONNXRUNTIME_OPENVINO=OFF'
]
else:
if target_platform() == 'windows':
if 'base' in images:
cargs.append('-DTRITON_BUILD_CONTAINER={}'.format(
images['base']))
else:
if 'base' in images:
cargs.append('-DTRITON_BUILD_CONTAINER={}'.format(
images['base']))
else:
cargs.append('-DTRITON_BUILD_CONTAINER_VERSION={}'.format(
TRITON_VERSION_MAP[FLAGS.version][1]))
if ((target_machine() != 'aarch64') and
(TRITON_VERSION_MAP[FLAGS.version][3] is not None)):
cargs.append('-DTRITON_ENABLE_ONNXRUNTIME_OPENVINO=ON')
cargs.append(
'-DTRITON_BUILD_ONNXRUNTIME_OPENVINO_VERSION={}'.format(
TRITON_VERSION_MAP[FLAGS.version][3]))
return cargs
def openvino_cmake_args():
cargs = [
'-DTRITON_BUILD_OPENVINO_VERSION={}'.format(
TRITON_VERSION_MAP[FLAGS.version][4]),
]
if target_platform() == 'windows':
if 'base' in images:
cargs.append('-DTRITON_BUILD_CONTAINER={}'.format(images['base']))
else:
if 'base' in images:
cargs.append('-DTRITON_BUILD_CONTAINER={}'.format(images['base']))
else:
cargs.append('-DTRITON_BUILD_CONTAINER_VERSION={}'.format(
TRITON_VERSION_MAP[FLAGS.version][1]))
return cargs
def tensorrt_cmake_args():
cargs = [
'-DTRITON_ENABLE_NVTX:BOOL={}'.format(cmake_enable(FLAGS.enable_nvtx))
]
if target_platform() == 'windows':
cargs.append('-DTRITON_TENSORRT_INCLUDE_PATHS=c:/TensorRT/include')
return cargs
def tensorflow_cmake_args(ver, images, library_paths):
backend_name = "tensorflow{}".format(ver)
# If platform is jetpack do not use docker images
extra_args = []
if target_platform() == 'jetpack':
if backend_name in library_paths:
extra_args = [
'-DTRITON_TENSORFLOW_LIB_PATHS={}'.format(
library_paths[backend_name])
]
else:
# If a specific TF image is specified use it, otherwise pull from NGC.
if backend_name in images:
image = images[backend_name]
else:
image = 'nvcr.io/nvidia/tensorflow:{}-tf{}-py3'.format(
FLAGS.upstream_container_version, ver)
extra_args = ['-DTRITON_TENSORFLOW_DOCKER_IMAGE={}'.format(image)]
return ['-DTRITON_TENSORFLOW_VERSION={}'.format(ver)] + extra_args
def dali_cmake_args():
return [
'-DTRITON_DALI_SKIP_DOWNLOAD=OFF',
]
def armnn_tflite_cmake_args():
return [
'-DJOBS={}'.format(multiprocessing.cpu_count()),
]
def install_dcgm_libraries(dcgm_version, target_machine):
if dcgm_version == '':
fail(
'unable to determine default repo-tag, DCGM version not known for {}'
.format(FLAGS.version))
return ''
else:
if target_machine == 'aarch64':
return '''
ENV DCGM_VERSION {}
# Install DCGM. Steps from https://developer.nvidia.com/dcgm#Downloads
RUN wget https://developer.download.nvidia.com/compute/cuda/repos/ubuntu2004/sbsa/cuda-ubuntu2004.pin && \
mv cuda-ubuntu2004.pin /etc/apt/preferences.d/cuda-repository-pin-600 && \
apt-key adv --fetch-keys https://developer.download.nvidia.com/compute/cuda/repos/ubuntu2004/sbsa/7fa2af80.pub && \
add-apt-repository "deb https://developer.download.nvidia.com/compute/cuda/repos/ubuntu2004/sbsa/ /" && \
apt-get update && apt-get install -y datacenter-gpu-manager=1:{}
'''.format(dcgm_version, dcgm_version)
else:
return '''
ENV DCGM_VERSION {}
# Install DCGM. Steps from https://developer.nvidia.com/dcgm#Downloads
RUN wget https://developer.download.nvidia.com/compute/cuda/repos/ubuntu2004/x86_64/cuda-ubuntu2004.pin && \
mv cuda-ubuntu2004.pin /etc/apt/preferences.d/cuda-repository-pin-600 && \
apt-key adv --fetch-keys https://developer.download.nvidia.com/compute/cuda/repos/ubuntu2004/x86_64/7fa2af80.pub && \
add-apt-repository "deb https://developer.download.nvidia.com/compute/cuda/repos/ubuntu2004/x86_64/ /" && \
apt-get update && apt-get install -y datacenter-gpu-manager=1:{}
'''.format(dcgm_version, dcgm_version)
def fil_cmake_args(images):
cargs = ['-DTRITON_FIL_DOCKER_BUILD=ON']
if 'base' in images:
cargs.append('-DTRITON_BUILD_CONTAINER={}'.format(images['base']))
else:
cargs.append('-DTRITON_BUILD_CONTAINER_VERSION={}'.format(
TRITON_VERSION_MAP[FLAGS.version][1]))
return cargs
def get_container_versions(version, container_version,
upstream_container_version):
if container_version is None:
if version not in TRITON_VERSION_MAP:
fail('container version not known for {}'.format(version))
container_version = TRITON_VERSION_MAP[version][0]
if upstream_container_version is None:
if version not in TRITON_VERSION_MAP:
fail('upstream container version not known for {}'.format(version))
upstream_container_version = TRITON_VERSION_MAP[version][1]
return container_version, upstream_container_version
def create_dockerfile_buildbase(ddir, dockerfile_name, argmap):
df = '''
ARG TRITON_VERSION={}
ARG TRITON_CONTAINER_VERSION={}
ARG BASE_IMAGE={}
'''.format(argmap['TRITON_VERSION'], argmap['TRITON_CONTAINER_VERSION'],
argmap['BASE_IMAGE'])
df += '''
FROM ${BASE_IMAGE}
ARG TRITON_VERSION
ARG TRITON_CONTAINER_VERSION
'''
# Install the windows- or linux-specific buildbase dependencies
if target_platform() == 'windows':
df += '''
SHELL ["cmd", "/S", "/C"]
'''
else:
df += '''
# Ensure apt-get won't prompt for selecting options
ENV DEBIAN_FRONTEND=noninteractive
# libcurl4-openSSL-dev is needed for GCS
# python3-dev is needed by Torchvision
# python3-pip and libarchive-dev is needed by python backend
# uuid-dev and pkg-config is needed for Azure Storage
# scons is needed for armnn_tflite backend build dep
RUN apt-get update && \
apt-get install -y --no-install-recommends \
autoconf \
automake \
build-essential \
docker.io \
git \
libre2-dev \
libssl-dev \
libtool \
libboost-dev \
libcurl4-openssl-dev \
libb64-dev \
patchelf \
python3-dev \
python3-pip \
python3-setuptools \
rapidjson-dev \
scons \
software-properties-common \
unzip \
wget \
zlib1g-dev \
libarchive-dev \
pkg-config \
uuid-dev \
libnuma-dev && \
rm -rf /var/lib/apt/lists/*
RUN pip3 install --upgrade pip && \
pip3 install --upgrade wheel setuptools docker
# Server build requires recent version of CMake (FetchContent required)
RUN wget -O - https://apt.kitware.com/keys/kitware-archive-latest.asc 2>/dev/null | \
gpg --dearmor - | \
tee /etc/apt/trusted.gpg.d/kitware.gpg >/dev/null && \
apt-add-repository 'deb https://apt.kitware.com/ubuntu/ focal main' && \
apt-get update && \
apt-get install -y --no-install-recommends \
cmake-data=3.21.1-0kitware1ubuntu20.04.1 cmake=3.21.1-0kitware1ubuntu20.04.1
'''
# Copy in the triton source. We remove existing contents first in
# case the FROM container has something there already.
if target_platform() == 'windows':
df += '''
WORKDIR /workspace
RUN rmdir /S/Q * || exit 0
COPY . .
'''
else:
df += '''
WORKDIR /workspace
RUN rm -fr *
COPY . .
ENTRYPOINT []
'''
if FLAGS.enable_gpu:
df += install_dcgm_libraries(argmap['DCGM_VERSION'], target_machine())
df += '''
ENV TRITON_SERVER_VERSION ${TRITON_VERSION}
ENV NVIDIA_TRITON_SERVER_VERSION ${TRITON_CONTAINER_VERSION}
'''
mkdir(ddir)
with open(os.path.join(ddir, dockerfile_name), "w") as dfile:
dfile.write(df)
def create_dockerfile_build(ddir, dockerfile_name, backends):
df = '''
FROM tritonserver_builder_image AS build
FROM tritonserver_buildbase
COPY --from=build /tmp/tritonbuild /tmp/tritonbuild
'''
# If requested, package the source code for all OSS used to build
# Triton Windows is not delivered as a container (and tar not
# available) so skip for windows platform.
if target_platform() != 'windows':
if not FLAGS.no_container_source:
df += '''
RUN mkdir -p /tmp/tritonbuild/install/third-party-src && \
(cd /tmp/tritonbuild/tritonserver/build && \
tar zcf /tmp/tritonbuild/install/third-party-src/src.tar.gz third-party-src)
COPY --from=build /workspace/build/server/README.third-party-src /tmp/tritonbuild/install/third-party-src/README
'''
if 'onnxruntime' in backends:
if target_platform() != 'windows':
df += '''
# Copy ONNX custom op library and model (needed for testing)
RUN if [ -d /tmp/tritonbuild/onnxruntime ]; then \
cp /tmp/tritonbuild/onnxruntime/install/test/libcustom_op_library.so /workspace/qa/L0_custom_ops/.; \
cp /tmp/tritonbuild/onnxruntime/install/test/custom_op_test.onnx /workspace/qa/L0_custom_ops/.; \
fi
'''
mkdir(ddir)
with open(os.path.join(ddir, dockerfile_name), "w") as dfile:
dfile.write(df)
def create_dockerfile_linux(ddir, dockerfile_name, argmap, backends, repoagents,
endpoints):
df = '''
#
# Multistage build.
#
ARG TRITON_VERSION={}
ARG TRITON_CONTAINER_VERSION={}
ARG BASE_IMAGE={}
ARG BUILD_IMAGE=tritonserver_build
############################################################################
## Build image
############################################################################
FROM ${{BUILD_IMAGE}} AS tritonserver_build
############################################################################
## Production stage: Create container with just inference server executable
############################################################################
FROM ${{BASE_IMAGE}}
'''.format(argmap['TRITON_VERSION'], argmap['TRITON_CONTAINER_VERSION'],
argmap['BASE_IMAGE'])
df += dockerfile_prepare_container_linux(argmap, backends, FLAGS.enable_gpu, target_machine())
df += '''
WORKDIR /opt/tritonserver
COPY --chown=1000:1000 LICENSE .
COPY --chown=1000:1000 TRITON_VERSION .
COPY --chown=1000:1000 NVIDIA_Deep_Learning_Container_License.pdf .
COPY --chown=1000:1000 --from=tritonserver_build /tmp/tritonbuild/install/bin/tritonserver bin/
COPY --chown=1000:1000 --from=tritonserver_build /tmp/tritonbuild/install/lib/libtritonserver.so lib/
COPY --chown=1000:1000 --from=tritonserver_build /tmp/tritonbuild/install/include/triton/core include/triton/core
# Top-level include/core not copied so --chown does not set it correctly,
# so explicit set on all of include
RUN chown -R triton-server:triton-server include
'''
# If requested, include the source code for all OSS used to build Triton
if not FLAGS.no_container_source:
df += '''
COPY --chown=1000:1000 --from=tritonserver_build /tmp/tritonbuild/install/third-party-src third-party-src
'''
for noncore in NONCORE_BACKENDS:
if noncore in backends:
df += '''
COPY --chown=1000:1000 --from=tritonserver_build /tmp/tritonbuild/install/backends backends
'''
break
if len(repoagents) > 0:
df += '''
COPY --chown=1000:1000 --from=tritonserver_build /tmp/tritonbuild/install/repoagents repoagents
'''
# Add feature labels for SageMaker endpoint
if 'sagemaker' in endpoints:
df += '''
LABEL com.amazonaws.sagemaker.capabilities.accept-bind-to-port=true
COPY --chown=1000:1000 --from=tritonserver_build /workspace/build/sagemaker/serve /usr/bin/.
'''
mkdir(ddir)
with open(os.path.join(ddir, dockerfile_name), "w") as dfile:
dfile.write(df)
def dockerfile_prepare_container_linux(argmap, backends, enable_gpu, target_machine):
gpu_enabled = 1 if enable_gpu else 0
# Common steps to produce docker images shared by build.py and compose.py.
# Sets enviroment variables, installs dependencies and adds entrypoint
df = '''
ARG TRITON_VERSION
ARG TRITON_CONTAINER_VERSION
ENV TRITON_SERVER_VERSION ${TRITON_VERSION}
ENV NVIDIA_TRITON_SERVER_VERSION ${TRITON_CONTAINER_VERSION}
LABEL com.nvidia.tritonserver.version="${TRITON_SERVER_VERSION}"
ENV PATH /opt/tritonserver/bin:${PATH}
'''
ort_dependencies = "libgomp1" if 'onnxruntime' in backends else ""
df += '''
ENV TF_ADJUST_HUE_FUSED 1
ENV TF_ADJUST_SATURATION_FUSED 1
ENV TF_ENABLE_WINOGRAD_NONFUSED 1
ENV TF_AUTOTUNE_THRESHOLD 2
ENV TRITON_SERVER_GPU_ENABLED {gpu_enabled}
# Create a user that can be used to run triton as
# non-root. Make sure that this user to given ID 1000. All server
# artifacts copied below are assign to this user.
ENV TRITON_SERVER_USER=triton-server
RUN userdel tensorrt-server > /dev/null 2>&1 || true && \
if ! id -u $TRITON_SERVER_USER > /dev/null 2>&1 ; then \
useradd $TRITON_SERVER_USER; \
fi && \
[ `id -u $TRITON_SERVER_USER` -eq 1000 ] && \
[ `id -g $TRITON_SERVER_USER` -eq 1000 ]
# Ensure apt-get won't prompt for selecting options
ENV DEBIAN_FRONTEND=noninteractive
# Common dependencies. FIXME (can any of these be conditional? For
# example libcurl only needed for GCS?)
RUN apt-get update && \
apt-get install -y --no-install-recommends \
software-properties-common \
libb64-0d \
libcurl4-openssl-dev \
libre2-5 \
git \
dirmngr \
libnuma-dev \
curl \
{ort_dependencies} && \
rm -rf /var/lib/apt/lists/*
'''.format(gpu_enabled=gpu_enabled, ort_dependencies=ort_dependencies)
if enable_gpu:
df += install_dcgm_libraries(argmap['DCGM_VERSION'], target_machine)
df += '''
# Extra defensive wiring for CUDA Compat lib
RUN ln -sf ${_CUDA_COMPAT_PATH}/lib.real ${_CUDA_COMPAT_PATH}/lib \
&& echo ${_CUDA_COMPAT_PATH}/lib > /etc/ld.so.conf.d/00-cuda-compat.conf \
&& ldconfig \
&& rm -f ${_CUDA_COMPAT_PATH}/lib
'''
# Add dependencies needed for python backend
if 'python' in backends:
df += '''
# python3, python3-pip and some pip installs required for the python backend
RUN apt-get update && \
apt-get install -y --no-install-recommends \
python3 libarchive-dev \
python3-pip \
libpython3-dev && \
pip3 install --upgrade pip && \
pip3 install --upgrade wheel setuptools && \
pip3 install --upgrade numpy && \
rm -rf /var/lib/apt/lists/*
'''
df += '''
WORKDIR /opt/tritonserver
RUN rm -fr /opt/tritonserver/*
COPY --chown=1000:1000 nvidia_entrypoint.sh .
ENTRYPOINT ["/opt/tritonserver/nvidia_entrypoint.sh"]
'''
df += '''
ENV NVIDIA_BUILD_ID {}
LABEL com.nvidia.build.id={}
LABEL com.nvidia.build.ref={}
'''.format(argmap['NVIDIA_BUILD_ID'], argmap['NVIDIA_BUILD_ID'],
argmap['NVIDIA_BUILD_REF'])
return df
def create_dockerfile_windows(ddir, dockerfile_name, argmap, backends,
repoagents):
df = '''
#
# Multistage build.
#
ARG TRITON_VERSION={}
ARG TRITON_CONTAINER_VERSION={}
ARG BASE_IMAGE={}
ARG BUILD_IMAGE=tritonserver_build
############################################################################
## Build image
############################################################################
FROM ${{BUILD_IMAGE}} AS tritonserver_build
############################################################################
## Production stage: Create container with just inference server executable
############################################################################
FROM ${{BASE_IMAGE}}
ARG TRITON_VERSION
ARG TRITON_CONTAINER_VERSION
ENV TRITON_SERVER_VERSION ${{TRITON_VERSION}}
ENV NVIDIA_TRITON_SERVER_VERSION ${{TRITON_CONTAINER_VERSION}}
LABEL com.nvidia.tritonserver.version="${{TRITON_SERVER_VERSION}}"
RUN setx path "%path%;C:\opt\tritonserver\bin"
'''.format(argmap['TRITON_VERSION'], argmap['TRITON_CONTAINER_VERSION'],
argmap['BASE_IMAGE'])
df += '''
WORKDIR /opt/tritonserver
RUN rmdir /S/Q * || exit 0
COPY LICENSE .
COPY TRITON_VERSION .
COPY NVIDIA_Deep_Learning_Container_License.pdf .
COPY --from=tritonserver_build /tmp/tritonbuild/install/bin bin
COPY --from=tritonserver_build /tmp/tritonbuild/install/lib/tritonserver.lib lib/
COPY --from=tritonserver_build /tmp/tritonbuild/install/include/triton/core include/triton/core
'''
for noncore in NONCORE_BACKENDS:
if noncore in backends:
df += '''
COPY --from=tritonserver_build /tmp/tritonbuild/install/backends backends
'''
break
df += '''
ENTRYPOINT []
ENV NVIDIA_BUILD_ID {}
LABEL com.nvidia.build.id={}
LABEL com.nvidia.build.ref={}
'''.format(argmap['NVIDIA_BUILD_ID'], argmap['NVIDIA_BUILD_ID'],
argmap['NVIDIA_BUILD_REF'])
mkdir(ddir)
with open(os.path.join(ddir, dockerfile_name), "w") as dfile:
dfile.write(df)
def container_build(images, backends, repoagents, endpoints):
# The cmake, build and install directories within the container.
build_dir = os.path.join(os.sep, 'tmp', 'tritonbuild')
install_dir = os.path.join(os.sep, 'tmp', 'tritonbuild', 'install')
if target_platform() == 'windows':
cmake_dir = os.path.normpath('c:/workspace/build')
else:
cmake_dir = '/workspace/build'
# We can't use docker module for building container because it
# doesn't stream output and it also seems to handle cache-from
# incorrectly which leads to excessive rebuilds in the multistage
# build.
if 'base' in images:
base_image = images['base']
elif target_platform() == 'windows':
base_image = 'mcr.microsoft.com/dotnet/framework/sdk:4.8'
else:
base_image = 'nvcr.io/nvidia/tritonserver:{}-py3-min'.format(
FLAGS.upstream_container_version)
dockerfileargmap = {
'NVIDIA_BUILD_REF':
'' if FLAGS.build_sha is None else FLAGS.build_sha,
'NVIDIA_BUILD_ID':
'<unknown>' if FLAGS.build_id is None else FLAGS.build_id,
'TRITON_VERSION':
FLAGS.version,
'TRITON_CONTAINER_VERSION':
FLAGS.container_version,
'BASE_IMAGE':
base_image,
'DCGM_VERSION':
'' if FLAGS.version is None or FLAGS.version
not in TRITON_VERSION_MAP else TRITON_VERSION_MAP[FLAGS.version][5],
}
cachefrommap = [
'tritonserver_buildbase', 'tritonserver_buildbase_cache0',
'tritonserver_buildbase_cache1'
]
cachefromargs = ['--cache-from={}'.format(k) for k in cachefrommap]
commonargs = [
'docker', 'build', '-f',
os.path.join(FLAGS.build_dir, 'Dockerfile.buildbase')
]
if not FLAGS.no_container_pull:
commonargs += [
'--pull',
]
# Windows docker runs in a VM and memory needs to be specified
# explicitly.
if target_platform() == 'windows':
commonargs += [
'--memory', FLAGS.container_memory
]
log_verbose('buildbase container {}'.format(commonargs + cachefromargs))
create_dockerfile_buildbase(FLAGS.build_dir, 'Dockerfile.buildbase',
dockerfileargmap)
try:
# Create buildbase image, this is an image with all
# dependencies needed for the build.
p = subprocess.Popen(commonargs + cachefromargs +
['-t', 'tritonserver_buildbase', '.'])
p.wait()
fail_if(p.returncode != 0, 'docker build tritonserver_buildbase failed')
# Before attempting to run the new image, make sure any
# previous 'tritonserver_builder' container is removed.
client = docker.from_env(timeout=3600)
try:
existing = client.containers.get('tritonserver_builder')
existing.remove(force=True)
except docker.errors.NotFound:
pass # ignore
# Next run build.py inside the container with the same flags
# as was used to run this instance, except:
#
# --no-container-build is added so that within the buildbase
# container we just created we do not attempt to do a nested
# container build
#