forked from leejet/stable-diffusion.cpp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
5395 lines (4983 loc) · 205 KB
/
main.cpp
File metadata and controls
5395 lines (4983 loc) · 205 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
#include <algorithm>
#include <chrono>
#include <cctype>
#include <cmath>
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <deque>
#include <filesystem>
#include <functional>
#include <map>
#include <unordered_map>
#include <numeric>
#include <optional>
#include <sstream>
#include <iostream>
#include <memory>
#include <limits>
#include <mutex>
#include <random>
#include <set>
#include <string>
#include <system_error>
#include <utility>
#include <vector>
#include "stable-diffusion.h"
#include "model.h"
#include "httplib.h"
#include "json.hpp"
#define STB_IMAGE_IMPLEMENTATION
#define STB_IMAGE_STATIC
#include "stb_image.h"
#define STB_IMAGE_RESIZE_IMPLEMENTATION
#define STB_IMAGE_RESIZE_STATIC
#include "stb_image_resize.h"
#define STB_IMAGE_WRITE_IMPLEMENTATION
#define STB_IMAGE_WRITE_STATIC
#include "stb_image_write.h"
using json = nlohmann::json;
namespace fs = std::filesystem;
namespace {
std::string to_lower_copy(const std::string& input) {
std::string lowered = input;
std::transform(lowered.begin(), lowered.end(), lowered.begin(), [](unsigned char ch) {
return static_cast<char>(std::tolower(ch));
});
return lowered;
}
std::string trim_copy(const std::string& input) {
size_t first = input.find_first_not_of(" \t\n\r");
if (first == std::string::npos) {
return {};
}
size_t last = input.find_last_not_of(" \t\n\r");
return input.substr(first, last - first + 1);
}
std::vector<std::string> split_and_trim(const std::string& input, char delimiter) {
std::vector<std::string> parts;
if (input.empty()) {
return parts;
}
size_t start_pos = 0;
while (start_pos <= input.size()) {
size_t end = input.find(delimiter, start_pos);
std::string part;
if (end == std::string::npos) {
part = input.substr(start_pos);
parts.push_back(trim_copy(part));
break;
}
part = input.substr(start_pos, end - start_pos);
parts.push_back(trim_copy(part));
start_pos = end + 1;
if (start_pos == input.size()) {
parts.emplace_back();
break;
}
}
return parts;
}
std::string trim_trailing_separators(const std::string& input) {
std::string trimmed = input;
while (!trimmed.empty()) {
char tail = trimmed.back();
if (tail == '/' || tail == '\\') {
trimmed.pop_back();
} else {
break;
}
}
return trimmed;
}
bool has_trailing_separator(const std::string& input) {
return !input.empty() && (input.back() == '/' || input.back() == '\\');
}
std::string default_convert_output_path(const std::string& input_path, const std::string& qtype) {
std::string trimmed = trim_trailing_separators(input_path);
fs::path input_fs = trimmed.empty() ? fs::path(input_path) : fs::path(trimmed);
fs::path parent = input_fs.parent_path();
std::string stem;
if (!input_fs.filename().empty()) {
stem = input_fs.stem().string();
if (stem.empty()) {
stem = input_fs.filename().string();
}
}
if (stem.empty()) {
stem = "model";
}
std::string type_label = qtype.empty() ? "unknown" : qtype;
fs::path output = parent / (stem + "_" + type_label + ".gguf");
return output.string();
}
int64_t generate_random_seed() {
std::random_device rd;
uint64_t high = static_cast<uint64_t>(rd()) << 32u;
uint64_t low = static_cast<uint64_t>(rd());
uint64_t combined = (high | low) & std::numeric_limits<int64_t>::max();
if (combined == 0) {
combined = 1;
}
return static_cast<int64_t>(combined);
}
sd_cache_params_t make_cache_defaults() {
sd_cache_params_t params;
sd_cache_params_init(¶ms);
params.mode = SD_CACHE_DISABLED;
params.reuse_threshold = 0.2f;
params.start_percent = 0.15f;
params.end_percent = 0.95f;
return params;
}
void set_cache_mode(sd_cache_params_t& params, sd_cache_mode_t mode) {
params.mode = mode;
}
bool cache_enabled(const sd_cache_params_t& params) {
return params.mode != SD_CACHE_DISABLED;
}
bool parse_cache_mode(const std::string& value, sd_cache_mode_t& mode_out) {
if (value == "disabled" || value == "none") {
mode_out = SD_CACHE_DISABLED;
return true;
}
if (value == "easycache") {
mode_out = SD_CACHE_EASYCACHE;
return true;
}
if (value == "ucache") {
mode_out = SD_CACHE_UCACHE;
return true;
}
if (value == "dbcache") {
mode_out = SD_CACHE_DBCACHE;
return true;
}
if (value == "taylorseer") {
mode_out = SD_CACHE_TAYLORSEER;
return true;
}
if (value == "cache-dit" || value == "cache_dit" || value == "cachedit") {
mode_out = SD_CACHE_CACHE_DIT;
return true;
}
return false;
}
const char* log_level_tag(sd_log_level_t level) {
switch (level) {
case SD_LOG_DEBUG:
return "DEBUG";
case SD_LOG_INFO:
return "INFO";
case SD_LOG_WARN:
return "WARN";
case SD_LOG_ERROR:
return "ERROR";
default:
return "INFO";
}
}
std::string log_level_to_string(sd_log_level_t level) {
switch (level) {
case SD_LOG_DEBUG:
return "debug";
case SD_LOG_INFO:
return "info";
case SD_LOG_WARN:
return "warn";
case SD_LOG_ERROR:
return "error";
default:
return "info";
}
}
std::string base64_encode(const unsigned char* data, size_t length) {
static const char table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
if (length == 0) {
return {};
}
std::string encoded;
encoded.reserve(((length + 2) / 3) * 4);
size_t i = 0;
while (i + 2 < length) {
unsigned char b0 = data[i];
unsigned char b1 = data[i + 1];
unsigned char b2 = data[i + 2];
encoded.push_back(table[(b0 >> 2) & 0x3F]);
encoded.push_back(table[((b0 & 0x03) << 4) | ((b1 >> 4) & 0x0F)]);
encoded.push_back(table[((b1 & 0x0F) << 2) | ((b2 >> 6) & 0x03)]);
encoded.push_back(table[b2 & 0x3F]);
i += 3;
}
if (i < length) {
unsigned char b0 = data[i];
encoded.push_back(table[(b0 >> 2) & 0x3F]);
if (i + 1 < length) {
unsigned char b1 = data[i + 1];
encoded.push_back(table[((b0 & 0x03) << 4) | ((b1 >> 4) & 0x0F)]);
encoded.push_back(table[(b1 & 0x0F) << 2]);
encoded.push_back('=');
} else {
encoded.push_back(table[(b0 & 0x03) << 4]);
encoded.push_back('=');
encoded.push_back('=');
}
}
return encoded;
}
struct Utf8SplitResult {
std::string valid;
std::string remainder;
};
Utf8SplitResult extract_complete_utf8(const std::string& input) {
Utf8SplitResult result;
result.valid.reserve(input.size());
const std::size_t size = input.size();
std::size_t i = 0;
while (i < size) {
unsigned char c = static_cast<unsigned char>(input[i]);
if (c < 0x80) {
result.valid.push_back(static_cast<char>(c));
++i;
continue;
}
std::size_t expected = 0;
if (c >= 0xC2 && c <= 0xDF) {
expected = 2;
} else if (c >= 0xE0 && c <= 0xEF) {
expected = 3;
} else if (c >= 0xF0 && c <= 0xF4) {
expected = 4;
} else {
result.valid.push_back('?');
++i;
continue;
}
if (i + expected > size) {
result.remainder = input.substr(i);
return result;
}
bool valid_sequence = true;
for (std::size_t j = 1; j < expected; ++j) {
unsigned char continuation = static_cast<unsigned char>(input[i + j]);
if ((continuation & 0xC0) != 0x80) {
valid_sequence = false;
break;
}
}
if (!valid_sequence) {
result.valid.push_back('?');
++i;
continue;
}
if (expected == 3) {
unsigned char b1 = static_cast<unsigned char>(input[i + 1]);
if (c == 0xE0 && b1 < 0xA0) {
result.valid.push_back('?');
++i;
continue;
}
if (c == 0xED && b1 >= 0xA0) {
result.valid.push_back('?');
++i;
continue;
}
} else if (expected == 4) {
unsigned char b1 = static_cast<unsigned char>(input[i + 1]);
if (c == 0xF0 && b1 < 0x90) {
result.valid.push_back('?');
++i;
continue;
}
if (c == 0xF4 && b1 >= 0x90) {
result.valid.push_back('?');
++i;
continue;
}
}
result.valid.append(input, i, expected);
i += expected;
}
return result;
}
struct OwnedImage {
uint32_t width = 0;
uint32_t height = 0;
uint32_t channel = 0;
std::vector<uint8_t> data;
bool valid() const {
return width > 0 && height > 0 && !data.empty() && channel > 0;
}
sd_image_t as_sd_image() const {
sd_image_t image;
image.width = width;
image.height = height;
image.channel = channel;
image.data = data.empty() ? nullptr : const_cast<uint8_t*>(data.data());
return image;
}
};
bool process_loaded_pixels(const std::string& source_label,
int expected_width,
int expected_height,
int actual_channel,
int width,
int height,
const stbi_uc* pixels,
OwnedImage& out,
std::string& error) {
if (width <= 0 || height <= 0) {
error = "image '" + source_label + "' has invalid dimensions";
return false;
}
std::vector<uint8_t> buffer;
buffer.assign(pixels, pixels + static_cast<size_t>(width) * height * actual_channel);
if (expected_width > 0 && expected_height > 0 && (width != expected_width || height != expected_height)) {
float dst_aspect = static_cast<float>(expected_width) / static_cast<float>(expected_height);
float src_aspect = static_cast<float>(width) / static_cast<float>(height);
int crop_x = 0;
int crop_y = 0;
int crop_w = width;
int crop_h = height;
if (src_aspect > dst_aspect) {
crop_w = static_cast<int>(std::lround(height * dst_aspect));
crop_x = (width - crop_w) / 2;
} else if (src_aspect < dst_aspect) {
crop_h = static_cast<int>(std::lround(width / dst_aspect));
crop_y = (height - crop_h) / 2;
}
if (crop_x != 0 || crop_y != 0 || crop_w != width || crop_h != height) {
std::vector<uint8_t> cropped(static_cast<size_t>(crop_w) * crop_h * actual_channel);
for (int row = 0; row < crop_h; ++row) {
const uint8_t* src = buffer.data() + (static_cast<size_t>(crop_y + row) * width + crop_x) * actual_channel;
uint8_t* dst = cropped.data() + static_cast<size_t>(row) * crop_w * actual_channel;
std::memcpy(dst, src, static_cast<size_t>(crop_w) * actual_channel);
}
buffer.swap(cropped);
width = crop_w;
height = crop_h;
}
if (width != expected_width || height != expected_height) {
std::vector<uint8_t> resized(static_cast<size_t>(expected_width) * expected_height * actual_channel);
if (!stbir_resize_uint8(buffer.data(),
width,
height,
0,
resized.data(),
expected_width,
expected_height,
0,
actual_channel)) {
error = "failed to resize image '" + source_label + "'";
return false;
}
buffer.swap(resized);
width = expected_width;
height = expected_height;
}
}
out.width = static_cast<uint32_t>(width);
out.height = static_cast<uint32_t>(height);
out.channel = static_cast<uint32_t>(actual_channel);
out.data = std::move(buffer);
return true;
}
bool load_image_file(const std::string& path,
int expected_width,
int expected_height,
int expected_channel,
OwnedImage& out,
std::string& error) {
int width = 0;
int height = 0;
int channels = 0;
if (expected_channel <= 0) {
expected_channel = 3;
}
stbi_uc* raw_pixels = stbi_load(path.c_str(), &width, &height, &channels, expected_channel);
std::unique_ptr<stbi_uc, decltype(&stbi_image_free)> pixels_guard(raw_pixels, stbi_image_free);
if (pixels_guard == nullptr) {
error = "failed to load image from '" + path + "'";
return false;
}
const int actual_channel = expected_channel;
return process_loaded_pixels(path, expected_width, expected_height, actual_channel, width, height, pixels_guard.get(), out, error);
}
bool load_image_from_memory(const std::string& label,
const unsigned char* buffer,
size_t length,
int expected_width,
int expected_height,
int expected_channel,
OwnedImage& out,
std::string& error) {
if (buffer == nullptr || length == 0) {
error = "image '" + label + "' has no data";
return false;
}
if (expected_channel <= 0) {
expected_channel = 3;
}
if (length > static_cast<size_t>(std::numeric_limits<int>::max())) {
error = "image '" + label + "' is too large to decode";
return false;
}
int width = 0;
int height = 0;
int channels = 0;
stbi_uc* raw_pixels =
stbi_load_from_memory(buffer, static_cast<int>(length), &width, &height, &channels, expected_channel);
std::unique_ptr<stbi_uc, decltype(&stbi_image_free)> pixels_guard(raw_pixels, stbi_image_free);
if (pixels_guard == nullptr) {
error = "failed to decode image data from '" + label + "'";
return false;
}
const int actual_channel = expected_channel;
return process_loaded_pixels(label, expected_width, expected_height, actual_channel, width, height, pixels_guard.get(), out, error);
}
std::string describe_httplib_error(httplib::Error err) {
switch (err) {
case httplib::Error::Success:
return "success";
case httplib::Error::Unknown:
return "unknown error";
case httplib::Error::Connection:
return "connection error";
case httplib::Error::BindIPAddress:
return "failed to bind local address";
case httplib::Error::Read:
return "read error";
case httplib::Error::Write:
return "write error";
case httplib::Error::ExceedRedirectCount:
return "too many redirects";
case httplib::Error::Canceled:
return "request canceled";
case httplib::Error::SSLConnection:
return "SSL connection error";
case httplib::Error::SSLLoadingCerts:
return "failed to load SSL certificates";
case httplib::Error::SSLServerVerification:
return "SSL server verification failed";
case httplib::Error::UnsupportedMultipartBoundaryChars:
return "unsupported multipart boundary characters";
case httplib::Error::Compression:
return "compression error";
case httplib::Error::ConnectionTimeout:
return "connection timed out";
case httplib::Error::ProxyConnection:
return "proxy connection error";
default:
return "unexpected transport error";
}
}
bool split_url_base_and_path(const std::string& raw_url, std::string& base, std::string& path, std::string& error) {
std::string trimmed = trim_copy(raw_url);
if (trimmed.empty()) {
error = "url must not be empty";
return false;
}
auto fragment_pos = trimmed.find('#');
if (fragment_pos != std::string::npos) {
trimmed = trimmed.substr(0, fragment_pos);
}
auto scheme_pos = trimmed.find("://");
if (scheme_pos == std::string::npos) {
error = "url must include a scheme such as http:// or https://";
return false;
}
std::string scheme = to_lower_copy(trimmed.substr(0, scheme_pos));
if (scheme != "http" && scheme != "https") {
error = "unsupported URL scheme '" + scheme + "'";
return false;
}
std::size_t authority_start = scheme_pos + 3;
if (authority_start >= trimmed.size()) {
error = "url is missing a host component";
return false;
}
std::size_t path_pos = trimmed.find_first_of("/?", authority_start);
std::string authority;
if (path_pos == std::string::npos) {
authority = trimmed.substr(authority_start);
path = "/";
} else {
authority = trimmed.substr(authority_start, path_pos - authority_start);
path = trimmed.substr(path_pos);
if (path.empty()) {
path = "/";
} else if (path[0] != '/') {
path.insert(path.begin(), '/');
}
}
if (authority.empty()) {
error = "url is missing a host component";
return false;
}
if (authority.find('@') != std::string::npos) {
error = "url must not include user info";
return false;
}
base = scheme + "://" + authority;
return true;
}
bool download_url_to_buffer(const std::string& raw_url, std::vector<uint8_t>& buffer, std::string& error) {
std::string base;
std::string path;
if (!split_url_base_and_path(raw_url, base, path, error)) {
return false;
}
buffer.clear();
try {
httplib::Client client(base);
client.set_follow_location(true);
client.set_connection_timeout(30, 0);
client.set_read_timeout(120, 0);
client.set_write_timeout(120, 0);
#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
client.enable_server_certificate_verification(true);
#endif
if (!client.is_valid()) {
error = "failed to initialize HTTP client for '" + raw_url + "'";
return false;
}
auto result = client.Get(path);
if (!result) {
error = "request to '" + raw_url + "' failed: " + describe_httplib_error(result.error());
return false;
}
if (result->status >= 400) {
error = "request to '" + raw_url + "' failed with HTTP " + std::to_string(result->status);
return false;
}
buffer.assign(result->body.begin(), result->body.end());
return true;
} catch (const std::exception& ex) {
error = "failed to fetch '" + raw_url + "': " + std::string(ex.what());
return false;
}
}
bool load_image_from_url(const std::string& url,
int expected_width,
int expected_height,
int expected_channel,
OwnedImage& out,
std::string& error) {
std::vector<uint8_t> bytes;
if (!download_url_to_buffer(url, bytes, error)) {
return false;
}
if (bytes.empty()) {
error = "downloaded image from '" + url + "' is empty";
return false;
}
return load_image_from_memory(url,
reinterpret_cast<const unsigned char*>(bytes.data()),
bytes.size(),
expected_width,
expected_height,
expected_channel,
out,
error);
}
bool load_images_from_directory(const std::string& directory,
int expected_width,
int expected_height,
int expected_channel,
int max_images,
std::vector<OwnedImage>& images,
std::string& error) {
std::error_code ec;
if (!fs::exists(directory, ec) || !fs::is_directory(directory, ec)) {
error = "directory '" + directory + "' does not exist or is not accessible";
return false;
}
std::vector<fs::directory_entry> candidates;
for (const auto& entry : fs::directory_iterator(directory, ec)) {
if (ec) {
error = "failed to iterate directory '" + directory + "'";
return false;
}
if (!entry.is_regular_file(ec)) {
continue;
}
candidates.push_back(entry);
}
std::sort(candidates.begin(), candidates.end(), [](const fs::directory_entry& a, const fs::directory_entry& b) {
return to_lower_copy(a.path().filename().string()) < to_lower_copy(b.path().filename().string());
});
images.clear();
images.reserve(candidates.size());
auto has_image_extension = [](const fs::path& path) {
std::string ext = to_lower_copy(path.extension().string());
return ext == ".png" || ext == ".jpg" || ext == ".jpeg" || ext == ".bmp";
};
for (const auto& entry : candidates) {
if (!has_image_extension(entry.path())) {
continue;
}
OwnedImage loaded;
if (!load_image_file(entry.path().string(), expected_width, expected_height, expected_channel, loaded, error)) {
return false;
}
images.push_back(std::move(loaded));
if (max_images > 0 && static_cast<int>(images.size()) >= max_images) {
break;
}
}
if (images.empty()) {
error = "no images found in directory '" + directory + "'";
return false;
}
return true;
}
struct CLIOptions {
std::string model_path;
std::string clip_l_path;
std::string clip_g_path;
std::string clip_vision_path;
std::string t5xxl_path;
std::string llm_path;
std::string llm_vision_path;
std::string diffusion_model_path;
std::string high_noise_diffusion_model_path;
std::string vae_path;
std::string taesd_path;
std::string control_net_path;
std::string embedding_dir;
std::string photo_maker_path;
int port = 8000;
int n_threads = -1;
bool verbose = false;
bool diffusion_flash_attn = false;
bool diffusion_conv_direct = false;
bool vae_conv_direct = false;
bool offload_params_to_cpu = false;
bool control_net_cpu = false;
bool clip_on_cpu = false;
bool vae_on_cpu = false;
bool force_sdxl_vae_conv_scale = false;
bool chroma_use_dit_mask = true;
bool chroma_use_t5_mask = false;
int chroma_t5_mask_pad = 1;
float flow_shift = std::numeric_limits<float>::infinity();
sd_type_t wtype = SD_TYPE_COUNT;
rng_type_t rng_type = CUDA_RNG;
prediction_t prediction = PREDICTION_COUNT;
lora_apply_mode_t lora_apply_mode = LORA_APPLY_IMMEDIATELY;
bool cache_provided = false;
sd_cache_params_t cache_params = make_cache_defaults();
};
void print_usage() {
std::cout
<< "Usage: sd-server -m <model_path> [options]\n"
<< "\n"
<< "Model & encoder paths:\n"
<< " -m, --model <path> Primary model path (.gguf)\n"
<< " --diffusion-model <path> Standalone diffusion model path\n"
<< " --high-noise-diffusion-model <path> Standalone high-noise diffusion model path\n"
<< " --vae <path> Standalone VAE path\n"
<< " --taesd <path> Tiny autoencoder path\n"
<< " --clip_l <path> CLIP-L text encoder\n"
<< " --clip_g <path> CLIP-G text encoder\n"
<< " --clip_vision <path> CLIP-Vision encoder\n"
<< " --t5xxl <path> T5 XXL text encoder\n"
<< " --llm <path> LLM text encoder (Qwen2VL, Flux2, etc.)\n"
<< " --llm_vision <path> LLM vision encoder\n"
<< " --control-net <path> ControlNet model path\n"
<< " --lora-model-dir <path> Directory containing LoRA weights\n"
<< " --embd-dir <path> Directory containing textual inversion embeddings\n"
<< " --photo-maker <path> PhotoMaker model path\n"
<< "\n"
<< "Runtime options:\n"
<< " -p, --port <port> HTTP port (default 8000)\n"
<< " -t, --threads <n> Number of CPU threads (-1 auto)\n"
<< " --type <format> Weight type override (e.g. f16, q8_0)\n"
<< " --rng <type> RNG, one of [std_default, cuda]\n"
<< " --prediction <type> Prediction override [eps, v, edm_v, sd3_flow, flux_flow, flux2_flow] (default: auto)\n"
<< " --lora-apply-mode <mode> LoRA apply mode [auto, immediately, at_runtime] (default: immediately)\n"
<< " --flow-shift <value> Flow model shift override\n"
<< " --easycache <thr,start,end> Enable EasyCache with threshold/start/end percents\n"
<< " --ucache <thr,start,end> Enable UCache with threshold/start/end percents\n"
<< " --cache-dit Enable CacheDIT (DBCache + TaylorSeer)\n"
<< " --chroma-t5-mask-pad <int> Padding for Chroma T5 mask\n"
<< "\n"
<< "Device placement:\n"
<< " --offload-to-cpu Offload model weights to CPU RAM\n"
<< " --control-net-cpu Keep ControlNet on CPU\n"
<< " --clip-on-cpu Keep CLIP on CPU\n"
<< " --vae-on-cpu Keep VAE on CPU\n"
<< "\n"
<< "Kernel options:\n"
<< " --diffusion-fa Enable flash attention in diffusion UNet\n"
<< " --diffusion-conv-direct Use ggml_conv2d_direct for diffusion\n"
<< " --vae-conv-direct Use ggml_conv2d_direct for VAE\n"
<< " --force-sdxl-vae-conv-scale Force conv scale for SDXL VAE\n"
<< "\n"
<< "Chroma:\n"
<< " --chroma-disable-dit-mask Disable DiT mask usage\n"
<< " --chroma-enable-t5-mask Enable T5 mask usage\n"
<< "\n"
<< "General:\n"
<< " -v, --verbose Verbose logging\n"
<< " -h, --help Show this help message\n"
<< std::endl;
}
bool parse_arguments(int argc, char** argv, CLIOptions& options, bool& show_help, std::string& error) {
show_help = false;
auto set_cache_mode_cli = [&](sd_cache_mode_t mode) -> bool {
if (options.cache_provided && options.cache_params.mode != mode) {
error = "multiple cache modes specified";
return false;
}
set_cache_mode(options.cache_params, mode);
options.cache_provided = true;
return true;
};
for (int i = 1; i < argc; ++i) {
std::string arg = argv[i];
if (arg == "-m" || arg == "--model") {
if (i + 1 >= argc) {
error = "missing value for -m/--model";
return false;
}
options.model_path = argv[++i];
} else if (arg == "--clip_l") {
if (i + 1 >= argc) {
error = "missing value for --clip_l";
return false;
}
options.clip_l_path = argv[++i];
} else if (arg == "--clip_g") {
if (i + 1 >= argc) {
error = "missing value for --clip_g";
return false;
}
options.clip_g_path = argv[++i];
} else if (arg == "--clip_vision") {
if (i + 1 >= argc) {
error = "missing value for --clip_vision";
return false;
}
options.clip_vision_path = argv[++i];
} else if (arg == "--t5xxl") {
if (i + 1 >= argc) {
error = "missing value for --t5xxl";
return false;
}
options.t5xxl_path = argv[++i];
} else if (arg == "--llm") {
if (i + 1 >= argc) {
error = "missing value for --llm";
return false;
}
options.llm_path = argv[++i];
} else if (arg == "--llm_vision") {
if (i + 1 >= argc) {
error = "missing value for --llm_vision";
return false;
}
options.llm_vision_path = argv[++i];
} else if (arg == "--diffusion-model") {
if (i + 1 >= argc) {
error = "missing value for --diffusion-model";
return false;
}
options.diffusion_model_path = argv[++i];
} else if (arg == "--high-noise-diffusion-model") {
if (i + 1 >= argc) {
error = "missing value for --high-noise-diffusion-model";
return false;
}
options.high_noise_diffusion_model_path = argv[++i];
} else if (arg == "--vae") {
if (i + 1 >= argc) {
error = "missing value for --vae";
return false;
}
options.vae_path = argv[++i];
} else if (arg == "--taesd") {
if (i + 1 >= argc) {
error = "missing value for --taesd";
return false;
}
options.taesd_path = argv[++i];
} else if (arg == "--control-net") {
if (i + 1 >= argc) {
error = "missing value for --control-net";
return false;
}
options.control_net_path = argv[++i];
} else if (arg == "--embd-dir") {
if (i + 1 >= argc) {
error = "missing value for --embd-dir";
return false;
}
options.embedding_dir = argv[++i];
} else if (arg == "--photo-maker") {
if (i + 1 >= argc) {
error = "missing value for --photo-maker";
return false;
}
options.photo_maker_path = argv[++i];
} else if (arg == "-p" || arg == "--port") {
if (i + 1 >= argc) {
error = "missing value for --port";
return false;
}
try {
options.port = std::stoi(argv[++i]);
} catch (const std::exception&) {
error = "invalid port value";
return false;
}
if (options.port <= 0 || options.port > 65535) {
error = "port must be between 1 and 65535";
return false;
}
} else if (arg == "-t" || arg == "--threads") {
if (i + 1 >= argc) {
error = "missing value for -t/--threads";
return false;
}
try {
options.n_threads = std::stoi(argv[++i]);
} catch (const std::exception&) {
error = "invalid threads value";
return false;
}
if (options.n_threads == 0) {
error = "thread count must not be zero";
return false;
}
} else if (arg == "--type") {
if (i + 1 >= argc) {
error = "missing value for --type";
return false;
}
std::string value = to_lower_copy(argv[++i]);
sd_type_t type = str_to_sd_type(value.c_str());
if (type == SD_TYPE_COUNT) {
error = "invalid weight type '" + value + "'";
return false;
}
options.wtype = type;
} else if (arg == "--rng") {
if (i + 1 >= argc) {
error = "missing value for --rng";
return false;
}
std::string value = to_lower_copy(argv[++i]);
rng_type_t rng = str_to_rng_type(value.c_str());
if (rng == RNG_TYPE_COUNT) {
error = "invalid rng '" + value + "'";
return false;
}
options.rng_type = rng;
} else if (arg == "--prediction") {
if (i + 1 >= argc) {
error = "missing value for --prediction";
return false;
}
std::string value = to_lower_copy(argv[++i]);
prediction_t prediction = str_to_prediction(value.c_str());
if (prediction == PREDICTION_COUNT) {
error = "invalid prediction '" + value + "'";
return false;
}
options.prediction = prediction;
} else if (arg == "--lora-apply-mode") {
if (i + 1 >= argc) {
error = "missing value for --lora-apply-mode";
return false;
}
std::string value = to_lower_copy(argv[++i]);
lora_apply_mode_t mode = str_to_lora_apply_mode(value.c_str());
if (mode == LORA_APPLY_MODE_COUNT) {
error = "invalid lora apply mode '" + value + "'";
return false;
}
options.lora_apply_mode = mode;
} else if (arg == "--flow-shift") {
if (i + 1 >= argc) {
error = "missing value for --flow-shift";
return false;
}
std::string value = argv[++i];
if (value == "auto") {
options.flow_shift = std::numeric_limits<float>::infinity();
} else {
try {
options.flow_shift = std::stof(value);
} catch (const std::exception&) {
error = "invalid float for --flow-shift";
return false;
}
}
} else if (arg == "--easycache") {
if (i + 1 >= argc) {
error = "missing value for --easycache";
return false;