forked from Xilinx/inference-server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
proteus
executable file
·1497 lines (1288 loc) · 50.3 KB
/
proteus
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 2021 Xilinx Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import argparse
import getpass
import glob
import hashlib
import json
import multiprocessing as mp
import os
from pathlib import Path
import pty
import shlex
import shutil
import subprocess
import sys
import tarfile
import textwrap
import time
import urllib.error
import urllib.request
import zipfile
def get_version():
version_file = Path(__file__).parent.resolve() / "VERSION"
with open(version_file, "r") as f:
return f.readline().strip()
# https://stackoverflow.com/a/34736291/13621369
class NegateAction(argparse.Action):
def __init__(
self,
option_strings,
dest,
const=True,
default=None,
required=False,
help=None,
metavar=None,
):
super().__init__(
option_strings=option_strings,
dest=dest,
nargs=0,
const=const,
default=default,
required=required,
help=help,
)
def __call__(self, parser, ns, values, option):
setattr(ns, self.dest, option[2:4] != "no")
def get_build_config(dir):
build_config_file = Path(f"{dir}/config.txt")
try:
with open(build_config_file, "r") as f:
build_config = f.readline().strip()
except FileNotFoundError:
build_config = None
if build_config:
build_options_file = Path(f"{dir}/{build_config}/config.txt")
try:
with open(build_options_file, "r") as f:
build_options_str = f.readline().strip()
build_options = (
build_options_str.split(" ") if build_options_str else []
)
except FileNotFoundError:
build_options = None
else:
build_options = None
return (build_config_file, build_config, build_options)
def run_tty_command(command: str, dry_run: bool):
if dry_run:
print(command)
return
status = pty.spawn(shlex.split(command))
if os.WIFSIGNALED(status):
exit_code = -os.WTERMSIG(status)
elif os.WIFEXITED(status):
exit_code = os.WEXITSTATUS(status)
elif os.WIFSTOPPED(status):
exit_code = -os.WSTOPSIG(status)
else:
raise Exception("Unknown exception")
if exit_code != 0:
sys.exit(exit_code)
def run_command(command: str, dry_run: bool, exit_on_error=True, quiet=False):
if dry_run:
print(command)
return
try:
if quiet:
subprocess.check_call(
shlex.split(command),
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
else:
subprocess.check_call(
shlex.split(command), stdout=sys.stdout, stderr=subprocess.STDOUT
)
except subprocess.CalledProcessError as error:
if exit_on_error:
sys.exit(error.returncode)
else:
return error.returncode
def run_shell_command(command: str, dry_run: bool):
if dry_run:
print(command)
return
subprocess.call(command, shell=True)
class WriteComposeFile:
@staticmethod
def get_devices():
devices = []
files = glob.glob("/dev/xclmgmt*")
for file in files:
devices.append(f"{file}:{file}")
files = glob.glob("/dev/dri/render*")
for file in files:
devices.append(f"{file}:{file}")
return devices
@staticmethod
def get_user_configs():
configs = []
user_config = Path.home() / ".gitconfig"
if user_config.exists():
configs.append(f"{str(user_config)}:/home/proteus-user/.gitconfig:ro")
global_config = Path("/etc/gitconfig")
if global_config.exists():
configs.append(f"{str(global_config)}:/etc/gitconfig:ro")
ssh = Path.home() / ".ssh"
if ssh.exists():
configs.append(f"{str(ssh)}:/home/proteus-user/.ssh:ro")
return configs
@staticmethod
def get_xclbins():
xclbins = []
path = Path("/opt/xilinx/overlaybins")
if path.exists():
xclbins.append(f"{str(path)}:{str(path)}:ro")
return xclbins
@classmethod
def merge(cls, base, supplement):
for key in supplement.keys():
if key in base:
if isinstance(base[key], list):
if isinstance(supplement[key], list):
base[key].extend(supplement[key])
else:
base[key].append(supplement[key])
elif isinstance(base[key], dict):
cls.merge(base[key], supplement[key])
else:
base[key] = supplement[key]
else:
base[key] = supplement[key]
@staticmethod
def set_or_extend(dictionary, key, value):
if key in dictionary:
if isinstance(dictionary[key], list):
if isinstance(value, list):
dictionary[key].extend(value)
else:
dictionary[key].append(value)
else:
dictionary[key] = value
@classmethod
def write(cls, args: argparse.Namespace, profile: str):
try:
import yaml
except ImportError:
raise argparse.ArgumentError(
None,
"The yaml package is required for this command but could not be imported.",
)
with open(f"docker-compose.base.yml", "r") as f:
config = yaml.safe_load(f)
with open(f"docker-compose.{profile}.yml", "r") as f:
supplement = yaml.safe_load(f)
cls.merge(config, supplement)
for service in config["services"]:
if args.devices:
cls.set_or_extend(
config["services"][service], "devices", cls.get_devices()
)
# if args.user_config:
# cls.set_or_extend(
# config["services"][service], "volumes", cls.get_user_configs()
# )
# if args.xclbins:
# default_xclbin_path = "/opt/xilinx/overlaybins"
# if Path(default_xclbin_path).exists():
# mount = f"{default_xclbin_path}:{default_xclbin_path}:ro"
# cls.set_or_extend(config["services"][service], "volumes", mount)
# if args.command:
# cls.set_or_extend(
# config["services"][service],
# "command",
# shlex.split(args.command.strip('"')),
# )
if args.dry_run:
print(json.dumps(config, indent=2))
else:
with open("docker-compose.yml", "w") as f:
yaml.dump(config, f)
class Attach:
@staticmethod
def parse(args, unknown_args):
user = getpass.getuser()
cmd = f"docker ps --filter status=running --filter 'label=project=proteus' --latest --quiet"
if args.name is None:
try:
latest_container = (
subprocess.check_output(shlex.split(cmd)).decode("utf-8").strip()
)
except FileNotFoundError:
print("Docker not found, cannot attach to a container")
sys.exit(1)
else:
latest_container = args.name
if latest_container == "":
print(
"Failed to find a container to attach to automatically. Use --name to specify one"
)
if not args.dry_run:
sys.exit(1)
sys.exit(0)
columns, lines = shutil.get_terminal_size()
command = f"docker exec -it --user proteus-user -e COLUMNS={columns} -e LINES={lines} {latest_container} /bin/bash"
run_tty_command(command, args.dry_run)
@classmethod
def add(cls, parser):
subparser = parser.add_parser(
"attach", help="Attach to a running Proteus container", add_help=False
)
command_group = subparser.add_argument_group("Options")
command_group.add_argument(
"-n",
"--name",
action="store",
help="name of the container to attach to. Defaults to latest running container",
)
command_group.add_argument(
"-h", "--help", action="help", help="show this help message and exit"
)
subparser.set_defaults(func=cls.parse)
class Benchmark:
@staticmethod
def parse(args, unknown_args):
unknown_commands = " ".join(unknown_args)
command = f"python3 tools/benchmark.py {unknown_commands}"
run_command(command, args.dry_run)
@classmethod
def add(cls, parser):
subparser = parser.add_parser(
"benchmark", help="Benchmark Proteus", add_help=False
)
subparser.set_defaults(func=cls.parse)
class Build:
@staticmethod
def parse(args, unknown_args: list):
unknown_args.sort()
(
build_config_file,
old_build_config,
old_build_options,
) = get_build_config(args.dir)
if old_build_options is not None and unknown_args != old_build_options:
args.regen = True
if old_build_config is None:
old_build_config = "Debug"
args.regen = True
if not args.dry_run:
os.makedirs(os.path.dirname(build_config_file), exist_ok=True)
os.makedirs(
os.path.dirname(build_config_file) + "/" + old_build_config,
exist_ok=True,
)
else:
print(f"Making directories: {str(build_config_file)}")
print(f"Making directories: {str(build_config_file/old_build_config)}")
if args.config is None:
args.config = old_build_config.strip()
build_options_file = f"{args.dir}/{args.config}/config.txt"
build_dir = Path(f"{args.dir}/{args.config}")
# build_dir.mkdir(parents=True, exist_ok=True)
build_options = " ".join(unknown_args)
if args.lint:
build_options += " -DPROTEUS_ENABLE_LINTING=ON"
if args.clean and build_dir.exists():
command = (
f"cmake --build {str(build_dir)} --target clean -- -j {args.threads}"
)
run_command(command, args.dry_run)
# if the package isn't importable, then we need to delete the CMake cache so the package can be installed by the build
try:
import proteus
except ImportError:
args.regen = True
cmake_cache = build_dir / "CMakeCache.txt"
if args.regen or (not build_dir.exists()) or (not cmake_cache.exists()):
file = f"{str(build_dir)}/CMakeCache.txt"
command = f"rm -f {str(cmake_cache)}"
if args.dry_run:
print(command)
else:
try:
os.remove(file)
except OSError:
pass
command = f'cmake --no-warn-unused-cli -DCMAKE_EXPORT_COMPILE_COMMANDS:BOOL=TRUE \
-DCMAKE_BUILD_TYPE:STRING={args.config} -DCMAKE_C_COMPILER:FILEPATH=/usr/bin/gcc \
-DCMAKE_CXX_COMPILER:FILEPATH=/usr/bin/g++ -H{Path.cwd()} -B{str(build_dir)} \
-DCMAKE_PREFIX_PATH="$CMAKE_PREFIX_PATH" -G "Unix Makefiles" {build_options}'
run_command(command, args.dry_run)
if args.dry_run:
print(f"Saving {args.config} to {str(build_config_file)}")
print(f"Saving {build_options} to {str(build_options_file)}")
else:
with open(build_config_file, "w") as f:
f.write(args.config)
with open(build_options_file, "w") as f:
f.write(build_options)
command = f"cmake --build {str(build_dir)} --target all -- -j {args.threads}"
run_command(command, args.dry_run)
path = f"{args.dir}/workers"
if args.dry_run:
print(f"mkdir -p {path}")
else:
Path(path).mkdir(parents=True, exist_ok=True)
shared_libs = " ".join(glob.glob(f"{str(build_dir)}/src/proteus/workers/*.so"))
command = f"cp -fs {shared_libs} {path}/"
run_command(command, args.dry_run)
command = f"symlinks -rc {path}"
run_command(command, args.dry_run, quiet=True)
if not args.dry_run:
print("")
print("======================")
print(f"Built {args.config} version")
print("======================")
if args.all:
args.jobs = mp.cpu_count()
Make.parse(args, ["extra"])
Make.parse(args, ["doxygen"])
Make.parse(args, ["sphinx"])
@classmethod
def add(cls, parser):
subparser = parser.add_parser(
"build", help="Build the proteus project", add_help=False
)
command_group = subparser.add_mutually_exclusive_group()
command_group.add_argument(
"--coverage",
dest="config",
action="store_const",
const="Coverage",
help="build the coverage configuration",
)
command_group.add_argument(
"--debug",
dest="config",
action="store_const",
const="Debug",
help="build the debug configuration",
)
command_group.add_argument(
"--release",
dest="config",
action="store_const",
const="Release",
help="build the release configuration",
)
command_group = subparser.add_argument_group("Options")
command_group.add_argument(
"-a",
"--all",
action="store_true",
help="Build additional optional targets",
)
command_group.add_argument(
"-c",
"--clean",
action="store_true",
help="clean prior to building",
)
command_group.add_argument(
"-d",
"--dir",
action="store",
help="root path to place the build tree. Defaults to ./build",
default=str(Path.cwd() / "build"),
)
command_group.add_argument(
"-l",
"--lint",
action="store_true",
help="Enable build-time linting in CMake. Defaults to false",
)
command_group.add_argument(
"-r",
"--regen",
action="store_true",
help="Delete the CMakeCache and regenerate",
)
command_group.add_argument(
"-t",
"--threads",
action="store",
help="number of threads for Make (defaults to number of processors)",
default=mp.cpu_count(),
)
command_group.add_argument(
"-h", "--help", action="help", help="show this help message and exit"
)
subparser.set_defaults(func=cls.parse)
class ClangFormat:
@staticmethod
def parse(args, unknown_args):
unknown_commands = " ".join(unknown_args)
command = f"clang-format -style=file -i {unknown_commands} {args.path}"
run_command(command, args.dry_run)
@classmethod
def add(cls, parser):
subparser = parser.add_parser(
"clangformat",
help="Run clangformat on a file",
add_help=False,
description="This is a wrapper around clangformat to format a particular file in place based on the existing clangformat rules. Any unmatched arguments are passed to clang-format. Use clang-format --help to see options",
)
subparser.add_argument(
"path", action="store", help="Path to a C++ file to analyze"
)
command_group = subparser.add_argument_group("Options")
command_group.add_argument(
"-h", "--help", action="help", help="show this help message and exit"
)
subparser.set_defaults(func=cls.parse)
class ClangTidy:
@staticmethod
def parse(args, unknown_args):
_, old_build_config, _ = get_build_config(args.dir)
if old_build_config is None:
old_build_config = "Debug"
unknown_commands = " ".join(unknown_args)
command = f"clang-tidy -format-style=file -p={args.dir}/{old_build_config} {unknown_commands}"
run_command(command, args.dry_run)
@classmethod
def add(cls, parser):
subparser = parser.add_parser(
"clangtidy", help="Run clang-tidy on all source files", add_help=False
)
command_group = subparser.add_argument_group("Options")
command_group.add_argument(
"-d",
"--dir",
action="store",
help="root path to the build tree. Defaults to ./build",
default=str(Path.cwd() / "build"),
)
command_group.add_argument(
"-h", "--help", action="help", help="show this help message and exit"
)
subparser.set_defaults(func=cls.parse)
class Clean:
@staticmethod
def parse(args, unknown_args):
commands = [
"rm -f docker-compose.devices.yml",
"rm -f docker-compose.yml",
"rm -f include/proteus/build_options.hpp",
"rm -f src/proteus/version.hpp",
"rm -f tools/benchmark.yml",
"rm -rf external/aks/graph_zoo",
"rm -rf external/aks/kernel_src",
"rm -rf external/aks/kernel_zoo",
"rm -f external/aks/cmake-kernels.sh",
"rm -rf external/aks/libs",
]
if args.gui:
commands.extend(
[
"rm -rf src/gui/node_modules",
"rm -rf src/gui/public/coverage",
"rm -rf src/gui/public/doxygen",
"rm -rf src/gui/public/sphinx",
"rm -f src/gui/src/build_options.ts",
]
)
if args.artifacts:
commands.append("rm -rf external/artifacts/*")
command = "; ".join(commands)
run_command(command, args.dry_run)
command = "find . -name build -type d -exec rm -r {} +"
run_command(command, args.dry_run)
@classmethod
def add(cls, parser):
subparser = parser.add_parser(
"clean",
help="Delete all generated files, restoring the repo to clean state",
add_help=False,
)
command_group = subparser.add_argument_group("Options")
command_group.add_argument(
"--artifacts",
action="store_true",
help="Delete downloaded XModel artifacts",
)
command_group.add_argument(
"-h", "--help", action="help", help="show this help message and exit"
)
command_group.add_argument(
"--no-gui",
dest="gui",
action="store_false",
help="Don't clean web GUI/nodeJS related files",
)
subparser.set_defaults(func=cls.parse)
class Dockerize:
@staticmethod
def parse(args, unknown_args):
unknown_arguments = " ".join(unknown_args)
tag_prefix = f"{args.registry}"
if args.production:
tag_prefix += f"/proteus" + args.suffix
target = "proteus"
else:
tag_prefix += f"/proteus-dev" + args.suffix
target = "proteus_dev_final"
latest_tag = f"{tag_prefix}:latest"
build_args = ""
if not args.vitis:
build_args += "--build-arg ENABLE_VITIS=no "
if args.dev_base:
build_args += f"--build-arg DEV_BASE_IMAGE={args.dev_base} "
if args.tfzendnn_path:
build_args += f" --build-arg ENABLE_TFZENDNN=yes"
build_args += f" --build-arg TFZENDNN_PATH={args.tfzendnn_path}"
if args.ptzendnn_path:
build_args += f" --build-arg ENABLE_PTZENDNN=yes"
build_args += f" --build-arg PTZENDNN_PATH={args.ptzendnn_path}"
try:
git_branch = (
subprocess.check_output(shlex.split("git rev-parse --abbrev-ref HEAD"))
.decode("utf-8")
.strip()
)
except subprocess.CalledProcessError:
git_branch = "unknown"
try:
git_commit = (
subprocess.check_output(shlex.split("git rev-parse HEAD"))
.decode("utf-8")
.strip()
)
except subprocess.CalledProcessError:
git_commit = "unknown"
else:
retval = run_command(
"git diff --quiet -- . ':(exclude)VERSION'", False, False
)
if retval:
git_commit += "-dirty"
labels = f"--label git-branch={git_branch} --label git-commit={git_commit}"
version = get_version()
os.environ["DOCKER_BUILDKIT"] = "1"
command = f"docker build {labels} --target {target} -t {latest_tag} -t {tag_prefix}:{version} {build_args} {unknown_arguments} ."
run_command(command, args.dry_run)
if args.push:
command = f"docker push {tag_prefix}:{version}"
run_command(command, args.dry_run)
command = f"docker push {latest_tag}"
run_command(command, args.dry_run)
@classmethod
def add(cls, parser):
subparser = parser.add_parser(
"dockerize", help="Build a docker image", add_help=False
)
command_group = subparser.add_argument_group("Options")
command_group.add_argument(
"--dev-base",
dest="dev_base",
action="store",
help=f"Name of the image to use as dev image to build the production image.",
default="",
)
command_group.add_argument(
"-h", "--help", action="help", help="show this help message and exit"
)
command_group.add_argument(
"--no-vitis",
dest="vitis",
action="store_false",
help="Remove Vitis dependencies from the container",
)
command_group.add_argument(
"--production",
action="store_true",
help=f"Build the production image. Defaults to false to build the dev image.",
)
command_group.add_argument(
"--push",
action="store_true",
help="Push the image(s) to the registry after building.",
)
command_group.add_argument(
"--registry",
action="store",
help=f"Docker image registry. Defaults to {getpass.getuser()}",
default=getpass.getuser(),
)
command_group.add_argument(
"--tfzendnn_path",
type=str,
default=None,
help="TF+ZenDNN C++ package location. If provided, will build with TF+ZenDNN enabled",
)
command_group.add_argument(
"--ptzendnn_path",
type=str,
default=None,
help="PT+ZenDNN C++ package location. If provided, will build with PT+ZenDNN enabled",
)
command_group.add_argument(
"--suffix",
action="store",
help=f"String to append to the tag of the Docker image to use. Defaults to empty string",
default="",
)
subparser.set_defaults(func=cls.parse)
class Get:
@staticmethod
def parse(args, unknown_args):
if unknown_args:
unknown_arguments = " ".join(unknown_args)
raise argparse.ArgumentError(
None, f"Unknown argument(s) passed: {unknown_arguments}"
)
if not args.dry_run:
print(
textwrap.dedent(
"""
NOTICE: BY INVOKING THIS SCRIPT AND USING THE FILES INSTALLED BY THE SCRIPT, YOU
AGREE ON BEHALF OF YOURSELF AND YOUR EMPLOYER (IF APPLICABLE) TO BE BOUND TO THE
COPYRIGHT AND LICENSE AGREEMENT APPLICABLE TO THE FILES THAT YOU INSTALL BY
RUNNING THE SCRIPT. XILINX DOES NOT GRANT TO YOU ANY RIGHTS OR LICENSES TO SUCH
FILES. YOU AGREES TO CAREFULLY REVIEW AND ABIDE BY THE TERMS AND CONDITIONS OF
THE LICENSE AGREEMENT TO THE EXTENT THAT THEY GOVERN SUCH FILES.
"""
)
)
test_asset_dir = Path.cwd() / "tests/assets"
artifact_dir = Path.cwd() / "external/artifacts"
tensorflow_models = Path.cwd() / "external/tensorflow_models"
repository = Path.cwd() / "external/repository"
pytorch_models = Path.cwd() / "external/pytorch_models"
alveo_dir = artifact_dir / "u200_u250"
tmp_dir = Path("/tmp/proteus_get")
alveo_dir.mkdir(exist_ok=True, parents=True)
tmp_dir.mkdir(exist_ok=True, parents=True)
repository.mkdir(exist_ok=True, parents=True)
files = {
test_asset_dir: [
"https://upload.wikimedia.org/wikipedia/commons/c/c4/Physicsworks.ogv",
"https://cdn.pixabay.com/photo/2016/11/29/03/35/girl-1867092_640.jpg",
],
alveo_dir: [
"https://www.xilinx.com/bin/public/openDownload?filename=densebox_320_320-u200-u250-r1.4.0.tar.gz",
"https://www.xilinx.com/bin/public/openDownload?filename=resnet_v1_50_tf-u200-u250-r1.4.0.tar.gz",
"https://www.xilinx.com/bin/public/openDownload?filename=yolov3_adas_pruned_0_9-u200-u250-r1.4.0.tar.gz",
"https://www.xilinx.com/bin/public/openDownload?filename=yolov3_voc-u200-u250-r1.4.0.tar.gz",
],
tmp_dir: [
"https://www.xilinx.com/bin/public/openDownload?filename=vitis_ai_runtime_r1.3.0_image_video.tar.gz",
],
}
if args.tfzendnn:
files.update({
tensorflow_models: [
"https://www.xilinx.com/bin/public/openDownload?filename=tf_resnetv1_50_imagenet_224_224_6.97G_2.5_1.0_Z3.3.zip"
],
})
if args.ptzendnn:
files.update({
pytorch_models:[
"https://www.xilinx.com/bin/public/openDownload?filename=pt_resnet50_imagenet_224_224_8.2G_2.5_1.0_Z3.3.zip"
]
})
for location, urls in files.items():
for url in urls:
if "www.xilinx.com/bin/public/openDownload" in url:
search_str = "filename="
filename = url[url.index(search_str) + len(search_str) :]
else:
filename = os.path.basename(urllib.parse.urlparse(url).path)
if args.dry_run:
print(f"Downloading {filename} from {url} to {location}")
else:
with open(tmp_dir / filename, "wb") as f:
req = urllib.request.Request(url)
# need to specify the user-agent for accessing wikimedia
req.add_header("User-Agent", f"proteus {get_version()}")
response = urllib.request.urlopen(req)
f.write(response.read())
filepath = str(tmp_dir / filename)
if filename.endswith("tar.gz"):
tar_file = tarfile.open(filepath, mode="r:gz")
tar_file.extractall(location)
elif filename.endswith("zip"):
with zipfile.ZipFile(str(tmp_dir / filename), "r") as zip_ref:
zip_ref.extractall(str(tmp_dir))
if args.tfzendnn or args.ptzendnn:
modelpath = str(tmp_dir / filename.split(".zip")[0] / "float/")
modelname = os.listdir(modelpath)[0]
if not os.path.exists(location): os.makedirs(location)
shutil.move(os.path.join(modelpath, modelname),
os.path.join(location, modelname))
else:
shutil.copy2(filepath, str(location / filename))
os.remove(filepath)
if not args.quiet:
print(f"Downloaded {url} to {str(location/filename)}")
if not args.dry_run:
adas_webm = Path(tmp_dir / "adas_detection/video/adas.webm")
if adas_webm.exists():
shutil.move(str(adas_webm), str(test_asset_dir / "adas.webm"))
shutil.rmtree(str(tmp_dir))
with zipfile.ZipFile(str(test_asset_dir / "mnist.zip"), "r") as zip_ref:
zip_ref.extractall(str(repository))
@classmethod
def add(cls, parser):
subparser = parser.add_parser(
"get", help="Get artifacts such as XModels", add_help=False
)
command_group = subparser.add_argument_group("Options")
command_group.add_argument(
"-h", "--help", action="help", help="show this help message and exit"
)
command_group.add_argument(
"-q", "--quiet", action="store_true", help="suppress prints"
)
command_group.add_argument(
"--tfzendnn",
action="store_true",
help="If TF+ZenDNN should be enabled",
)
command_group.add_argument(
"--ptzendnn",
action="store_true",
help="If PT+ZenDNN should be enabled",
)
subparser.set_defaults(func=cls.parse)
class Install:
@staticmethod
def parse(args, unknown_args):
if args.get_manifest:
try:
with open(f"{args.dir}/Release/install_manifest.txt") as f:
print(f.read())
sys.exit(0)
except FileNotFoundError:
raise argparse.ArgumentError(
None, "No manifest found. Install Proteus first."
)
build_args = f"--dir {args.dir} --release --regen -DPROTEUS_BUILD_TESTING=OFF "
if unknown_args:
build_args += " ".join(unknown_args)
command = f"./proteus build {build_args}"
run_command(command, args.dry_run)
command = f"sudo make -C {args.dir}/Release install"
run_command(command, args.dry_run)
@classmethod
def add(cls, parser):
subparser = parser.add_parser(
"install",
help="Install Proteus. Any unknown arguments are passed to the build command. Use -- --help to see options.",
add_help=False,
)
command_group = subparser.add_argument_group("Options")
# we need to build it somewhere else first because we're assuming that this
# build is running in the mounted directory in a container. The `make install`
# needs to be run as sudo to install to the system directory but the process
# also writes install_manifest.txt to the build tree. The root user does not
# have permissions to write into the mounted directory.
command_group.add_argument(
"-d",
"--dir",
action="store",
help="root path to the build tree. Defaults to /tmp/proteus/build",
default="/tmp/proteus/build",
)
command_group.add_argument(
"--get-manifest",
action="store_true",
help="Print the list of files last installed.",
)
command_group.add_argument(
"-h", "--help", action="help", help="show this help message and exit"
)
subparser.set_defaults(func=cls.parse)
class List:
@staticmethod
def parse(args, unknown_args):
if args.type == "images":
command = 'docker image list -f reference=*/*proteus* -f reference=*/*/*proteus* --format "table {{.Repository}}\\t{{.Tag}}\\t{{.ID}}\\t{{.CreatedSince}}\\t{{.Size}}" '
elif args.type == "labels":
command = 'docker image list -f reference=*/*proteus* -f reference=*/*/*proteus* --format "{{.ID}}" | uniq | xargs -I{} bash -c \'docker image inspect {} | jq -r \'\\\'\'if (.[0].RepoTags != []) then ((.[0].RepoTags | join(", ")), (.[0].Config.Labels | del(."git-commit") | del(."git-branch") | del(.project) | keys[] as $k | " \($k): \(.[$k])")) else empty end\'\\\'\'\''
else:
command = 'docker ps --filter "label=project=proteus" --format "table {{.ID}}\\t{{.Image}}\\t{{.RunningFor}}\\t{{.Status}}\\t{{.Names}}\\t{{.Ports}}" '
if args.type == "labels":
if shutil.which("jq") is not None:
run_shell_command(command, args.dry_run)
else:
print("Install jq to use this command")
else:
if unknown_args:
command += " ".join(unknown_args)
run_command(command, args.dry_run)
@classmethod
def add(cls, parser):
subparser = parser.add_parser(
"list",
help="List Proteus containers and images on the host.",
add_help=False,
)
subparser.add_argument(
"type",
nargs="?",
action="store",
default=False,
help="List the active containers (default) or specify 'images' or 'labels'",
)
command_group = subparser.add_argument_group("Options")
command_group.add_argument(
"-h", "--help", action="help", help="show this help message and exit"
)
subparser.set_defaults(func=cls.parse)
class Make:
@staticmethod
def parse(args, unknown_args):
_, old_build_config, _ = get_build_config(args.dir)
command = f"make -C {args.dir}/{old_build_config} "
if args.jobs is None:
command += "-j "