-
Notifications
You must be signed in to change notification settings - Fork 2
/
recom_examples.patch
3595 lines (3595 loc) · 86.5 KB
/
recom_examples.patch
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
diff --git a/tensorflow/recom/BUILD b/tensorflow/recom/BUILD
new file mode 100644
index 00000000000..a6ab99eb524
--- /dev/null
+++ b/tensorflow/recom/BUILD
@@ -0,0 +1,54 @@
+licenses(["notice"]) # Apache 2.0
+
+package(default_visibility = ["//visibility:public"])
+
+load("//tensorflow:tensorflow.bzl", "tf_cc_binary")
+
+tf_cc_binary(
+ name = "benchmark_multi_thread",
+ srcs = ["benchmark_multi_thread.cu.cc", "cxxopts.hpp"],
+ copts = [
+ "-fexceptions"
+ ],
+ linkopts = [
+ "-rdynamic",
+ "-lpthread",
+ "-lcudart",
+ "-L/usr/local/cuda/lib64" # Replace it if different on your system
+ ],
+ deps = [
+ ":utils",
+ "//tensorflow/cc:client_session",
+ "//tensorflow/core:tensorflow",
+ ]
+)
+
+tf_cc_binary(
+ name = "benchmark_throughput",
+ srcs = ["benchmark_throughput.cc", "cxxopts.hpp"],
+ copts = [
+ "-fexceptions"
+ ],
+ linkopts = [
+ "-rdynamic",
+ "-lpthread",
+ ],
+ deps = [
+ ":utils",
+ "//tensorflow/cc:client_session",
+ "//tensorflow/core:tensorflow",
+ ]
+)
+
+cc_library(
+ name = "utils",
+ srcs = ["utils.cc"],
+ hdrs = ["utils.h"],
+ deps = [
+ "//tensorflow/c:c_api",
+ "//tensorflow/cc:cc_ops",
+ "//tensorflow/core:tensorflow",
+ "//tensorflow/cc/saved_model:signature_constants",
+ "//tensorflow/cc/saved_model:loader"
+ ]
+)
diff --git a/tensorflow/recom/benchmark_multi_thread.cu.cc b/tensorflow/recom/benchmark_multi_thread.cu.cc
new file mode 100644
index 00000000000..4ff79f8467b
--- /dev/null
+++ b/tensorflow/recom/benchmark_multi_thread.cu.cc
@@ -0,0 +1,197 @@
+// Copyright 2023 The RECom Authors. All rights reserved.
+// 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.
+
+#include <cuda_profiler_api.h>
+#include <unistd.h>
+
+#include <chrono>
+#include <cstdlib>
+#include <fstream>
+#include <iostream>
+#include <string>
+#include <thread>
+#include <unordered_map>
+#include <vector>
+
+#include "absl/strings/str_replace.h"
+#include "cxxopts.hpp"
+#include "tensorflow/core/public/session.h"
+#include "utils.h"
+
+using namespace ::tensorflow;
+using namespace ::tensorflow::benchmark;
+
+int main(int argc, char **argv) {
+ cxxopts::Options options("benchmark_multi_thread",
+ "Benchmark the performance of TF recommendation "
+ "models with mutliple inference threads");
+
+ // clang-format off
+ options.add_options()
+ ("model_path", "Path of the TF saved model (mandatory)", cxxopts::value<std::string>())
+ ("batch_size", "Inference batch size", cxxopts::value<int>()->default_value("256"))
+ ("serve_workers", "Number of workers serving the requests concurrently", cxxopts::value<int>()->default_value("1"))
+ ("intra_threads", "TF intra_threads_parallelism (CPU)", cxxopts::value<int>()->default_value("0"))
+ ("inter_threads", "TF inter_threads_parallelism (CPU)", cxxopts::value<int>()->default_value("0"))
+ ("num_iterations", "Number of running iteration", cxxopts::value<int>()->default_value("100"))
+ ("lib_path", "Link a TF addon library", cxxopts::value<std::string>())
+ ("disable_gpu", "Disable the Usage of GPU", cxxopts::value<bool>()->default_value("false"))
+ ("embedding_only", "Only process the embedding parts", cxxopts::value<bool>()->default_value("false"))
+ ("cuda_profile", "Profiling the kernels (single thread). Only works when GPU is used", cxxopts::value<bool>()->default_value("false"))
+ ("timeline", "Record the TF timeline (single thread) to the specified path", cxxopts::value<std::string>())
+ ("h,help", "Show usage");
+ // clang-format on
+
+ auto args = options.parse(argc, argv);
+ if (args.count("help")) {
+ std::cout << options.help() << std::endl;
+ exit(0);
+ }
+
+ if (!args.count("model_path")) {
+ std::cerr << "ERROR: model_path must be specified!" << std::endl;
+ std::cerr << options.help() << std::endl;
+ exit(-1);
+ }
+
+ const auto &model_path = args["model_path"].as<std::string>();
+ const auto &batch_size = args["batch_size"].as<int>();
+ const auto &serve_workers = args["serve_workers"].as<int>();
+ const auto &intra_threads = args["intra_threads"].as<int>();
+ const auto &inter_threads = args["inter_threads"].as<int>();
+ const auto &num_iterations = args["num_iterations"].as<int>();
+ const bool &use_gpu = !args["disable_gpu"].as<bool>();
+
+ const bool &use_lib = args.count("lib_path");
+ const std::string &lib_path =
+ use_lib ? args["lib_path"].as<std::string>() : "";
+
+ LOG(INFO) << "Testing with model: " << model_path;
+ LOG(INFO) << "Testing with batch_size: " << batch_size;
+ LOG(INFO) << "Testing with serve_workers: " << serve_workers;
+ LOG(INFO) << "Testing with intra_threads: " << intra_threads;
+ LOG(INFO) << "Testing with inter_threads: " << inter_threads;
+ LOG(INFO) << "Testing with num_iterations: " << num_iterations;
+ LOG(INFO) << "GPU is " << (use_gpu ? "" : "NOT ") << "enabled";
+
+ if (use_lib) {
+ LOG(INFO) << "Testing with library: " << lib_path;
+ LoadOpLibrary(lib_path);
+ }
+
+ std::shared_ptr<SavedModelBundle> bundle;
+ LoadSavedModelWrap(model_path, intra_threads, inter_threads, bundle, use_gpu);
+ const auto &gd = bundle->meta_graph_def.graph_def();
+
+ std::vector<std::string> outputs;
+ if (!args["embedding_only"].as<bool>()) {
+ ExtractGraphOutputs(bundle, outputs);
+ } else {
+ ExtractGraphConcats(gd, outputs);
+ }
+
+ auto RunPredict =
+ [&](const std::vector<std::pair<std::string, Tensor>> &inputs,
+ std::vector<Tensor> &results) {
+ Status status = bundle->session->Run(inputs, outputs, {}, &results);
+ if (!status.ok()) {
+ LOG(ERROR) << "Failed to predict! status = " << status.ToString();
+ exit(-1);
+ }
+ };
+
+ auto RunMultiThreads =
+ [&](const std::vector<std::pair<std::string, Tensor>> &inputs,
+ std::vector<Tensor> &results, int batch_size) {
+ // LOG(INFO) << "Fetch nodes: " << absl::StrJoin(outputs, ", ");
+
+ using milli = std::chrono::milliseconds;
+
+ LOG(INFO) << "Start warmup predict";
+
+ auto t1 = std::chrono::high_resolution_clock::now();
+ RunPredict(inputs, results);
+ auto t2 = std::chrono::high_resolution_clock::now();
+
+ int warmup_time = std::chrono::duration_cast<milli>(t2 - t1).count();
+ LOG(INFO) << "Warmup done. Time: " << warmup_time << "ms";
+
+ auto run_thread = [&](int idx, int total) {
+ auto t1 = std::chrono::high_resolution_clock::now();
+ for (int i = 0; i < num_iterations; ++i) {
+ std::vector<Tensor> res;
+ RunPredict(inputs, res);
+ }
+ auto t2 = std::chrono::high_resolution_clock::now();
+
+ LOG(INFO) << "Batch size " << batch_size << ", sess run "
+ << num_iterations << " times, average latency: "
+ << static_cast<float>(
+ std::chrono::duration_cast<milli>(t2 - t1).count()) /
+ num_iterations
+ << " ms";
+ };
+
+ auto t3 = std::chrono::high_resolution_clock::now();
+ std::vector<std::thread> threads;
+ for (int i = 0; i < serve_workers; i++) {
+ threads.push_back(std::thread(run_thread, i, serve_workers));
+ }
+ for (auto &thread : threads) {
+ thread.join();
+ }
+ auto t4 = std::chrono::high_resolution_clock::now();
+
+ int total_latency = std::chrono::duration_cast<milli>(t4 - t3).count();
+ LOG(INFO) << "Total latency: " << total_latency << "ms";
+
+ int throughput = serve_workers * num_iterations * batch_size /
+ static_cast<float>(total_latency) * 1000;
+ LOG(INFO) << "Batch size: " << batch_size
+ << ", Throughput: " << throughput << " inference/s";
+ };
+
+ std::vector<std::pair<std::string, Tensor>> inputs;
+ ConstructGraphInputs(gd, batch_size, inputs);
+
+ std::vector<Tensor> results;
+ RunMultiThreads(inputs, results, batch_size);
+
+ if (args.count("cuda_profile")) {
+ for (int i = 0; i < 10; ++i)
+ RunPredict(inputs, results);
+
+ cudaProfilerStart();
+ RunPredict(inputs, results);
+ cudaProfilerStop();
+ }
+
+ if (args.count("timeline")) {
+ for (int i = 0; i < 10; ++i)
+ RunPredict(inputs, results);
+
+ RunOptions run_options;
+ run_options.set_trace_level(RunOptions::FULL_TRACE);
+ RunMetadata run_metadata;
+ Status status = bundle->session->Run(run_options, inputs, outputs, {},
+ &results, &run_metadata);
+ if (!status.ok()) {
+ LOG(ERROR) << "Failed to predict! status = " << status.ToString();
+ exit(-1);
+ }
+
+ std::string tl_str;
+ run_metadata.step_stats().SerializeToString(&tl_str);
+ std::ofstream ofs(args["timeline"].as<std::string>());
+ ofs << tl_str;
+ ofs.close();
+ }
+}
diff --git a/tensorflow/recom/benchmark_throughput.cc b/tensorflow/recom/benchmark_throughput.cc
new file mode 100644
index 00000000000..af16b012860
--- /dev/null
+++ b/tensorflow/recom/benchmark_throughput.cc
@@ -0,0 +1,196 @@
+// Copyright 2023 The RECom Authors. All rights reserved.
+// 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.
+
+#include <unistd.h>
+
+#include <chrono>
+#include <cstdlib>
+#include <fstream>
+#include <iostream>
+#include <string>
+#include <thread>
+#include <unordered_map>
+#include <vector>
+
+#include "absl/strings/str_replace.h"
+#include "cxxopts.hpp"
+#include "tensorflow/core/public/session.h"
+#include "utils.h"
+
+using namespace ::tensorflow;
+using namespace ::tensorflow::benchmark;
+
+int main(int argc, char **argv) {
+ cxxopts::Options options(
+ "benchmark_throughput",
+ "Using pressure test to evaluate the throughput of TF recommendation "
+ "models with mutliple inference threads");
+
+ // clang-format off
+ options.add_options()
+ ("model_path", "Path of the TF saved model (mandatory)", cxxopts::value<std::string>())
+ ("serve_workers", "Number of workers serving the requests concurrently", cxxopts::value<int>()->default_value("1"))
+ ("sla_latency", "Service level agreemnet latency", cxxopts::value<float>()->default_value("100"))
+ ("intra_threads", "TF intra_threads_parallelism (CPU)", cxxopts::value<int>()->default_value("0"))
+ ("inter_threads", "TF inter_threads_parallelism (CPU)", cxxopts::value<int>()->default_value("0"))
+ ("num_iterations", "Number of running iteration", cxxopts::value<int>()->default_value("100"))
+ ("lib_path", "Link a TF addon library", cxxopts::value<std::string>())
+ ("disable_gpu", "Disable the Usage of GPU", cxxopts::value<bool>()->default_value("false"))
+ ("embedding_only", "Only process the embedding parts", cxxopts::value<bool>()->default_value("false"))
+ ("h,help", "Show usage");
+ // clang-format on
+
+ auto args = options.parse(argc, argv);
+ if (args.count("help")) {
+ std::cout << options.help() << std::endl;
+ exit(0);
+ }
+
+ if (!args.count("model_path")) {
+ std::cerr << "ERROR: model_path must be specified!" << std::endl;
+ std::cerr << options.help() << std::endl;
+ exit(-1);
+ }
+
+ const auto &model_path = args["model_path"].as<std::string>();
+ const auto &serve_workers = args["serve_workers"].as<int>();
+ const auto &sla_latency = args["sla_latency"].as<float>();
+ const auto &intra_threads = args["intra_threads"].as<int>();
+ const auto &inter_threads = args["inter_threads"].as<int>();
+ const auto &num_iterations = args["num_iterations"].as<int>();
+ const bool &use_gpu = !args["disable_gpu"].as<bool>();
+
+ const bool &use_lib = args.count("lib_path");
+ const std::string &lib_path =
+ use_lib ? args["lib_path"].as<std::string>() : "";
+
+ LOG(INFO) << "Testing with model: " << model_path;
+ LOG(INFO) << "Testing with serve_workers: " << serve_workers;
+ LOG(INFO) << "Testing with SLA latency: " << sla_latency;
+ LOG(INFO) << "Testing with intra_threads: " << intra_threads;
+ LOG(INFO) << "Testing with inter_threads: " << inter_threads;
+ LOG(INFO) << "Testing with num_iterations: " << num_iterations;
+ LOG(INFO) << "GPU is " << (use_gpu ? "" : "NOT ") << "enabled";
+
+ if (use_lib) {
+ LOG(INFO) << "Testing with library: " << lib_path;
+ LoadOpLibrary(lib_path);
+ }
+
+ std::shared_ptr<SavedModelBundle> bundle;
+ LoadSavedModelWrap(model_path, intra_threads, inter_threads, bundle, use_gpu);
+ const auto &gd = bundle->meta_graph_def.graph_def();
+
+ std::vector<std::string> outputs;
+ if (!args["embedding_only"].as<bool>()) {
+ ExtractGraphOutputs(bundle, outputs);
+ } else {
+ ExtractGraphConcats(gd, outputs);
+ }
+
+ auto RunPredict =
+ [&](const std::vector<std::pair<std::string, Tensor>> &inputs,
+ std::vector<Tensor> &results) {
+ Status status = bundle->session->Run(inputs, outputs, {}, &results);
+ if (!status.ok()) {
+ LOG(ERROR) << "Failed to predict! status = " << status.ToString();
+ exit(-1);
+ }
+ };
+
+ auto RunMultiThreads =
+ [&](const std::vector<std::pair<std::string, Tensor>> &inputs,
+ std::vector<Tensor> &results,
+ int batch_size) -> std::pair<float, int> {
+ // LOG(INFO) << "Fetch nodes: " << absl::StrJoin(outputs, ", ");
+
+ using milli = std::chrono::milliseconds;
+
+ LOG(INFO) << "Start warmup predict";
+
+ auto t1 = std::chrono::high_resolution_clock::now();
+ RunPredict(inputs, results);
+ auto t2 = std::chrono::high_resolution_clock::now();
+
+ int warmup_time = std::chrono::duration_cast<milli>(t2 - t1).count();
+ LOG(INFO) << "Warmup done. Time: " << warmup_time << "ms";
+
+ auto run_thread = [&](int idx, int total) {
+ for (int i = 0; i < num_iterations; ++i) {
+ std::vector<Tensor> res;
+ RunPredict(inputs, res);
+ }
+ };
+
+ auto t3 = std::chrono::high_resolution_clock::now();
+ std::vector<std::thread> threads;
+ for (int i = 0; i < serve_workers; i++) {
+ threads.push_back(std::thread(run_thread, i, serve_workers));
+ }
+ for (auto &thread : threads) {
+ thread.join();
+ }
+ auto t4 = std::chrono::high_resolution_clock::now();
+
+ int total_latency = std::chrono::duration_cast<milli>(t4 - t3).count();
+ float avg_latency = static_cast<float>(total_latency) / num_iterations;
+ int throughput = serve_workers * num_iterations * batch_size /
+ static_cast<float>(total_latency) * 1000;
+
+ return {avg_latency, throughput};
+ };
+
+ int max_throughput = 0;
+ int max_batch_size = 0;
+ int batch_size = 16;
+ while (true) {
+ std::vector<std::pair<std::string, Tensor>> inputs;
+
+ ConstructGraphInputs(gd, batch_size, inputs);
+
+ std::vector<Tensor> results;
+ auto latency_throughput = RunMultiThreads(inputs, results, batch_size);
+
+ float latency = latency_throughput.first;
+ int throughput = latency_throughput.second;
+ LOG(INFO) << "batch size: " << batch_size << ", "
+ << "avg latency: " << latency << ", "
+ << "throughput: " << throughput;
+
+ if (latency >= sla_latency) {
+ if (batch_size > 512) {
+ break;
+ } else {
+ batch_size += 50;
+ }
+ } else {
+ max_batch_size = batch_size;
+ max_throughput = throughput;
+
+ int increment;
+ if (latency < 50) {
+ increment = batch_size;
+ } else if (latency < 70) {
+ increment = batch_size / 5;
+ } else if (latency < 80) {
+ increment = batch_size / 10;
+ } else if (latency < 90) {
+ increment = batch_size / 30;
+ } else {
+ increment = batch_size / 100;
+ }
+ batch_size += std::max(5, increment);
+ }
+ }
+
+ LOG(INFO) << "[Throughput Result] max_batch_size " << max_batch_size
+ << ", max_throughput " << max_throughput;
+}
\ No newline at end of file
diff --git a/tensorflow/recom/cxxopts.hpp b/tensorflow/recom/cxxopts.hpp
new file mode 100644
index 00000000000..aa9586bfcd6
--- /dev/null
+++ b/tensorflow/recom/cxxopts.hpp
@@ -0,0 +1,2823 @@
+/*
+
+Copyright (c) 2014-2022 Jarryd Beck
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+
+*/
+
+// vim: ts=2:sw=2:expandtab
+
+#ifndef CXXOPTS_HPP_INCLUDED
+#define CXXOPTS_HPP_INCLUDED
+
+#include <cstring>
+#include <exception>
+#include <limits>
+#include <initializer_list>
+#include <map>
+#include <memory>
+#include <sstream>
+#include <string>
+#include <unordered_map>
+#include <unordered_set>
+#include <utility>
+#include <vector>
+#include <algorithm>
+#include <locale>
+
+#ifdef CXXOPTS_NO_EXCEPTIONS
+#include <iostream>
+#endif
+
+#if defined(__GNUC__) && !defined(__clang__)
+# if (__GNUC__ * 10 + __GNUC_MINOR__) < 49
+# define CXXOPTS_NO_REGEX true
+# endif
+#endif
+#if defined(_MSC_VER) && !defined(__clang__)
+#define CXXOPTS_LINKONCE_CONST __declspec(selectany) extern
+#define CXXOPTS_LINKONCE __declspec(selectany) extern
+#else
+#define CXXOPTS_LINKONCE_CONST
+#define CXXOPTS_LINKONCE
+#endif
+
+#ifndef CXXOPTS_NO_REGEX
+# include <regex>
+#endif // CXXOPTS_NO_REGEX
+
+// Nonstandard before C++17, which is coincidentally what we also need for <optional>
+#ifdef __has_include
+# if __has_include(<optional>)
+# include <optional>
+# ifdef __cpp_lib_optional
+# define CXXOPTS_HAS_OPTIONAL
+# endif
+# endif
+#endif
+
+#if __cplusplus >= 201603L
+#define CXXOPTS_NODISCARD [[nodiscard]]
+#else
+#define CXXOPTS_NODISCARD
+#endif
+
+#ifndef CXXOPTS_VECTOR_DELIMITER
+#define CXXOPTS_VECTOR_DELIMITER ','
+#endif
+
+#define CXXOPTS__VERSION_MAJOR 3
+#define CXXOPTS__VERSION_MINOR 1
+#define CXXOPTS__VERSION_PATCH 1
+
+#if (__GNUC__ < 10 || (__GNUC__ == 10 && __GNUC_MINOR__ < 1)) && __GNUC__ >= 6
+ #define CXXOPTS_NULL_DEREF_IGNORE
+#endif
+
+#if defined(__GNUC__)
+#define DO_PRAGMA(x) _Pragma(#x)
+#define CXXOPTS_DIAGNOSTIC_PUSH DO_PRAGMA(GCC diagnostic push)
+#define CXXOPTS_DIAGNOSTIC_POP DO_PRAGMA(GCC diagnostic pop)
+#define CXXOPTS_IGNORE_WARNING(x) DO_PRAGMA(GCC diagnostic ignored x)
+#else
+// define other compilers here if needed
+#define CXXOPTS_DIAGNOSTIC_PUSH
+#define CXXOPTS_DIAGNOSTIC_POP
+#define CXXOPTS_IGNORE_WARNING(x)
+#endif
+
+#ifdef CXXOPTS_NO_RTTI
+#define CXXOPTS_RTTI_CAST static_cast
+#else
+#define CXXOPTS_RTTI_CAST dynamic_cast
+#endif
+
+namespace cxxopts {
+static constexpr struct {
+ uint8_t major, minor, patch;
+} version = {
+ CXXOPTS__VERSION_MAJOR,
+ CXXOPTS__VERSION_MINOR,
+ CXXOPTS__VERSION_PATCH
+};
+} // namespace cxxopts
+
+//when we ask cxxopts to use Unicode, help strings are processed using ICU,
+//which results in the correct lengths being computed for strings when they
+//are formatted for the help output
+//it is necessary to make sure that <unicode/unistr.h> can be found by the
+//compiler, and that icu-uc is linked in to the binary.
+
+#ifdef CXXOPTS_USE_UNICODE
+#include <unicode/unistr.h>
+
+namespace cxxopts {
+
+using String = icu::UnicodeString;
+
+inline
+String
+toLocalString(std::string s)
+{
+ return icu::UnicodeString::fromUTF8(std::move(s));
+}
+
+// GNU GCC with -Weffc++ will issue a warning regarding the upcoming class, we want to silence it:
+// warning: base class 'class std::enable_shared_from_this<cxxopts::Value>' has accessible non-virtual destructor
+CXXOPTS_DIAGNOSTIC_PUSH
+CXXOPTS_IGNORE_WARNING("-Wnon-virtual-dtor")
+// This will be ignored under other compilers like LLVM clang.
+class UnicodeStringIterator
+{
+ public:
+
+ using iterator_category = std::forward_iterator_tag;
+ using value_type = int32_t;
+ using difference_type = std::ptrdiff_t;
+ using pointer = value_type*;
+ using reference = value_type&;
+
+ UnicodeStringIterator(const icu::UnicodeString* string, int32_t pos)
+ : s(string)
+ , i(pos)
+ {
+ }
+
+ value_type
+ operator*() const
+ {
+ return s->char32At(i);
+ }
+
+ bool
+ operator==(const UnicodeStringIterator& rhs) const
+ {
+ return s == rhs.s && i == rhs.i;
+ }
+
+ bool
+ operator!=(const UnicodeStringIterator& rhs) const
+ {
+ return !(*this == rhs);
+ }
+
+ UnicodeStringIterator&
+ operator++()
+ {
+ ++i;
+ return *this;
+ }
+
+ UnicodeStringIterator
+ operator+(int32_t v)
+ {
+ return UnicodeStringIterator(s, i + v);
+ }
+
+ private:
+ const icu::UnicodeString* s;
+ int32_t i;
+};
+CXXOPTS_DIAGNOSTIC_POP
+
+inline
+String&
+stringAppend(String&s, String a)
+{
+ return s.append(std::move(a));
+}
+
+inline
+String&
+stringAppend(String& s, std::size_t n, UChar32 c)
+{
+ for (std::size_t i = 0; i != n; ++i)
+ {
+ s.append(c);
+ }
+
+ return s;
+}
+
+template <typename Iterator>
+String&
+stringAppend(String& s, Iterator begin, Iterator end)
+{
+ while (begin != end)
+ {
+ s.append(*begin);
+ ++begin;
+ }
+
+ return s;
+}
+
+inline
+size_t
+stringLength(const String& s)
+{
+ return static_cast<size_t>(s.length());
+}
+
+inline
+std::string
+toUTF8String(const String& s)
+{
+ std::string result;
+ s.toUTF8String(result);
+
+ return result;
+}
+
+inline
+bool
+empty(const String& s)
+{
+ return s.isEmpty();
+}
+
+} // namespace cxxopts
+
+namespace std {
+
+inline
+cxxopts::UnicodeStringIterator
+begin(const icu::UnicodeString& s)
+{
+ return cxxopts::UnicodeStringIterator(&s, 0);
+}
+
+inline
+cxxopts::UnicodeStringIterator
+end(const icu::UnicodeString& s)
+{
+ return cxxopts::UnicodeStringIterator(&s, s.length());
+}
+
+} // namespace std
+
+//ifdef CXXOPTS_USE_UNICODE
+#else
+
+namespace cxxopts {
+
+using String = std::string;
+
+template <typename T>
+T
+toLocalString(T&& t)
+{
+ return std::forward<T>(t);
+}
+
+inline
+std::size_t
+stringLength(const String& s)
+{
+ return s.length();
+}
+
+inline
+String&
+stringAppend(String&s, const String& a)
+{
+ return s.append(a);
+}
+
+inline
+String&
+stringAppend(String& s, std::size_t n, char c)
+{
+ return s.append(n, c);
+}
+
+template <typename Iterator>
+String&
+stringAppend(String& s, Iterator begin, Iterator end)
+{
+ return s.append(begin, end);
+}
+
+template <typename T>
+std::string
+toUTF8String(T&& t)
+{
+ return std::forward<T>(t);
+}
+
+inline
+bool
+empty(const std::string& s)
+{
+ return s.empty();
+}
+
+} // namespace cxxopts
+
+//ifdef CXXOPTS_USE_UNICODE
+#endif
+
+namespace cxxopts {
+
+namespace {
+CXXOPTS_LINKONCE_CONST std::string LQUOTE("\'");
+CXXOPTS_LINKONCE_CONST std::string RQUOTE("\'");
+} // namespace
+
+// GNU GCC with -Weffc++ will issue a warning regarding the upcoming class, we
+// want to silence it: warning: base class 'class
+// std::enable_shared_from_this<cxxopts::Value>' has accessible non-virtual
+// destructor This will be ignored under other compilers like LLVM clang.
+CXXOPTS_DIAGNOSTIC_PUSH
+CXXOPTS_IGNORE_WARNING("-Wnon-virtual-dtor")
+
+// some older versions of GCC warn under this warning
+CXXOPTS_IGNORE_WARNING("-Weffc++")
+class Value : public std::enable_shared_from_this<Value>
+{
+ public:
+
+ virtual ~Value() = default;
+
+ virtual
+ std::shared_ptr<Value>
+ clone() const = 0;
+
+ virtual void
+ parse(const std::string& text) const = 0;
+
+ virtual void
+ parse() const = 0;
+
+ virtual bool
+ has_default() const = 0;
+
+ virtual bool
+ is_container() const = 0;
+
+ virtual bool
+ has_implicit() const = 0;
+
+ virtual std::string
+ get_default_value() const = 0;
+
+ virtual std::string
+ get_implicit_value() const = 0;
+
+ virtual std::shared_ptr<Value>
+ default_value(const std::string& value) = 0;
+
+ virtual std::shared_ptr<Value>
+ implicit_value(const std::string& value) = 0;
+
+ virtual std::shared_ptr<Value>
+ no_implicit_value() = 0;
+
+ virtual bool
+ is_boolean() const = 0;
+};
+
+CXXOPTS_DIAGNOSTIC_POP
+
+namespace exceptions {
+
+class exception : public std::exception
+{
+ public:
+ explicit exception(std::string message)
+ : m_message(std::move(message))
+ {
+ }
+
+ CXXOPTS_NODISCARD
+ const char*
+ what() const noexcept override
+ {
+ return m_message.c_str();
+ }
+
+ private:
+ std::string m_message;
+};
+
+class specification : public exception
+{
+ public:
+
+ explicit specification(const std::string& message)
+ : exception(message)
+ {
+ }
+};
+
+class parsing : public exception
+{
+ public:
+ explicit parsing(const std::string& message)
+ : exception(message)
+ {
+ }
+};
+
+class option_already_exists : public specification
+{
+ public:
+ explicit option_already_exists(const std::string& option)
+ : specification("Option " + LQUOTE + option + RQUOTE + " already exists")
+ {
+ }
+};
+
+class invalid_option_format : public specification
+{
+ public:
+ explicit invalid_option_format(const std::string& format)
+ : specification("Invalid option format " + LQUOTE + format + RQUOTE)
+ {
+ }
+};
+
+class invalid_option_syntax : public parsing {
+ public:
+ explicit invalid_option_syntax(const std::string& text)
+ : parsing("Argument " + LQUOTE + text + RQUOTE +
+ " starts with a - but has incorrect syntax")
+ {
+ }
+};
+
+class no_such_option : public parsing
+{
+ public:
+ explicit no_such_option(const std::string& option)
+ : parsing("Option " + LQUOTE + option + RQUOTE + " does not exist")
+ {
+ }
+};
+
+class missing_argument : public parsing
+{
+ public:
+ explicit missing_argument(const std::string& option)
+ : parsing(
+ "Option " + LQUOTE + option + RQUOTE + " is missing an argument"
+ )
+ {
+ }
+};
+
+class option_requires_argument : public parsing
+{
+ public:
+ explicit option_requires_argument(const std::string& option)
+ : parsing(
+ "Option " + LQUOTE + option + RQUOTE + " requires an argument"
+ )
+ {
+ }
+};
+
+class gratuitous_argument_for_option : public parsing
+{
+ public:
+ gratuitous_argument_for_option
+ (
+ const std::string& option,
+ const std::string& arg
+ )
+ : parsing(
+ "Option " + LQUOTE + option + RQUOTE +
+ " does not take an argument, but argument " +
+ LQUOTE + arg + RQUOTE + " given"
+ )
+ {
+ }
+};
+
+class requested_option_not_present : public parsing
+{
+ public:
+ explicit requested_option_not_present(const std::string& option)
+ : parsing("Option " + LQUOTE + option + RQUOTE + " not present")
+ {
+ }
+};
+
+class option_has_no_value : public exception
+{
+ public:
+ explicit option_has_no_value(const std::string& option)
+ : exception(
+ !option.empty() ?