-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconvert.cpp
1536 lines (1413 loc) · 60.9 KB
/
convert.cpp
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 "ggml/ggml.h"
// third-party libraries
#include "json.hpp"
#include "zip.h"
#include <stdarg.h>
#include <stdio.h>
#include <cstdlib>
#include <set>
#include <string>
#include <vector>
/*
References:
Pickle Format: https://github.com/python/cpython/blob/main/Lib/pickle.py
Safetensors: https://huggingface.co/docs/safetensors/index
bfloat16 conversion: https://en.wikipedia.org/wiki/Bfloat16_floating-point_format
diffusers to original conversion: https://github.com/comfyanonymous/ComfyUI/blob/master/comfy/diffusers_convert.py
*/
std::string format(const char* fmt, ...) {
char result[100];
va_list args;
va_start(args, fmt);
vsnprintf(result, 100, fmt, args);
va_end(args);
return std::string(result);
}
float bfloat16_to_fp32(uint16_t bfloat16) {
uint32_t val_bits = (static_cast<uint32_t>(bfloat16) << 16);
return *reinterpret_cast<float*>(&val_bits);
}
using json = nlohmann::json;
#define MAX_STRING_BUFFER 95
#define TIMESTEPS 1000
std::vector<std::string> unused_tensors = {
"betas",
"alphas_cumprod_prev",
"sqrt_alphas_cumprod",
"sqrt_one_minus_alphas_cumprod",
"log_one_minus_alphas_cumprod",
"sqrt_recip_alphas_cumprod",
"sqrt_recipm1_alphas_cumprod",
"posterior_variance",
"posterior_log_variance_clipped",
"posterior_mean_coef1",
"posterior_mean_coef2",
"cond_stage_model.transformer.text_model.embeddings.position_ids",
"cond_stage_model.model.logit_scale",
"cond_stage_model.model.text_projection",
"model.diffusion_model.time_embedding.cond_proj.weight",
"model_ema.decay",
"model_ema.num_updates",
"model_ema.diffusion_model",
"control_model",
"embedding_manager"};
std::string kqv_self[] = {
"self_attn.q_proj.weight",
"self_attn.k_proj.weight",
"self_attn.v_proj.weight",
"self_attn.q_proj.bias",
"self_attn.k_proj.bias",
"self_attn.v_proj.bias"};
#ifdef _WIN32 // code for windows
#include <windows.h>
bool file_exists(const std::string& filename) {
DWORD attributes = GetFileAttributesA(filename.c_str());
return (attributes != INVALID_FILE_ATTRIBUTES && !(attributes & FILE_ATTRIBUTE_DIRECTORY));
}
bool is_directory(const std::string& path) {
DWORD attributes = GetFileAttributesA(path.c_str());
return (attributes != INVALID_FILE_ATTRIBUTES && (attributes & FILE_ATTRIBUTE_DIRECTORY));
}
#else // code for linux
#include <dirent.h>
#include <sys/stat.h>
bool file_exists(const std::string& filename) {
struct stat buffer;
return (stat(filename.c_str(), &buffer) == 0 && S_ISREG(buffer.st_mode));
}
bool is_directory(const std::string& path) {
struct stat buffer;
return (stat(path.c_str(), &buffer) == 0 && S_ISDIR(buffer.st_mode));
}
#endif
enum SDVersion {
VERSION_1_x,
VERSION_2_x,
VERSION_XL
};
enum ReadPhase {
READ_NAME,
READ_DATA,
CHECK_SIZE,
READ_DIMENS
};
enum SDLoraType {
LORA_NONE,
LORA_REGULAR,
LORA_DIFFUSERS,
LORA_TRANSFORMERS
};
enum DataPointerType {
CHECKPOINT,
SAFETENSOR
};
enum TensorTarget {
NONE,
CLIP,
UNET,
VAE,
};
enum TinyAutoEncoderType {
TAE_DECODER,
TAE_ENCODER,
TAE_NONE
};
struct ConvertParams {
ggml_type out_type = GGML_TYPE_F32;
SDVersion version = VERSION_1_x;
std::string model_name = "";
std::string model_path = "";
std::string custom_vae_path = "";
std::string output_path = "";
// file pointers
std::vector<zip_t*> pkl_fp;
std::vector<FILE*> sf_fp;
bool from_folder = false;
bool merge_custom_vae = false;
bool verbose = false;
bool generate_alphas_cumprod = false;
// LoRA
bool lora = false;
std::map<std::string, float> lora_alphas;
std::set<std::string> alpha_keys;
std::vector<float> alpha_values;
SDLoraType lora_type = LORA_NONE;
// VAE
bool vae = false;
TinyAutoEncoderType taesd_type = TAE_NONE;
};
struct Tensor {
std::string name;
size_t data_offset = 0;
ggml_type dtype = GGML_TYPE_F32;
size_t data_size = 0;
int32_t shape[4] = {1, 1, 1, 1};
int32_t n_dims = 0;
ReadPhase t_phase = READ_NAME;
int32_t num_elements = 0;
bool is_view = false;
void* data = NULL;
int32_t ptr_idx = -1;
DataPointerType ptr_type = CHECKPOINT;
TensorTarget target = NONE;
Tensor() {}
Tensor(std::string name, ggml_type type, size_t data_size, const int32_t* ne, int n_dims, int32_t num_elements, bool is_view)
: name(name), dtype(type), data_size(data_size), n_dims(n_dims), num_elements(num_elements), is_view(is_view) {
for (int i = 0; i < n_dims; i++) {
shape[i] = ne[i];
}
}
bool detect_target(ConvertParams params) {
if (target != NONE) {
return false;
}
if (name.find("first_stage_model.") == 0 || params.vae) {
target = VAE;
} else if (name.find("model.diffusion_model.") == 0 ||
params.lora && name.find(".unet.") != std::string::npos) {
target = UNET;
} else if (name.find("cond_stage_model.") == 0 ||
name.find("conditioner.") == 0 ||
params.lora && name.find("text.model.") != std::string::npos) {
target = CLIP;
}
return true;
}
void dump() {
printf("Tensor: %30s | n_dim: %i | [%i, %i, %i, %i] | %s \n", name.c_str(), n_dims, shape[0], shape[1], shape[2], shape[3], ggml_type_name(dtype));
}
int64_t* inverse_shape() {
int64_t* v = new int64_t[4];
for (int i = 0; i < 4; i++) {
v[i] = (i < n_dims) ? shape[n_dims - 1 - i] : 1;
}
return v;
}
};
typedef std::unordered_map<std::string, Tensor> TensorMap;
/*
UTILS FUNTIONS
*/
void sd_fread(void* ptr, size_t size, size_t count, FILE* stream) {
size_t ret = std::fread(ptr, size, count, stream);
if (ret != count) {
printf("Error: read from file failed");
exit(1);
}
}
int64_t read_long(uint8_t* buffer) {
// little endian
int64_t value = 0;
value |= static_cast<int64_t>(buffer[7]) << 56;
value |= static_cast<int64_t>(buffer[6]) << 48;
value |= static_cast<int64_t>(buffer[5]) << 40;
value |= static_cast<int64_t>(buffer[4]) << 32;
value |= static_cast<int64_t>(buffer[3]) << 24;
value |= static_cast<int64_t>(buffer[2]) << 16;
value |= static_cast<int64_t>(buffer[1]) << 8;
value |= static_cast<int64_t>(buffer[0]);
return value;
}
int32_t read_int(uint8_t* buffer) {
// little endian
int value = 0;
value |= buffer[3] << 24;
value |= buffer[2] << 16;
value |= buffer[1] << 8;
value |= buffer[0];
return value;
}
uint16_t read_short(uint8_t* buffer) {
// little endian
uint16_t value = 0;
value |= buffer[1] << 8;
value |= buffer[0];
return value;
}
int8_t find_char(uint8_t* buffer, char c) {
for (int8_t len = 0; len < MAX_STRING_BUFFER; len++) {
if (buffer[len] == c) {
return len;
}
}
return -1;
}
// ported from https://github.com/openai/CLIP/blob/main/clip/simple_tokenizer.py#L16
std::map<char, int> unicode_to_byte() {
std::map<int, char> byte_to_unicode;
// List of utf-8 byte ranges
for (int b = static_cast<int>('!'); b <= static_cast<int>('~'); ++b) {
byte_to_unicode[b] = static_cast<char>(b);
}
for (int b = 49825; b <= 49836; ++b) {
byte_to_unicode[b] = static_cast<char>(b);
}
for (int b = 49838; b <= 50111; ++b) {
byte_to_unicode[b] = static_cast<char>(b);
}
// printf("%d %d %d %d\n", static_cast<int>('¡'), static_cast<int>('¬'), static_cast<int>('®'), static_cast<int>('ÿ'));
// exit(1);
int n = 0;
for (int b = 0; b < 256; ++b) {
if (byte_to_unicode.find(b) == byte_to_unicode.end()) {
byte_to_unicode[b] = static_cast<char>(256 + n);
n++;
}
}
// byte_encoder = bytes_to_unicode()
// byte_decoder = {v: k for k, v in byte_encoder.items()}
std::map<char, int> byte_decoder;
for (const auto& entry : byte_to_unicode) {
byte_decoder[entry.second] = entry.first;
}
byte_to_unicode.clear();
return byte_decoder;
}
bool is_unused_tensor(std::string name) {
for (int i = 0; i < unused_tensors.size(); i++) {
if (name.find(unused_tensors[i]) == 0) {
return true;
}
}
return false;
}
float* calculate_alpha_cumprod(float linear_start = 0.00085f, float linear_end = 0.0120, int timesteps = TIMESTEPS) {
float* ac = (float*)malloc(timesteps * 4);
float ls_sqrt = sqrtf(linear_start);
float le_sqrt = sqrtf(linear_end);
float amount = le_sqrt - ls_sqrt;
float product = 1.0f;
for (int i = 0; i < timesteps; i++) {
float beta = ls_sqrt + amount * ((float)i / (timesteps - 1));
product *= 1.0f - powf(beta, 2.0f);
ac[i] = product;
}
return ac;
}
/*
READ PYTORCH CHECKPOINT MODEL
*/
static ggml_type global_type = GGML_TYPE_F32; // all tensors data type
static bool read_global_type = false;
void exist_in_zip(struct zip_t* zip, const char* f_test, Tensor& tensor) {
size_t i, n = zip_entries_total(zip);
for (i = 0; i < n; ++i) {
zip_entry_openbyindex(zip, i);
{
const char* name = zip_entry_name(zip);
if (strcmp(name, f_test) == 0) {
tensor.data_offset = i;
tensor.data_size = zip_entry_size(zip);
zip_entry_close(zip);
return;
}
}
zip_entry_close(zip);
}
}
bool set_pkl_tensor_props(uint32_t value, struct Tensor& tensor) {
if (tensor.t_phase == CHECK_SIZE) {
if (tensor.data_size == value * ggml_type_size(tensor.dtype)) {
tensor.num_elements = value;
tensor.t_phase = READ_DIMENS;
return true;
} else {
tensor.t_phase = READ_NAME;
}
} else if (tensor.t_phase == READ_DIMENS) {
if (tensor.n_dims + 1 > 4) { // too many dimens
tensor.t_phase = READ_NAME;
tensor.n_dims = 0;
}
if (tensor.num_elements % value == 0) {
tensor.shape[tensor.n_dims] = value;
tensor.n_dims++;
}
}
return false;
}
void read_pkl_data_type(char* _name, struct Tensor& tensor) {
if (!strcmp(_name, "FloatStorage")) {
if (read_global_type) {
global_type = GGML_TYPE_F32;
read_global_type = false;
}
tensor.dtype = GGML_TYPE_F32;
} else if (!strcmp(_name, "HalfStorage")) {
if (read_global_type) {
global_type = GGML_TYPE_F16;
read_global_type = false;
}
tensor.dtype = GGML_TYPE_F16;
}
}
void read_pkl_string(char* text_str, struct zip_t* zip, std::string dir, struct Tensor& tensor) {
if (!strcmp(text_str, "storage")) {
read_global_type = true;
} else if (strcmp(text_str, "state_dict")) { // no state_dict
if (tensor.t_phase == READ_DATA) {
std::string zip_entry_name = dir + "data/" + std::string(text_str);
exist_in_zip(zip, zip_entry_name.c_str(), tensor);
tensor.t_phase = tensor.data_size > 0 ? CHECK_SIZE : READ_NAME;
}
if (!read_global_type && tensor.t_phase == READ_NAME) {
tensor.name = text_str;
tensor.t_phase = READ_DATA;
tensor.dtype = global_type;
}
}
}
// $ python -m pickletools sd-v1-4/archive/data.pkl | head -n 100
// 0: \x80 PROTO 2
// 2: } EMPTY_DICT
// 3: q BINPUT 0
// 5: ( MARK
// 6: X BINUNICODE 'epoch'
// 16: q BINPUT 1
// 18: K BININT1 6
// 20: X BINUNICODE 'global_step'
// 36: q BINPUT 2
// 38: J BININT 470000
// 43: X BINUNICODE 'pytorch-lightning_version'
// 73: q BINPUT 3
// 75: X BINUNICODE '1.4.2'
// 85: q BINPUT 4
// 87: X BINUNICODE 'state_dict'
// 102: q BINPUT 5
// 104: } EMPTY_DICT
// 105: q BINPUT 6
// 107: ( MARK
// 108: X BINUNICODE 'betas'
// 118: q BINPUT 7
// 120: c GLOBAL 'torch._utils _rebuild_tensor_v2'
// 153: q BINPUT 8
// 155: ( MARK
// 156: ( MARK
// 157: X BINUNICODE 'storage'
// 169: q BINPUT 9
// 171: c GLOBAL 'torch FloatStorage'
// 191: q BINPUT 10
// 193: X BINUNICODE '0'
// 199: q BINPUT 11
// 201: X BINUNICODE 'cpu'
// 209: q BINPUT 12
// 211: M BININT2 1000
// 214: t TUPLE (MARK at 156)
// 215: q BINPUT 13
// 217: Q BINPERSID
// 218: K BININT1 0
// 220: M BININT2 1000
// ...............................
// 3201: q BINPUT 250
// 3203: R REDUCE
// 3204: q BINPUT 251
// 3206: X BINUNICODE 'model.diffusion_model.input_blocks.1.1.proj_in.weight'
// 3264: q BINPUT 252
// 3266: h BINGET 8
// 3268: ( MARK
// 3269: ( MARK
// 3270: h BINGET 9
// 3272: h BINGET 10
// 3274: X BINUNICODE '30'
// 3281: q BINPUT 253
// 3283: h BINGET 12
// 3285: J BININT 102400
// 3290: t TUPLE (MARK at 3269)
// 3291: q BINPUT 254
// 3293: Q BINPERSID
// 3294: K BININT1 0
// 3296: ( MARK
// 3297: M BININT2 320
// 3300: M BININT2 320
// 3303: K BININT1 1
// 3305: K BININT1 1
// 3307: t TUPLE (MARK at 3296)
// 3308: q BINPUT 255
// 3310: ( MARK
// 3311: M BININT2 320
// 3314: K BININT1 1
// 3316: K BININT1 1
// 3318: K BININT1 1
// 3320: t TUPLE (MARK at 3310)
// 3321: r LONG_BINPUT 256
// 3326: \x89 NEWFALSE
// 3327: h BINGET 16
// 3329: ) EMPTY_TUPLE
// 3330: R REDUCE
// 3331: r LONG_BINPUT 257
// 3336: t TUPLE (MARK at 3268)
// 3337: r LONG_BINPUT 258
// 3342: R REDUCE
// 3343: r LONG_BINPUT 259
// 3348: X BINUNICODE 'model.diffusion_model.input_blocks.1.1.proj_in.bias'
// 3404: r LONG_BINPUT 260
// 3409: h BINGET 8
// 3411: ( MARK
// 3412: ( MARK
// 3413: h BINGET 9
// 3415: h BINGET 10
// 3417: X BINUNICODE '31'
void read_pkl_props(uint8_t* buffer,
zip_t* zip,
std::string dir,
TensorMap& tensors,
ConvertParams& params,
bool root_model,
TensorTarget target = NONE) {
if (buffer[0] == 0x80) { // proto
if (buffer[1] != 2) {
printf("Unsupported protocol\n");
return;
}
buffer += 2; // 0x80 and version
char string_buffer[MAX_STRING_BUFFER];
bool finish = false;
Tensor tensor;
// read pickle binary file
while (!finish) {
uint8_t opcode = *buffer;
buffer++;
// https://github.com/python/cpython/blob/3.7/Lib/pickletools.py#L1048
// https://github.com/python/cpython/blob/main/Lib/pickle.py#L105
switch (opcode) {
case '}': // EMPTY_DICT = b'}' # push empty dict
break;
case ']': // EMPTY_LIST = b']' # push empty list
break;
// skip unused sections
case 'h': // BINGET = b'h' # " " " " " " ; " " 1-byte arg
case 'q': // BINPUT = b'q' # " " " " " ; " " 1-byte arg
case 'Q': // BINPERSID = b'Q' # " " " ; " " " " stack
buffer++;
break;
case 'r': // LONG_BINPUT = b'r' # " " " " " ; " " 4-byte arg
buffer += 4;
break;
case 0x95: // FRAME = b'\x95' # indicate the beginning of a new frame
buffer += 8;
break;
case 0x94: // MEMOIZE = b'\x94' # store top of the stack in memo
break;
case '(': // MARK = b'(' # push special markobject on stack
break;
case 'K': // BININT1 = b'K' # push 1-byte unsigned int
{
uint8_t value = *buffer;
if (set_pkl_tensor_props(value, tensor)) {
buffer++;
}
buffer++;
} break;
case 'M': // BININT2 = b'M' # push 2-byte unsigned int
{
uint16_t value = read_short(buffer);
if (set_pkl_tensor_props(value, tensor)) {
buffer++;
}
buffer += 2;
} break;
case 'J': // BININT = b'J' # push four-byte signed int
{
const int32_t value = read_int(buffer);
if (set_pkl_tensor_props(value, tensor)) {
buffer++; // skip tuple after read num_elements
}
buffer += 4;
} break;
case 'X': // BINUNICODE = b'X' # " " " ; counted UTF-8 string argument
{
const int32_t len = read_int(buffer);
buffer += 4;
memset(string_buffer, 0, MAX_STRING_BUFFER);
if (len > MAX_STRING_BUFFER) {
printf("Tensor name very large\n");
}
memcpy(string_buffer, buffer, len < MAX_STRING_BUFFER ? len : (MAX_STRING_BUFFER - 1));
buffer += len;
read_pkl_string(string_buffer, zip, dir, tensor);
if (params.verbose) {
printf("pickle str: %s\n", string_buffer);
}
} break;
case 0x8C: // SHORT_BINUNICODE = b'\x8c' # push short string; UTF-8 length < 256 bytes
{
const int8_t len = *buffer;
buffer++;
memset(string_buffer, 0, MAX_STRING_BUFFER);
memcpy(string_buffer, buffer, len);
buffer += len;
// printf("String: '%s'\n", string_buffer);
} break;
case 'c': // GLOBAL = b'c' # push self.find_class(modname, name); 2 string args
{
int8_t len = find_char(buffer, '\n');
buffer += len + 1;
len = find_char(buffer, '\n');
memset(string_buffer, 0, MAX_STRING_BUFFER);
memcpy(string_buffer, buffer, len);
buffer += len + 1;
read_pkl_data_type(string_buffer, tensor);
// printf("Global: %s\n", string_buffer);
} break;
case 0x86: // TUPLE2 = b'\x86' # build 2-tuple from two topmost stack items
case 0x85: // TUPLE1 = b'\x85' # build 1-tuple from stack top
case 't': // TUPLE = b't' # build tuple from topmost stack items
if (tensor.t_phase == READ_DIMENS) {
if (!is_unused_tensor(tensor.name)) { // ignore unused tensors
tensor.ptr_idx = (int32_t)params.pkl_fp.size();
if (target != NONE) {
tensor.target = target;
} else if (params.merge_custom_vae) {
if (root_model) {
tensor.detect_target(params);
if (tensor.target == VAE) {
tensor = Tensor();
continue; // ignore original vae tensors
}
} else {
tensor.target = VAE;
tensor.detect_target(params);
}
}
tensors[tensor.name] = tensor;
}
// reset
tensor = Tensor();
}
break;
case '.': // STOP = b'.' # every pickle ends with STOP
finish = true;
break;
default:
break;
}
}
}
}
/*
PREPROCESS TENSORS
*/
std::string replace_name_by_map(const std::string full_name, std::unordered_map<std::string, std::string> ft_map) {
std::string result = full_name;
for (auto it : ft_map) {
size_t pos = result.find(it.first);
if (pos != std::string::npos) {
result = result.replace(pos, it.first.size(), it.second);
}
}
return result;
}
// hugging face pipeline to legacy stable diffusion
std::unordered_map<std::string, std::string> unet_convert_map;
std::unordered_map<std::string, std::string> unet_convert_map_resnet;
std::unordered_map<std::string, std::string> unet_convert_map_layers;
std::unordered_map<std::string, std::string> vae_convert_map;
std::unordered_map<std::string, std::string> clip_convert_map;
std::unordered_map<std::string, std::string> lora_fix_map;
std::string convert_unet_to_original(std::string name, ConvertParams params) {
bool resnet_tensor = name.find("resnets") != std::string::npos;
const char* separator = params.lora ? "." : "_";
if (unet_convert_map.empty()) {
unet_convert_map[format("time%sembedding.linear%s1.weight", separator, separator)] = "time_embed.0.weight";
unet_convert_map[format("time%sembedding.linear%s1.bias", separator, separator)] = "time_embed.0.bias";
unet_convert_map[format("time%sembedding.linear%s2.weight", separator, separator)] = "time_embed.2.weight";
unet_convert_map[format("time%sembedding.linear%s2.bias", separator, separator)] = "time_embed.2.bias";
unet_convert_map[format("conv%sin.weight", separator)] = "input_blocks.0.0.weight";
unet_convert_map[format("conv%sin.bias", separator)] = "input_blocks.0.0.bias";
unet_convert_map[format("conv%snorm%sout.weight", separator, separator)] = "out.0.weight";
unet_convert_map[format("conv%snorm%sout.bias", separator, separator)] = "out.0.bias";
unet_convert_map[format("conv%sout.weight", separator)] = "out.2.weight";
unet_convert_map[format("conv%sout.bias", separator)] = "out.2.bias";
}
// resnet
if (unet_convert_map_resnet.empty() && resnet_tensor) {
unet_convert_map_resnet["norm1"] = "in_layers.0";
unet_convert_map_resnet["conv1"] = "in_layers.2";
unet_convert_map_resnet["norm2"] = "out_layers.0";
unet_convert_map_resnet["conv2"] = "out_layers.3";
unet_convert_map_resnet[format("time%semb%sproj", separator, separator)] = "emb_layers.1";
unet_convert_map_resnet[format("conv%sshortcut", separator)] = "skip_connection";
}
if (unet_convert_map_layers.empty()) {
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 2; j++) {
unet_convert_map_layers[format("down%sblocks.%i.resnets.%i.", separator, i, j)] = format("input_blocks.%i.0.", 3 * i + j + 1);
if (i < 3) {
unet_convert_map_layers[format("down%sblocks.%i.attentions.%i.", separator, i, j)] = format("input_blocks.%i.1.", 3 * i + j + 1);
}
}
for (int j = 0; j < 3; j++) {
unet_convert_map_layers[format("up%sblocks.%i.resnets.%i.", separator, i, j)] = format("output_blocks.%i.0.", 3 * i + j);
if (i > 0) {
unet_convert_map_layers[format("up%sblocks.%i.attentions.%i.", separator, i, j)] = format("output_blocks.%i.1.", 3 * i + j);
}
}
if (i < 3) {
unet_convert_map_layers[format("down%sblocks.%i.downsamplers.0.conv.", separator, i)] = format("input_blocks.%i.0.op.", 3 * (i + 1));
unet_convert_map_layers[format("up%sblocks.%i.upsamplers.0.", separator, i)] = format("output_blocks.%i.%i.", 3 * i + 2, i == 0 ? 1 : 2);
}
}
unet_convert_map_layers[format("mid%sblock.attentions.0.", separator)] = "middle_block.1.";
for (int j = 0; j < 2; j++) {
unet_convert_map_layers[format("mid%sblock.resnets.%i.", separator, j)] = format("middle_block.%i.", 2 * j);
}
}
if (params.lora) {
unet_convert_map[".unet."] = ".model.diffusion_model.";
}
std::string result = replace_name_by_map(name, unet_convert_map);
result = replace_name_by_map(result, unet_convert_map_layers);
if (resnet_tensor) {
result = replace_name_by_map(result, unet_convert_map_resnet);
}
return result;
}
std::string convert_vae_to_original(std::string name, ConvertParams params) {
std::unordered_map<std::string, std::string> vae_map;
bool hf_attention = name.find("attentions") != std::string::npos;
if (vae_convert_map.empty()) {
vae_convert_map["conv_shortcut"] = "nin_shortcut";
vae_convert_map["conv_norm_out"] = "norm_out";
vae_convert_map["mid_block.attentions.0."] = "mid.attn_1.";
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 2; j++) {
vae_convert_map["encoder.down_blocks." + std::to_string(i) + ".resnets." + std::to_string(j) + "."] = "encoder.down." + std::to_string(i) + ".block." + std::to_string(j) + ".";
}
if (i < 2) {
vae_convert_map["mid_block.resnets." + std::to_string(i) + "."] = "mid.block_" + std::to_string(i + 1) + ".";
}
if (i < 3) {
vae_convert_map["down_blocks." + std::to_string(i) + ".downsamplers.0."] = "down." + std::to_string(i) + ".downsample.";
vae_convert_map["up_blocks." + std::to_string(i) + ".upsamplers.0."] = "up." + std::to_string(3 - i) + ".upsample.";
}
for (int j = 0; j < 3; j++) {
vae_convert_map["decoder.up_blocks." + std::to_string(i) + ".resnets." + std::to_string(j) + "."] = "decoder.up." + std::to_string(3 - i) + ".block." + std::to_string(j) + ".";
}
}
}
if (hf_attention || params.version == VERSION_2_x) {
vae_convert_map["to_k."] = "k.";
vae_convert_map["to_q."] = "q.";
vae_convert_map["to_v."] = "v.";
vae_convert_map["to_out.0."] = "proj_out.";
}
if (hf_attention) {
vae_convert_map["key."] = "k.";
vae_convert_map["query."] = "q.";
vae_convert_map["value."] = "v.";
vae_convert_map["group_norm."] = "norm.";
vae_convert_map["proj_attn."] = "proj_out.";
}
return replace_name_by_map(name, vae_convert_map);
}
std::string convert_clip_to_hf_clip(std::string name, ConvertParams params) {
std::string separator = params.lora ? "." : "_";
if (clip_convert_map.empty()) {
if (params.version == VERSION_2_x) {
clip_convert_map[".model."] = ".transformer.text_model.";
clip_convert_map["transformer.resblocks."] = "encoder.layers.";
clip_convert_map["attn.out_proj"] = "self_attn.out_proj";
clip_convert_map["ln_final."] = "final_layer_norm.";
clip_convert_map["token_embedding.weight"] =
"embeddings.token_embedding.weight";
clip_convert_map["positional_embedding"] =
"embeddings.position_embedding.weight";
} else {
clip_convert_map["resblocks."] = "text_model.encoder.layers.";
if (!params.lora) {
clip_convert_map[".attn."] = ".self_attn.";
}
clip_convert_map["ln_final."] = "transformer.text_model.final_layer_norm.";
if (name == "token_embedding.weight") {
return "transformer.text_model.embeddings.token_embedding.weight";
} else if (name == "positional_embedding") {
return "transformer.text_model.embeddings.position_embedding.weight";
}
}
clip_convert_map["ln_1."] = "layer_norm1.";
clip_convert_map["ln_2."] = "layer_norm2.";
clip_convert_map[".c_fc."] = ".fc1.";
clip_convert_map[".c_proj."] = ".fc2.";
}
if (params.lora) {
clip_convert_map["te.text.model"] = "cond_stage_model.transformer.text_model";
}
// SD XL to SD normal
if (params.version == VERSION_XL) {
clip_convert_map["conditioner.embedders.0.transformer.text_model"] = "cond_stage_model.transformer.text_model";
clip_convert_map["conditioner.embedders.1.model"] = "cond_stage_model.g.transformer.text_model";
}
return replace_name_by_map(name, clip_convert_map);
}
std::string fix_lora_names(std::string name) {
// lora fix names
if (lora_fix_map.empty()) {
lora_fix_map["self.attn"] = "self_attn";
lora_fix_map["proj.in"] = "proj_in";
lora_fix_map["proj.out"] = "proj_out";
lora_fix_map["out.proj"] = "out_proj";
lora_fix_map["transformer.blocks"] = "transformer_blocks";
lora_fix_map["q.proj"] = "q_proj";
lora_fix_map["k.proj"] = "k_proj";
lora_fix_map["v.proj"] = "v_proj";
lora_fix_map["to.q"] = "to_q";
lora_fix_map["to.k"] = "to_k";
lora_fix_map["to.v"] = "to_v";
lora_fix_map[".to.out"] = ".to_out";
lora_fix_map[".lora.down."] = ".lora_down.";
lora_fix_map[".lora.up."] = ".lora_up.";
}
return replace_name_by_map(name, lora_fix_map);
}
void* fetch_data(Tensor tensor, ConvertParams params) {
if (!tensor.data) { // fetch tensor data from zip (.ckpt) or file stream (.safetensors)
if (tensor.ptr_type == CHECKPOINT) {
zip_entry_openbyindex(params.pkl_fp[tensor.ptr_idx], tensor.data_offset);
size_t buf_sz;
if (zip_entry_read(params.pkl_fp[tensor.ptr_idx], &tensor.data, &buf_sz) < 0) {
return NULL;
}
} else {
#ifdef _WIN32
_fseeki64(params.sf_fp[tensor.ptr_idx], (__int64)tensor.data_offset, SEEK_SET);
#else
std::fseek(params.sf_fp[tensor.ptr_idx], (long)tensor.data_offset, SEEK_SET);
#endif
tensor.data = malloc(tensor.data_size);
sd_fread(tensor.data, 1, tensor.data_size, params.sf_fp[tensor.ptr_idx]);
}
}
return tensor.data;
}
std::tuple<Tensor, Tensor, Tensor> split_qkv_tensor(Tensor qkv_tensor, void* qkv_data) {
const int ne0 = qkv_tensor.shape[0] / 3; // split in 3 tensors: query, key, value
const int ne1 = qkv_tensor.shape[1];
const int32_t num_elements = ne0 * ne1;
ggml_type dtype = qkv_tensor.dtype;
const int n_dims = qkv_tensor.n_dims;
size_t chunk_size = (size_t)num_elements * ggml_type_size(qkv_tensor.dtype);
int32_t ne[4] = {ne0, ne1, 1, 1};
Tensor q = Tensor("", dtype, chunk_size, ne, n_dims, num_elements, true); // query
Tensor k = Tensor("", dtype, chunk_size, ne, n_dims, num_elements, true); // key
Tensor v = Tensor("", dtype, chunk_size, ne, n_dims, num_elements, true); // value
// make a view of original tensor data
q.data = qkv_data;
k.data = ((char*)qkv_data) + chunk_size;
v.data = ((char*)qkv_data) + chunk_size * 2;
return {q, k, v};
}
void preprocess_tensors(
TensorMap& src,
std::vector<Tensor>& dst,
ConvertParams& params) {
printf("preprocessing %zu tensors\n", src.size());
for (auto& it : src) {
std::string name = it.first;
Tensor tensor = it.second;
if (!tensor.detect_target(params)) {
if (tensor.target == CLIP && name.find("cond_stage_model.transformer.text_model") == std::string::npos) {
if (name.find("text_model.") == 0) {
tensor.name = "cond_stage_model.transformer." + name;
} else {
tensor.name = "cond_stage_model.transformer.text_model" + name;
}
} else if (name.find("model.diffusion_model.") == std::string::npos && tensor.target == UNET) {
tensor.name = "model.diffusion_model." + name;
} else if (name.find("first_stage_model.") == std::string::npos && tensor.target == VAE) {
tensor.name = "first_stage_model." + name;
}
}
if (tensor.target == VAE) {
tensor.name = convert_vae_to_original(tensor.name, params);
if (params.vae && name.find("first_stage_model.") == std::string::npos) {
std::string tae = "";
if(params.taesd_type == TAE_DECODER) {
tae = "decoder.";
} else if(params.taesd_type == TAE_ENCODER) {
tae = "encoder.";
}
tensor.name = "first_stage_model." + tae + tensor.name;
}
// convert vae attn block linear to conv2d 1x1
if (tensor.name.find("attn_1") != std::string::npos) {
if (tensor.n_dims == 2) {
tensor.n_dims += 2;
if (params.verbose) {
printf("linear to conv2d %s\n", tensor.name.c_str());
}
}
}
}
if (tensor.target == CLIP) {
tensor.name = convert_clip_to_hf_clip(tensor.name, params);
if (params.version == VERSION_2_x) {
size_t fw = tensor.name.find("attn.in_proj_weight");
size_t fb = tensor.name.find("attn.in_proj_bias");
if (fw != std::string::npos) {
Tensor q, k, v;
std::tie(q, k, v) = split_qkv_tensor(tensor, fetch_data(tensor, params));
for (int i = 0; i < 3; i++) {
Tensor attn_t = i == 0 ? q : (i == 1 ? k : v);
attn_t.name = tensor.name.substr(0, fw) + kqv_self[i];
dst.push_back(attn_t);
if (params.verbose) {
printf("split %s => %s\n", it.first.c_str(), attn_t.name.c_str());
}
}
continue;
} else if (fb != std::string::npos) {
Tensor q, k, v;
std::tie(q, k, v) = split_qkv_tensor(tensor, fetch_data(tensor, params));
for (int i = 0; i < 3; i++) {
Tensor attn_t = i == 0 ? q : (i == 1 ? k : v);
attn_t.name = tensor.name.substr(0, fb) + kqv_self[i + 3];
dst.push_back(attn_t);
if (params.verbose) {
printf("split %s => %s\n", it.first.c_str(), attn_t.name.c_str());
}
}
continue;
}
}
} else if (tensor.target == UNET) {
tensor.name = convert_unet_to_original(tensor.name, params);
if (tensor.name.find("proj_in.weight") != std::string::npos ||
tensor.name.find("proj_out.weight") != std::string::npos) {
if (tensor.n_dims == 2) {
tensor.n_dims += 2;
if (params.verbose) {
printf("linear to conv2d %s\n", tensor.name.c_str());
}
}
}
}
if (params.lora) {
tensor.name = fix_lora_names(tensor.name);
}
if (is_unused_tensor(tensor.name)) { // discard tensors
continue;
}
if (params.lora) {
int pos = (int)name.find("lora.up.weight");
if (pos != std::string::npos) {
std::string key = name.substr(0, pos) + "alpha";
if (params.lora_alphas.find(key) != params.lora_alphas.end()) {
int kpos = (int)tensor.name.find("lora_up");
std::string target = tensor.name.substr(0, kpos) + "alpha";
params.alpha_keys.emplace(target);
params.alpha_values.push_back(params.lora_alphas[key]);
} else {
printf("WARNING: missing alpha '%s'\n", key.c_str());
}
}
}
dst.push_back(tensor);
}
if (params.lora) {
params.lora_alphas.clear();