-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMultistageOptimizer.cpp
More file actions
2196 lines (2032 loc) · 84.5 KB
/
MultistageOptimizer.cpp
File metadata and controls
2196 lines (2032 loc) · 84.5 KB
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
/*
Filename: MultistageOptimizer.cpp
Description : Calculate optimal mass for each stage given a DeltaV requirement on a multistage Rocket
Source of math equations : http://www.projectrho.com/public_html/rocket/multistage.php
Author: Florian Zimmer
Version : rolling (see GitHub releases: b<commit-count> padded to 5 digits)
Last Changed : 31.03.2021
Legacy changelog (pre-continuous releases):
0.1 basic functionality/port from python project
0.2 debugging
0.3 json input
0.4 cleanup code
0.5 fix Perfomance Issues and Multithreading
0.6 split files
0.7 added config
0.8 added icon
*/
#include <algorithm>
#include <atomic>
#include <chrono>
#include <cctype>
#include <climits>
#include <cmath>
#include <cstdint>
#include <cstring>
#include <cstdlib>
#include <ctime>
#include <fstream>
#include <functional>
#include <iomanip>
#include <iostream>
#include <limits>
#include <sstream>
#include <string>
#include <thread>
#include <vector>
#if defined(_WIN32)
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <windows.h>
#include <psapi.h>
#endif
#include "rocket_definition/Stage.hpp"
#include "rocket_definition/Engine.hpp"
#include "rocket_definition/Rocket.hpp"
#include "math/math.hpp"
#include "math/massCalc.hpp"
#include "math/validation.hpp"
#include "backend/backend_loader.hpp"
#include "backend/full_grid_problem.hpp"
#include "optimizer/budget.hpp"
#include "optimizer/solver.hpp"
#include "optimizer/reporting.hpp"
#include "read_json/read_json.hpp"
#include "util/budget_config.hpp"
#include "util/config_parsing.hpp"
#include "util/format_numbers.hpp"
#include "util/gpu_memory.hpp"
#include "util/text_table.hpp"
using namespace std;
using MassType = double;
struct MemoryCounters {
std::uint64_t working_set_bytes = 0;
std::uint64_t private_bytes = 0;
std::uint64_t gpu_used_bytes = 0;
std::uint64_t gpu_total_bytes = 0;
bool gpu_available = false;
};
static bool readCurrentProcessMemory(MemoryCounters& out)
{
#if defined(_WIN32)
PROCESS_MEMORY_COUNTERS_EX pmc;
std::memset(&pmc, 0, sizeof(pmc));
if (!K32GetProcessMemoryInfo(GetCurrentProcess(),
reinterpret_cast<PROCESS_MEMORY_COUNTERS*>(&pmc),
static_cast<DWORD>(sizeof(pmc)))) {
return false;
}
out.working_set_bytes = static_cast<std::uint64_t>(pmc.WorkingSetSize);
out.private_bytes = static_cast<std::uint64_t>(pmc.PrivateUsage);
return true;
#else
(void)out;
return false;
#endif
}
static bool readCurrentProcessGpuMemory(MemoryCounters& out)
{
util::GpuMemorySample sample = util::sampleProcessGpuMemory();
if (!sample.available) {
return false;
}
out.gpu_used_bytes = sample.used_bytes;
out.gpu_total_bytes = sample.total_bytes;
out.gpu_available = true;
return true;
}
template <typename Fn>
static bool runWithPeakMemory(Fn&& fn, MemoryCounters& peak_out, int sample_ms = 5)
{
std::atomic<bool> stop{false};
MemoryCounters peak;
std::uint64_t gpu_baseline_used = 0;
std::uint64_t gpu_peak_used = 0;
std::uint64_t gpu_total_bytes = 0;
bool gpu_baseline_set = false;
bool gpu_available = false;
if (sample_ms < 0) {
sample_ms = 0;
}
{
MemoryCounters baseline;
if (readCurrentProcessGpuMemory(baseline)) {
gpu_available = true;
gpu_baseline_set = true;
gpu_baseline_used = baseline.gpu_used_bytes;
gpu_peak_used = baseline.gpu_used_bytes;
gpu_total_bytes = baseline.gpu_total_bytes;
}
}
std::thread sampler([&] {
for (;;) {
MemoryCounters current;
if (readCurrentProcessMemory(current)) {
peak.working_set_bytes = std::max(peak.working_set_bytes, current.working_set_bytes);
peak.private_bytes = std::max(peak.private_bytes, current.private_bytes);
}
if (readCurrentProcessGpuMemory(current)) {
gpu_available = true;
gpu_total_bytes = std::max(gpu_total_bytes, current.gpu_total_bytes);
if (!gpu_baseline_set) {
gpu_baseline_set = true;
gpu_baseline_used = current.gpu_used_bytes;
gpu_peak_used = current.gpu_used_bytes;
}
else {
gpu_peak_used = std::max(gpu_peak_used, current.gpu_used_bytes);
}
}
if (stop.load(std::memory_order_relaxed)) {
break;
}
if (sample_ms > 0) {
std::this_thread::sleep_for(std::chrono::milliseconds(sample_ms));
}
}
});
bool ok = false;
try {
ok = fn();
}
catch (...) {
stop.store(true, std::memory_order_relaxed);
sampler.join();
throw;
}
stop.store(true, std::memory_order_relaxed);
sampler.join();
if (gpu_available && gpu_baseline_set) {
peak.gpu_total_bytes = gpu_total_bytes;
peak.gpu_used_bytes = (gpu_peak_used > gpu_baseline_used) ? (gpu_peak_used - gpu_baseline_used) : 0;
peak.gpu_available = true;
}
peak_out = peak;
return ok;
}
struct BenchmarkTimings {
double fill_seconds = 0.0;
double tuple_seconds = 0.0;
double mass_seconds = 0.0;
double min_seconds = 0.0;
double total_seconds = 0.0;
};
struct OptimizationSummary {
BenchmarkTimings timings;
unsigned long long n_combinations = 0;
MassType min_mass = 0.0;
long long min_index = 0;
int stage_count = 0;
int precision = 0;
int threads_used = 0;
int deltaVmission = 0;
std::vector<unsigned char> best_distribution;
};
struct RunOptions {
bool print_output = true;
bool pause_on_exit = true;
bool force_verbose_off = false;
int threads_override = 0;
string full_grid_mode_override;
string backend_override;
string backend_path_override;
int gpu_device_override = std::numeric_limits<int>::min();
};
struct ProgramOptions {
bool benchmark = false;
bool benchmark_compare = false;
int benchmark_iterations = 1;
int benchmark_warmup = 0;
int benchmark_threads = 0;
double benchmark_max_seconds = -1.0;
string benchmark_compare_format = "json";
string benchmark_csv_path = "benchmark_results.csv";
string full_grid_mode_override;
string backend_override;
string backend_path_override;
int gpu_device_override = std::numeric_limits<int>::min();
bool no_prompt = false;
bool show_help = false;
string config_path = "config/config.json";
string benchmark_config_path;
};
using Clock = std::chrono::steady_clock;
static double elapsedSeconds(Clock::time_point start, Clock::time_point end)
{
return std::chrono::duration<double>(end - start).count();
}
static std::string formatBytesHuman(std::uint64_t bytes)
{
std::ostringstream oss;
constexpr double gib_div = 1024.0 * 1024.0 * 1024.0;
double gib = static_cast<double>(bytes) / gib_div;
oss << std::fixed << std::setprecision(2) << gib << " GiB (" << bytes << " bytes)";
return oss.str();
}
static void output2Darr(unsigned char* arr, int sizeY, int sizeX)
{
for (int i = 0; i < sizeY; i++) {
for (int j = 0; j < sizeX; j++) {
std::cout << (int)arr[j * sizeY + i] << "\t";
}
std::cout << "\n";
}
}
static void outputArr(double* arr, int sizeX)
{
for (int i = 0; i < sizeX; i++) {
std::cout << arr[i] << "%\t";
}
}
static string trimLine(const string& value)
{
size_t start = 0;
while (start < value.size() && (value[start] == ' ' || value[start] == '\t' || value[start] == '\r' || value[start] == '\n')) {
start++;
}
size_t end = value.size();
while (end > start && (value[end - 1] == ' ' || value[end - 1] == '\t' || value[end - 1] == '\r' || value[end - 1] == '\n')) {
end--;
}
return value.substr(start, end - start);
}
static bool readFirstLine(const string& path, string& line)
{
ifstream file(path);
if (!file.is_open()) {
return false;
}
if (!std::getline(file, line)) {
return false;
}
line = trimLine(line);
return !line.empty();
}
static string readPackedRef(const string& packed_refs_path, const string& ref)
{
ifstream file(packed_refs_path);
if (!file.is_open()) {
return "";
}
string line;
while (std::getline(file, line)) {
if (line.empty() || line[0] == '#' || line[0] == '^') {
continue;
}
std::istringstream iss(line);
string hash;
string name;
if (!(iss >> hash >> name)) {
continue;
}
if (name == ref) {
return trimLine(hash);
}
}
return "";
}
static bool readEnvVar(const char* name, string& value)
{
#if defined(_MSC_VER)
char* buffer = nullptr;
size_t length = 0;
if (_dupenv_s(&buffer, &length, name) != 0 || buffer == nullptr) {
return false;
}
value.assign(buffer);
free(buffer);
value = trimLine(value);
return !value.empty();
#else
const char* result = std::getenv(name);
if (!result || !*result) {
return false;
}
value = trimLine(result);
return !value.empty();
#endif
}
static string getGitHead()
{
string value;
if (readEnvVar("GIT_HEAD", value)) {
return value;
}
if (readEnvVar("GITHUB_SHA", value)) {
return value;
}
if (readEnvVar("CI_COMMIT_SHA", value)) {
return value;
}
string head_line;
if (!readFirstLine(".git/HEAD", head_line)) {
return "unknown";
}
const string ref_prefix = "ref:";
if (head_line.compare(0, ref_prefix.size(), ref_prefix) == 0) {
string ref_path = trimLine(head_line.substr(ref_prefix.size()));
if (!ref_path.empty() && ref_path[0] == ':') {
ref_path = trimLine(ref_path.substr(1));
}
string ref_line;
if (readFirstLine(".git/" + ref_path, ref_line)) {
return ref_line;
}
string packed_ref = readPackedRef(".git/packed-refs", ref_path);
if (!packed_ref.empty()) {
return packed_ref;
}
return "unknown";
}
return head_line;
}
static string jsonEscape(const string& value)
{
string out;
out.reserve(value.size());
for (char c : value) {
switch (c) {
case '\\':
out += "\\\\";
break;
case '"':
out += "\\\"";
break;
case '\b':
out += "\\b";
break;
case '\f':
out += "\\f";
break;
case '\n':
out += "\\n";
break;
case '\r':
out += "\\r";
break;
case '\t':
out += "\\t";
break;
default:
if (static_cast<unsigned char>(c) < 0x20) {
std::ostringstream oss;
oss << "\\u" << std::hex << std::setw(4) << std::setfill('0') << (int)static_cast<unsigned char>(c);
out += oss.str();
}
else {
out += c;
}
break;
}
}
return out;
}
static bool parseInt(const char* value, int& out)
{
if (!value || *value == '\0') {
return false;
}
char* end = nullptr;
long parsed = std::strtol(value, &end, 10);
if (*end != '\0') {
return false;
}
if (parsed > INT_MAX || parsed < INT_MIN) {
return false;
}
out = static_cast<int>(parsed);
return true;
}
static bool parseDouble(const char* value, double& out)
{
if (!value || *value == '\0') {
return false;
}
char* end = nullptr;
double parsed = std::strtod(value, &end);
if (*end != '\0') {
return false;
}
out = parsed;
return true;
}
static bool parseUInt64Json(const json& value, std::uint64_t& out)
{
if (value.is_number_unsigned()) {
out = value.get<std::uint64_t>();
return true;
}
if (value.is_number_integer()) {
long long signed_value = value.get<long long>();
if (signed_value < 0) {
return false;
}
out = static_cast<std::uint64_t>(signed_value);
return true;
}
if (value.is_number_float()) {
double number = value.get<double>();
if (!std::isfinite(number) || number < 0.0 || number > static_cast<double>(std::numeric_limits<std::uint64_t>::max())) {
return false;
}
out = static_cast<std::uint64_t>(number);
return true;
}
return false;
}
static void printUsage()
{
std::cout << "Usage: MultistageOptimizer.exe [options]\n";
std::cout << "\n";
std::cout << "Options:\n";
std::cout << " --config <path> Config file for normal runs.\n";
std::cout << " --backend <mode> Backend: auto|cpu|cuda|rocm (default: auto).\n";
std::cout << " --backend-path <path> Backend plugin path (file or directory).\n";
std::cout << " --gpu-device <id> GPU device id (default: 0).\n";
std::cout << " --no-prompt Skip waiting for Enter before exit.\n";
std::cout << " --benchmark Run performance benchmark.\n";
std::cout << " --benchmark-compare Run multiple benchmark strategies and compare.\n";
std::cout << " --benchmark-compare-format <f> Output format for --benchmark-compare (json|table).\n";
std::cout << " --benchmark-config <path> Config file for benchmark runs.\n";
std::cout << " --benchmark-iterations <count> Number of benchmark samples.\n";
std::cout << " --benchmark-warmup <count> Warmup runs before sampling.\n";
std::cout << " --benchmark-threads <count> Override thread count.\n";
std::cout << " --fullgrid-mode <mode> Full-grid mode: materialize|streaming (default: materialize).\n";
std::cout << " --benchmark-max-seconds <sec> Fail if average total exceeds this.\n";
std::cout << " --benchmark-csv <path> Append benchmark results to CSV.\n";
std::cout << " --help Show this help.\n";
}
static bool parseOptions(int argc, char** argv, ProgramOptions& options)
{
for (int i = 1; i < argc; i++) {
string arg = argv[i];
if (arg == "--help" || arg == "-h") {
options.show_help = true;
return true;
}
if (arg == "--config") {
if (i + 1 >= argc) {
std::cerr << "Missing value for --config.\n";
return false;
}
options.config_path = argv[++i];
}
else if (arg == "--backend") {
if (i + 1 >= argc) {
std::cerr << "Missing value for --backend.\n";
return false;
}
std::string value = argv[++i];
backend::Mode parsed = backend::Mode::Auto;
if (!backend::parseMode(value, parsed)) {
std::cerr << "Invalid --backend value (expected auto|cpu|cuda|rocm).\n";
return false;
}
options.backend_override = value;
}
else if (arg == "--backend-path") {
if (i + 1 >= argc) {
std::cerr << "Missing value for --backend-path.\n";
return false;
}
options.backend_path_override = argv[++i];
}
else if (arg == "--gpu-device") {
if (i + 1 >= argc) {
std::cerr << "Missing value for --gpu-device.\n";
return false;
}
int value = 0;
if (!parseInt(argv[++i], value) || value < -1) {
std::cerr << "Invalid --gpu-device value.\n";
return false;
}
options.gpu_device_override = value;
}
else if (arg == "--no-prompt") {
options.no_prompt = true;
}
else if (arg == "--benchmark") {
options.benchmark = true;
}
else if (arg == "--benchmark-compare") {
options.benchmark_compare = true;
}
else if (arg == "--benchmark-compare-format") {
if (i + 1 >= argc) {
std::cerr << "Missing value for --benchmark-compare-format.\n";
return false;
}
options.benchmark_compare_format = argv[++i];
if (options.benchmark_compare_format != "json" && options.benchmark_compare_format != "table") {
std::cerr << "Invalid --benchmark-compare-format value (expected json|table).\n";
return false;
}
}
else if (arg == "--benchmark-config") {
if (i + 1 >= argc) {
std::cerr << "Missing value for --benchmark-config.\n";
return false;
}
options.benchmark_config_path = argv[++i];
}
else if (arg == "--benchmark-iterations") {
if (i + 1 >= argc) {
std::cerr << "Missing value for --benchmark-iterations.\n";
return false;
}
int value = 0;
if (!parseInt(argv[++i], value) || value < 1) {
std::cerr << "Invalid --benchmark-iterations value.\n";
return false;
}
options.benchmark_iterations = value;
}
else if (arg == "--benchmark-warmup") {
if (i + 1 >= argc) {
std::cerr << "Missing value for --benchmark-warmup.\n";
return false;
}
int value = 0;
if (!parseInt(argv[++i], value) || value < 0) {
std::cerr << "Invalid --benchmark-warmup value.\n";
return false;
}
options.benchmark_warmup = value;
}
else if (arg == "--benchmark-threads") {
if (i + 1 >= argc) {
std::cerr << "Missing value for --benchmark-threads.\n";
return false;
}
int value = 0;
if (!parseInt(argv[++i], value) || value < 1) {
std::cerr << "Invalid --benchmark-threads value.\n";
return false;
}
options.benchmark_threads = value;
}
else if (arg == "--fullgrid-mode") {
if (i + 1 >= argc) {
std::cerr << "Missing value for --fullgrid-mode.\n";
return false;
}
options.full_grid_mode_override = argv[++i];
}
else if (arg == "--benchmark-max-seconds") {
if (i + 1 >= argc) {
std::cerr << "Missing value for --benchmark-max-seconds.\n";
return false;
}
double value = 0.0;
if (!parseDouble(argv[++i], value) || value <= 0.0) {
std::cerr << "Invalid --benchmark-max-seconds value.\n";
return false;
}
options.benchmark_max_seconds = value;
}
else if (arg == "--benchmark-csv") {
if (i + 1 >= argc) {
std::cerr << "Missing value for --benchmark-csv.\n";
return false;
}
options.benchmark_csv_path = argv[++i];
}
else {
std::cerr << "Unknown argument: " << arg << "\n";
return false;
}
}
return true;
}
static int resolveThreadCount(bool useMultiCore, int threads_override)
{
if (threads_override > 0) {
return threads_override;
}
if (!useMultiCore) {
return 1;
}
unsigned int hw_threads = std::thread::hardware_concurrency();
if (hw_threads == 0) {
return 1;
}
return static_cast<int>(hw_threads);
}
static bool parseFullGridModeString(const std::string& value, optimizer::FullGridMode& out)
{
std::string s;
s.reserve(value.size());
for (char c : value) {
s.push_back(static_cast<char>(std::tolower(static_cast<unsigned char>(c))));
}
if (s == "materialize" || s == "materialized") {
out = optimizer::FullGridMode::Materialize;
return true;
}
if (s == "streaming" || s == "stream") {
out = optimizer::FullGridMode::Streaming;
return true;
}
return false;
}
static bool runOptimization(const json& config, const RunOptions& options, OptimizationSummary& summary, std::string* error_out = nullptr)
{
if (error_out) {
error_out->clear();
}
auto setError = [&](const std::string& message) {
if (error_out) {
*error_out = message;
}
};
bool verbose = false;
if (config.contains("verbose")) {
if (!config["verbose"].is_boolean()) {
std::cerr << "Invalid verbose value in config.\n";
setError("Invalid verbose value in config.");
return false;
}
verbose = config["verbose"].get<bool>();
}
if (options.force_verbose_off) {
verbose = false;
}
optimizer::FullGridMode full_grid_mode = optimizer::FullGridMode::Materialize;
const bool full_grid_mode_explicit = config.contains("fullGridMode") || !options.full_grid_mode_override.empty();
if (config.contains("fullGridMode")) {
if (!config["fullGridMode"].is_string()) {
std::cerr << "Invalid fullGridMode value in config.\n";
setError("Invalid fullGridMode value in config.");
return false;
}
std::string mode = config["fullGridMode"].get<std::string>();
if (!parseFullGridModeString(mode, full_grid_mode)) {
std::cerr << "Invalid fullGridMode value in config (expected materialize|streaming).\n";
setError("Invalid fullGridMode value in config.");
return false;
}
}
if (!options.full_grid_mode_override.empty()) {
if (!parseFullGridModeString(options.full_grid_mode_override, full_grid_mode)) {
std::cerr << "Invalid --fullgrid-mode value (expected materialize|streaming).\n";
setError("Invalid --fullgrid-mode value.");
return false;
}
}
backend::Request backend_request;
backend_request.mode = backend::Mode::Auto;
backend_request.backend_path.clear();
backend_request.device_id = -1;
if (config.contains("backend")) {
if (!config["backend"].is_string()) {
std::cerr << "Invalid backend value in config.\n";
setError("Invalid backend value in config.");
return false;
}
std::string mode = config["backend"].get<std::string>();
if (!backend::parseMode(mode, backend_request.mode)) {
std::cerr << "Invalid backend value in config (expected auto|cpu|cuda|rocm).\n";
setError("Invalid backend value in config.");
return false;
}
}
if (config.contains("backendPath")) {
if (!config["backendPath"].is_string()) {
std::cerr << "Invalid backendPath value in config.\n";
setError("Invalid backendPath value in config.");
return false;
}
backend_request.backend_path = config["backendPath"].get<std::string>();
}
if (config.contains("gpuDevice")) {
if (!config["gpuDevice"].is_number_integer()) {
std::cerr << "Invalid gpuDevice value in config.\n";
setError("Invalid gpuDevice value in config.");
return false;
}
int device = config["gpuDevice"].get<int>();
if (device < -1) {
std::cerr << "Invalid gpuDevice value in config.\n";
setError("Invalid gpuDevice value in config.");
return false;
}
backend_request.device_id = device;
}
if (!options.backend_override.empty()) {
backend::Mode parsed = backend::Mode::Auto;
if (!backend::parseMode(options.backend_override, parsed)) {
std::cerr << "Invalid --backend value (expected auto|cpu|cuda|rocm).\n";
setError("Invalid --backend value.");
return false;
}
backend_request.mode = parsed;
}
if (!options.backend_path_override.empty()) {
backend_request.backend_path = options.backend_path_override;
}
if (options.gpu_device_override != std::numeric_limits<int>::min()) {
if (options.gpu_device_override < -1) {
std::cerr << "Invalid --gpu-device value.\n";
setError("Invalid --gpu-device value.");
return false;
}
backend_request.device_id = options.gpu_device_override;
}
bool useMultiCore = false;
if (config.contains("useMultiCore")) {
if (!config["useMultiCore"].is_boolean()) {
std::cerr << "Invalid useMultiCore value in config.\n";
setError("Invalid useMultiCore value in config.");
return false;
}
useMultiCore = config["useMultiCore"].get<bool>();
}
unsigned long long maxRAM = 0;
if (!config.contains("maxRAM")) {
std::cerr << "Missing maxRAM value in config.\n";
setError("Missing maxRAM value in config.");
return false;
}
if (!parseMaxRam(config["maxRAM"], maxRAM)) {
std::cerr << "Invalid maxRAM value in config.\n";
setError("Invalid maxRAM value in config.");
return false;
}
if (!config.contains("precision") || !config["precision"].is_number()) {
std::cerr << "Missing precision value in config.\n";
setError("Missing precision value in config.");
return false;
}
int precision = config["precision"].get<int>();
if (precision <= 0 || precision > 255) {
std::cerr << "Invalid precision value in config.\n";
setError("Invalid precision value in config.");
return false;
}
vector<Engine> engineList;
Rocket rocket;
try {
engineList = importEngines(config.at("enginesPath").get<string>());
rocket = importRocket(config.at("rocketPath").get<string>(), engineList);
}
catch (const std::exception& e) {
std::cerr << e.what() << "\n";
setError(e.what());
return false;
}
const std::size_t stage_count = rocket.stages.size();
if (stage_count < 1) {
std::cerr << "Rocket has no stages.\n";
setError("Rocket has no stages.");
return false;
}
int nThreads = resolveThreadCount(useMultiCore, options.threads_override);
if (options.threads_override > 0) {
useMultiCore = (nThreads > 1);
}
if (nThreads < 1) {
nThreads = 1;
}
bool zoom_enabled = false;
bool zoom_has_coarse_precision = false;
bool zoom_has_fine_precision = false;
optimizer::ZoomOptions zoom_options;
if (config.contains("zoom") && config["zoom"].is_object()) {
const auto& zoom = config["zoom"];
if (zoom.contains("enabled")) {
zoom_enabled = zoom["enabled"].get<bool>();
}
if (zoom.contains("coarse_precision")) {
zoom_has_coarse_precision = true;
zoom_options.coarse_precision = zoom["coarse_precision"].get<int>();
}
if (zoom.contains("fine_precision")) {
zoom_has_fine_precision = true;
zoom_options.fine_precision = zoom["fine_precision"].get<int>();
}
if (zoom.contains("window_coarse_steps")) {
zoom_options.window_coarse_steps = zoom["window_coarse_steps"].get<int>();
}
if (zoom.contains("top_k")) {
zoom_options.top_k = static_cast<std::size_t>(std::max(1, zoom["top_k"].get<int>()));
}
}
zoom_options.verbose = verbose;
zoom_options.threads = nThreads;
double reporting_min_stage_dv_mps = 0.0;
if (config.contains("reporting") && config["reporting"].is_object()) {
const auto& reporting = config["reporting"];
if (reporting.contains("min_stage_dv_mps")) {
if (!reporting["min_stage_dv_mps"].is_number()) {
std::cerr << "Invalid reporting.min_stage_dv_mps value in config.\n";
setError("Invalid reporting.min_stage_dv_mps value in config.");
return false;
}
reporting_min_stage_dv_mps = reporting["min_stage_dv_mps"].get<double>();
if (!std::isfinite(reporting_min_stage_dv_mps) || reporting_min_stage_dv_mps < 0.0) {
std::cerr << "Invalid reporting.min_stage_dv_mps value in config.\n";
setError("Invalid reporting.min_stage_dv_mps value in config.");
return false;
}
}
}
backend::ResolvedBackend resolved_backend;
std::string backend_error;
if (zoom_enabled) {
if (backend_request.mode == backend::Mode::Cuda) {
std::cerr << "CUDA backend currently supports full-grid runs only (zoom is CPU-only for now).\n";
setError("CUDA backend currently supports full-grid runs only (zoom is CPU-only for now).");
return false;
}
if (backend_request.mode == backend::Mode::Rocm) {
std::cerr << "ROCm backend not implemented yet.\n";
setError("ROCm backend not implemented yet.");
return false;
}
resolved_backend.mode = backend::Mode::Cpu;
}
else {
if (!backend::resolve(backend_request, resolved_backend, backend_error)) {
std::cerr << backend_error << "\n";
setError(backend_error);
return false;
}
}
const bool using_cuda_backend =
(!zoom_enabled && resolved_backend.mode == backend::Mode::Cuda && resolved_backend.plugin.has_value() && resolved_backend.plugin->loaded());
const bool effective_streaming_mode =
(full_grid_mode == optimizer::FullGridMode::Streaming) || using_cuda_backend;
if (using_cuda_backend && full_grid_mode_explicit) {
static bool warned_full_grid_mode_ignored_for_cuda = false;
if (!warned_full_grid_mode_ignored_for_cuda) {
warned_full_grid_mode_ignored_for_cuda = true;
std::cerr << "Note: fullGridMode has no effect when using the CUDA backend; distributions are always enumerated on the device.\n";
}
}
std::uint64_t max_combinations_budget = 0;
util::BudgetBackend budget_backend = using_cuda_backend ? util::BudgetBackend::Cuda : util::BudgetBackend::Cpu;
if (const auto* selected = util::selectBudgetValue(config, budget_backend, "maxCombinations")) {
std::uint64_t parsed = 0;
if (!parseUInt64Json(*selected, parsed) || parsed == 0) {
std::cerr << "Invalid maxCombinations value in config.\n";
setError("Invalid maxCombinations value in config.");
return false;
}
max_combinations_budget = parsed;
}
double target_seconds = -1.0;
if (max_combinations_budget == 0) {
const auto* selected = util::selectBudgetValue(config, budget_backend, "targetSeconds");
if (selected) {
if (!selected->is_number()) {
std::cerr << "Invalid targetSeconds value in config.\n";
setError("Invalid targetSeconds value in config.");
return false;
}
target_seconds = selected->get<double>();
if (!std::isfinite(target_seconds) || target_seconds <= 0.0) {
std::cerr << "Invalid targetSeconds value in config.\n";
setError("Invalid targetSeconds value in config.");
return false;
}
int calib_precision = precision;
if (zoom_enabled && zoom_has_fine_precision && zoom_options.fine_precision > 0) {
calib_precision = zoom_options.fine_precision;
}
calib_precision = std::clamp(calib_precision, static_cast<int>(stage_count), 255);
std::uint64_t calib_total = nCr(calib_precision - 1, static_cast<int>(stage_count) - 1);
if (calib_total == 0) {
std::cerr << "Unable to calibrate runtime (invalid precision/stages).\n";
setError("Unable to calibrate runtime (invalid precision/stages).");
return false;
}
std::uint64_t sample = std::min<std::uint64_t>(5000, calib_total);
std::vector<unsigned char> dist(sample * stage_count, 1);
std::uint64_t gen = createTuple(dist.data(), stage_count, sample, calib_precision);
if (gen != sample) {
std::cerr << "Unable to calibrate runtime (tuple generation failed).\n";
setError("Unable to calibrate runtime (tuple generation failed).");
return false;
}
std::vector<double> masses(sample, 0.0);
auto calib_start = Clock::now();
if (nThreads == 1) {
distMass(false, 0, sample, sample, rocket, masses.data(), dist.data(), calib_precision);
}
else {
std::uint64_t threadBlock = sample / static_cast<std::uint64_t>(nThreads);
std::vector<std::thread> threads;
threads.reserve(static_cast<std::size_t>(nThreads));
for (int t = 0; t < nThreads; t++) {
std::uint64_t begin = static_cast<std::uint64_t>(t) * threadBlock;
std::uint64_t end = (t == nThreads - 1) ? sample : begin + threadBlock;
threads.push_back(std::thread([begin, end, sample, &rocket, &masses, &dist, calib_precision] {
distMass(false, begin, end, sample, rocket, masses.data(), dist.data(), calib_precision);
}));
}
for (auto& th : threads) {
th.join();
}
}
auto calib_end = Clock::now();
double secs = elapsedSeconds(calib_start, calib_end);
if (!std::isfinite(secs) || secs <= 0.0) {
std::cerr << "Unable to calibrate runtime (timing failed).\n";
setError("Unable to calibrate runtime (timing failed).");
return false;
}