forked from leejet/stable-diffusion.cpp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodel.cpp
More file actions
3020 lines (2715 loc) · 116 KB
/
model.cpp
File metadata and controls
3020 lines (2715 loc) · 116 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 <array>
#include <atomic>
#include <chrono>
#include <cctype>
#include <cmath>
#include <cstdarg>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <functional>
#include <mutex>
#include <regex>
#include <set>
#include <string>
#include <thread>
#include <unordered_map>
#include <vector>
#include "gguf_reader.hpp"
#include "model.h"
#include "stable-diffusion.h"
#include "util.h"
#include "vocab.hpp"
#include "vocab_mistral.hpp"
#include "vocab_qwen.hpp"
#include "vocab_umt5.hpp"
#include "ggml-alloc.h"
#include "ggml-backend.h"
#include "ggml-cpu.h"
#include "ggml.h"
#include "name_conversion.h"
#include "stable-diffusion.h"
#ifdef SD_USE_METAL
#include "ggml-metal.h"
#endif
#ifdef SD_USE_VULKAN
#include "ggml-vulkan.h"
#endif
#ifdef SD_USE_OPENCL
#include "ggml-opencl.h"
#endif
#define ST_HEADER_SIZE_LEN 8
uint64_t read_u64(uint8_t* buffer) {
// little endian
uint64_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;
}
/*================================================= Preprocess ==================================================*/
const char* 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.1.model.text_model.embeddings.position_ids",
"cond_stage_model.transformer.vision_model.embeddings.position_ids",
"cond_stage_model.model.logit_scale",
"conditioner.embedders.0.transformer.text_model.embeddings.position_ids",
"conditioner.embedders.0.model.logit_scale",
"conditioner.embedders.1.model.logit_scale",
"model.diffusion_model.time_embedding.cond_proj.weight",
"unet.time_embedding.cond_proj.weight",
"model_ema.decay",
"model_ema.num_updates",
"model_ema.diffusion_model",
"embedding_manager",
"denoiser.sigmas",
"text_encoders.t5xxl.transformer.encoder.embed_tokens.weight", // only used during training
"ztsnr", // Found in some SDXL vpred models
"edm_vpred.sigma_min", // Found in CosXL
// TODO: find another way to avoid the "unknown tensor" for these two
// "edm_vpred.sigma_max", // Used to detect CosXL
// "v_pred", // Used to detect SDXL vpred models
"text_encoders.llm.output.weight",
"text_encoders.llm.lm_head.",
"first_stage_model.bn.",
};
bool is_unused_tensor(std::string name) {
for (size_t i = 0; i < sizeof(unused_tensors) / sizeof(const char*); i++) {
if (starts_with(name, unused_tensors[i])) {
return true;
}
}
return false;
}
uint16_t f8_e4m3_to_f16(uint8_t f8) {
// do we need to support uz?
const uint32_t exponent_bias = 7;
if (f8 == 0xff) {
return ggml_fp32_to_fp16(-NAN);
} else if (f8 == 0x7f) {
return ggml_fp32_to_fp16(NAN);
}
uint32_t sign = f8 & 0x80;
uint32_t exponent = (f8 & 0x78) >> 3;
uint32_t mantissa = f8 & 0x07;
uint32_t result = sign << 24;
if (exponent == 0) {
if (mantissa > 0) {
exponent = 0x7f - exponent_bias;
// yes, 2 times
if ((mantissa & 0x04) == 0) {
mantissa &= 0x03;
mantissa <<= 1;
exponent -= 1;
}
if ((mantissa & 0x04) == 0) {
mantissa &= 0x03;
mantissa <<= 1;
exponent -= 1;
}
result |= (mantissa & 0x03) << 21;
result |= exponent << 23;
}
} else {
result |= mantissa << 20;
exponent += 0x7f - exponent_bias;
result |= exponent << 23;
}
return ggml_fp32_to_fp16(*reinterpret_cast<const float*>(&result));
}
uint16_t f8_e5m2_to_f16(uint8_t fp8) {
uint8_t sign = (fp8 >> 7) & 0x1;
uint8_t exponent = (fp8 >> 2) & 0x1F;
uint8_t mantissa = fp8 & 0x3;
uint16_t fp16_sign = sign << 15;
uint16_t fp16_exponent;
uint16_t fp16_mantissa;
if (exponent == 0 && mantissa == 0) { // zero
return fp16_sign;
}
if (exponent == 0x1F) { // NAN and INF
fp16_exponent = 0x1F;
fp16_mantissa = mantissa ? (mantissa << 8) : 0;
return fp16_sign | (fp16_exponent << 10) | fp16_mantissa;
}
if (exponent == 0) { // subnormal numbers
fp16_mantissa = (mantissa << 8);
return fp16_sign | fp16_mantissa;
}
// normal numbers
int16_t true_exponent = (int16_t)exponent - 15 + 15;
if (true_exponent <= 0) {
fp16_exponent = 0;
fp16_mantissa = (mantissa << 8);
} else if (true_exponent >= 0x1F) {
fp16_exponent = 0x1F;
fp16_mantissa = 0;
} else {
fp16_exponent = (uint16_t)true_exponent;
fp16_mantissa = mantissa << 8;
}
return fp16_sign | (fp16_exponent << 10) | fp16_mantissa;
}
void f8_e4m3_to_f16_vec(uint8_t* src, uint16_t* dst, int64_t n) {
// support inplace op
for (int64_t i = n - 1; i >= 0; i--) {
dst[i] = f8_e4m3_to_f16(src[i]);
}
}
void f8_e5m2_to_f16_vec(uint8_t* src, uint16_t* dst, int64_t n) {
// support inplace op
for (int64_t i = n - 1; i >= 0; i--) {
dst[i] = f8_e5m2_to_f16(src[i]);
}
}
void f64_to_f32_vec(double* src, float* dst, int64_t n) {
// support inplace op
for (int64_t i = 0; i < n; i++) {
dst[i] = (float)src[i];
}
}
void i64_to_i32_vec(int64_t* src, int32_t* dst, int64_t n) {
// support inplace op
for (int64_t i = 0; i < n; i++) {
dst[i] = (int32_t)src[i];
}
}
static inline size_t sd_hmx_wf8_permuted_weight_index(int k, int i, int j) {
const int kt = k / 32;
const int i0 = i / 32;
const int i1 = i % 32;
const int j0 = j / 32;
const int j1 = j % 32;
const size_t tile_idx = (size_t)j0 * (size_t)kt + (size_t)i0;
static const uint8_t lane_perm[4] = {0, 2, 1, 3};
const size_t tile_row = (size_t)(i1 / 4) * 4 + (size_t)(j1 / 8);
const size_t tile_col = (size_t)(j1 % 8) * 4 + (size_t)lane_perm[i1 % 4];
return tile_idx * 1024 + tile_row * 32 + tile_col;
}
static float sd_decode_fp8_e4m3fn_export(uint8_t code) {
const int sign = (code & 0x80) ? -1 : 1;
const int exp = (code >> 3) & 0x0f;
const int mant = code & 0x07;
if (exp == 0x0f && mant == 0x07) {
return 0.0f;
}
if (exp == 0) {
if (mant == 0) {
return 0.0f;
}
return sign * std::ldexp((float) mant, -9);
}
return sign * std::ldexp(1.0f + (float) mant / 8.0f, exp - 7);
}
struct sd_wf8_export_code_value {
float value;
uint8_t code;
};
static const std::array<sd_wf8_export_code_value, 254>& sd_wf8_export_sorted_codebook() {
static const std::array<sd_wf8_export_code_value, 254> table = []() {
std::array<sd_wf8_export_code_value, 254> out{};
size_t idx = 0;
for (int code = 0; code < 256; ++code) {
if (((code >> 3) & 0x0f) == 0x0f && (code & 0x07) == 0x07) {
continue;
}
if (code == 0x80) {
continue;
}
out[idx++] = { sd_decode_fp8_e4m3fn_export((uint8_t) code), (uint8_t) code };
}
std::sort(out.begin(), out.end(), [](const sd_wf8_export_code_value& a, const sd_wf8_export_code_value& b) {
if (a.value != b.value) {
return a.value < b.value;
}
return a.code < b.code;
});
return out;
}();
return table;
}
static uint8_t sd_encode_fp8_e4m3fn_best_export(float x) {
x *= 256.0f;
if (x == 0.0f) {
return 0x00;
}
const auto& table = sd_wf8_export_sorted_codebook();
auto it = std::lower_bound(
table.begin(), table.end(), x,
[](const sd_wf8_export_code_value& e, float v) {
return e.value < v;
});
const sd_wf8_export_code_value* best = nullptr;
auto consider = [&](const sd_wf8_export_code_value* cand) {
if (cand == nullptr) {
return;
}
if (best == nullptr) {
best = cand;
return;
}
const float cand_err = std::fabs(cand->value - x);
const float best_err = std::fabs(best->value - x);
if (cand_err < best_err || (cand_err == best_err && cand->code < best->code)) {
best = cand;
}
};
if (it != table.end()) {
consider(&(*it));
const float v = it->value;
for (auto jt = it + 1; jt != table.end() && jt->value == v; ++jt) {
consider(&(*jt));
}
}
if (it != table.begin()) {
auto jt = it;
do {
--jt;
consider(&(*jt));
} while (jt != table.begin() && jt->value == (jt - 1)->value);
}
return best ? best->code : 0;
}
static uint8_t sd_encode_fp8_e4m3fn_best_export_f16(ggml_fp16_t h) {
static const std::array<uint8_t, 65536> lut = []() {
std::array<uint8_t, 65536> out{};
for (uint32_t i = 0; i < out.size(); ++i) {
const ggml_fp16_t hval = (ggml_fp16_t) i;
out[i] = sd_encode_fp8_e4m3fn_best_export(ggml_fp16_to_fp32(hval));
}
return out;
}();
return lut[(uint16_t) h];
}
template<typename SrcT, typename EncodeFn>
static void sd_pack_compact_wf8_weight_from_ggml_tensor_layout_impl(
uint8_t * dst,
const SrcT * src,
int k,
int n,
int nthread,
EncodeFn encode_fn) {
std::memset(dst, 0, (size_t) k * (size_t) n);
const int nthread_use = std::max(1, std::min(nthread, n));
if (nthread_use == 1) {
for (int j = 0; j < n; ++j) {
const size_t row_off = (size_t) j * (size_t) k;
for (int i = 0; i < k; ++i) {
dst[sd_hmx_wf8_permuted_weight_index(k, i, j)] = encode_fn(src[row_off + (size_t) i]);
}
}
return;
}
std::vector<std::thread> threads;
threads.reserve((size_t) nthread_use);
for (int tid = 0; tid < nthread_use; ++tid) {
const int j0 = (n * tid) / nthread_use;
const int j1 = (n * (tid + 1)) / nthread_use;
threads.emplace_back([=]() {
for (int j = j0; j < j1; ++j) {
const size_t row_off = (size_t) j * (size_t) k;
for (int i = 0; i < k; ++i) {
dst[sd_hmx_wf8_permuted_weight_index(k, i, j)] = encode_fn(src[row_off + (size_t) i]);
}
}
});
}
for (auto& t : threads) {
t.join();
}
}
static void sd_pack_compact_wf8_weight_from_ggml_tensor_layout(
uint8_t * dst,
const float * src,
int k,
int n,
int nthread) {
sd_pack_compact_wf8_weight_from_ggml_tensor_layout_impl(
dst, src, k, n, nthread,
[](float x) { return sd_encode_fp8_e4m3fn_best_export(x); });
}
static void sd_pack_compact_wf8_weight_from_f16_ggml_tensor_layout(
uint8_t * dst,
const ggml_fp16_t * src,
int k,
int n,
int nthread) {
sd_pack_compact_wf8_weight_from_ggml_tensor_layout_impl(
dst, src, k, n, nthread,
[](ggml_fp16_t x) { return sd_encode_fp8_e4m3fn_best_export_f16(x); });
}
template<typename DstT, typename StoreFn>
static void sd_unpack_compact_wf8_weight_to_ggml_tensor_layout_impl(
DstT * dst,
const uint8_t * src,
int k,
int n,
StoreFn store_fn) {
for (int j = 0; j < n; ++j) {
const size_t row_off = (size_t) j * (size_t) k;
for (int i = 0; i < k; ++i) {
const float v = sd_decode_fp8_e4m3fn_export(src[sd_hmx_wf8_permuted_weight_index(k, i, j)]) / 256.0f;
dst[row_off + (size_t) i] = store_fn(v);
}
}
}
static void sd_unpack_compact_wf8_weight_to_f16_ggml_tensor_layout(
ggml_fp16_t * dst,
const uint8_t * src,
int k,
int n) {
sd_unpack_compact_wf8_weight_to_ggml_tensor_layout_impl(
dst, src, k, n,
[](float v) { return ggml_fp32_to_fp16(v); });
}
static void sd_unpack_compact_wf8_weight_to_f32_ggml_tensor_layout(
float * dst,
const uint8_t * src,
int k,
int n) {
sd_unpack_compact_wf8_weight_to_ggml_tensor_layout_impl(
dst, src, k, n,
[](float v) { return v; });
}
void convert_tensor(void* src,
ggml_type src_type,
void* dst,
ggml_type dst_type,
int nrows,
int n_per_row) {
int n = nrows * n_per_row;
if (src_type == dst_type) {
size_t nbytes = n * ggml_type_size(src_type) / ggml_blck_size(src_type);
memcpy(((char*)dst), ((char*)src), nbytes);
} else if (src_type == GGML_TYPE_WF8_HMX_PREPACK && dst_type == GGML_TYPE_F16) {
sd_unpack_compact_wf8_weight_to_f16_ggml_tensor_layout(
(ggml_fp16_t *) dst, (const uint8_t *) src, n_per_row, nrows);
} else if (src_type == GGML_TYPE_WF8_HMX_PREPACK && dst_type == GGML_TYPE_F32) {
sd_unpack_compact_wf8_weight_to_f32_ggml_tensor_layout(
(float *) dst, (const uint8_t *) src, n_per_row, nrows);
} else if (dst_type == GGML_TYPE_WF8_HMX_PREPACK) {
if (src_type == GGML_TYPE_F32) {
sd_pack_compact_wf8_weight_from_ggml_tensor_layout((uint8_t*) dst, (const float*) src, n_per_row, nrows,
sd_get_num_physical_cores());
} else if (src_type == GGML_TYPE_F16) {
sd_pack_compact_wf8_weight_from_f16_ggml_tensor_layout((uint8_t*) dst, (const ggml_fp16_t*) src, n_per_row, nrows,
sd_get_num_physical_cores());
} else {
auto qtype = ggml_get_type_traits(src_type);
if (qtype->to_float == nullptr) {
throw std::runtime_error(sd_format("type %s unsupported for WF8_HMX_PREPACK conversion",
ggml_type_name(src_type)));
}
std::vector<float> src_data_f32(n);
qtype->to_float(src, src_data_f32.data(), n);
sd_pack_compact_wf8_weight_from_ggml_tensor_layout((uint8_t*) dst, src_data_f32.data(), n_per_row, nrows,
sd_get_num_physical_cores());
}
} else if (src_type == GGML_TYPE_F32) {
if (dst_type == GGML_TYPE_F16) {
ggml_fp32_to_fp16_row((float*)src, (ggml_fp16_t*)dst, n);
} else {
std::vector<float> imatrix(n_per_row, 1.0f); // dummy importance matrix
const float* im = imatrix.data();
ggml_quantize_chunk(dst_type, (float*)src, dst, 0, nrows, n_per_row, im);
}
} else if (dst_type == GGML_TYPE_F32) {
if (src_type == GGML_TYPE_F16) {
ggml_fp16_to_fp32_row((ggml_fp16_t*)src, (float*)dst, n);
} else {
auto qtype = ggml_get_type_traits(src_type);
if (qtype->to_float == nullptr) {
throw std::runtime_error(sd_format("type %s unsupported for integer quantization: no dequantization available",
ggml_type_name(src_type)));
}
qtype->to_float(src, (float*)dst, n);
}
} else {
// src_type == GGML_TYPE_F16 => dst_type is quantized
// src_type is quantized => dst_type == GGML_TYPE_F16 or dst_type is quantized
auto qtype = ggml_get_type_traits(src_type);
if (qtype->to_float == nullptr) {
throw std::runtime_error(sd_format("type %s unsupported for integer quantization: no dequantization available",
ggml_type_name(src_type)));
}
std::vector<char> buf;
buf.resize(sizeof(float) * n);
char* src_data_f32 = buf.data();
qtype->to_float(src, (float*)src_data_f32, n);
if (dst_type == GGML_TYPE_F16) {
ggml_fp32_to_fp16_row((float*)src_data_f32, (ggml_fp16_t*)dst, n);
} else {
std::vector<float> imatrix(n_per_row, 1.0f); // dummy importance matrix
const float* im = imatrix.data();
ggml_quantize_chunk(dst_type, (float*)src_data_f32, dst, 0, nrows, n_per_row, im);
}
}
}
static bool sd_convert_htp_permute_enabled() {
static int enabled = -1;
if (enabled < 0) {
const char* env = getenv("SD_GGUF_CONVERT_HTP_PERMUTE");
enabled = (env != nullptr && env[0] != '\0' && strcmp(env, "0") != 0) ? 1 : 0;
}
return enabled != 0;
}
// Inverse of the HMX 32x32 weight layout permute, used to build host-side CPU
// references from a permuted+repacked GGUF. Mutually exclusive with PERMUTE.
static bool sd_convert_htp_invpermute_enabled() {
static int enabled = -1;
if (enabled < 0) {
const char* env = getenv("SD_GGUF_CONVERT_HTP_INVPERMUTE");
enabled = (env != nullptr && env[0] != '\0' && strcmp(env, "0") != 0) ? 1 : 0;
}
return enabled != 0;
}
static bool sd_convert_htp_permute_core_only() {
static int enabled = -1;
if (enabled < 0) {
const char* env = getenv("SD_GGUF_CONVERT_HTP_PERMUTE_CORE_ONLY");
enabled = (env != nullptr && env[0] != '\0' && strcmp(env, "0") != 0) ? 1 : 0;
}
return enabled != 0;
}
static bool sd_convert_htp_permute_log_enabled() {
static int enabled = -1;
if (enabled < 0) {
const char* env = getenv("SD_GGUF_CONVERT_HTP_PERMUTE_LOG");
enabled = (env != nullptr && env[0] != '\0' && strcmp(env, "0") != 0) ? 1 : 0;
}
return enabled != 0;
}
static std::atomic<int>& sd_convert_htp_permute_count() {
static std::atomic<int> count(0);
return count;
}
static bool sd_convert_htp_repack_enabled() {
static int enabled = -1;
if (enabled < 0) {
const char* env = getenv("SD_GGUF_CONVERT_HTP_REPACK");
enabled = (env != nullptr && env[0] != '\0' && strcmp(env, "0") != 0) ? 1 : 0;
}
return enabled != 0;
}
// When enabled, only weights that were permuted in this conversion run will be
// repacked into the HMX packed-quant layout. This keeps small CPU-only matmuls
// (e.g. cap_embed / adaLN) compatible with vanilla ggml execution.
static bool sd_convert_htp_repack_only_permuted() {
static int enabled = -1;
if (enabled < 0) {
const char* env = getenv("SD_GGUF_CONVERT_HTP_REPACK_ONLY_PERMUTED");
if (env != nullptr && env[0] != '\0') {
enabled = (strcmp(env, "0") != 0) ? 1 : 0;
} else {
const char* overlay = getenv("SD_DIFFUSION_MODEL_OVERLAY");
// Overlay convert starts from an already packed baseline GGUF and replaces
// only a subset of tensors from the source model. Repacking untouched
// baseline qweights again corrupts their on-disk layout, so in overlay mode
// only tensors permuted in this conversion pass may be repacked.
enabled = (overlay != nullptr && overlay[0] != '\0') ? 1 : 0;
}
}
return enabled != 0;
}
// Optional override for the GGUF metadata flag sd.npu.contract.export.repack.
// This can be used to keep CPU fallback in vanilla mode even if we repack a
// subset of weights for the HMX fast-path.
static bool sd_convert_htp_repack_metadata_enabled() {
static int enabled = -1;
if (enabled < 0) {
const char* env = getenv("SD_GGUF_CONVERT_HTP_REPACK_META");
if (env != nullptr && env[0] != '\0') {
enabled = (strcmp(env, "0") != 0 && strcmp(env, "false") != 0) ? 1 : 0;
} else {
enabled = sd_convert_htp_repack_enabled() ? 1 : 0;
}
}
return enabled != 0;
}
static std::atomic<int>& sd_convert_htp_repack_count() {
static std::atomic<int> count(0);
return count;
}
static std::vector<std::string> sd_parse_csv_env(const char* name) {
std::vector<std::string> out;
const char* env = getenv(name);
if (env == nullptr || env[0] == '\0') {
return out;
}
std::string s(env);
size_t start = 0;
while (start < s.size()) {
size_t end = s.find(',', start);
if (end == std::string::npos) {
end = s.size();
}
size_t b = start;
while (b < end && std::isspace((unsigned char)s[b])) {
++b;
}
size_t e = end;
while (e > b && std::isspace((unsigned char)s[e - 1])) {
--e;
}
if (e > b) {
out.emplace_back(s.substr(b, e - b));
}
start = end + 1;
}
return out;
}
static bool sd_name_match_any(const std::string& name, const std::vector<std::string>& keys) {
for (const auto& k : keys) {
if (!k.empty() && name.find(k) != std::string::npos) {
return true;
}
}
return false;
}
static bool sd_convert_htp_permute_name_allowed(const std::string& name) {
static std::vector<std::string> include = sd_parse_csv_env("SD_GGUF_CONVERT_HTP_PERMUTE_INCLUDE");
static std::vector<std::string> exclude = sd_parse_csv_env("SD_GGUF_CONVERT_HTP_PERMUTE_EXCLUDE");
if (!include.empty() && !sd_name_match_any(name, include)) {
return false;
}
if (!exclude.empty() && sd_name_match_any(name, exclude)) {
return false;
}
return true;
}
static bool sd_convert_should_hmx_permute(const TensorStorage& tensor_storage, const ggml_tensor* dst_tensor) {
const bool do_perm = sd_convert_htp_permute_enabled();
const bool do_inv = sd_convert_htp_invpermute_enabled();
if (do_perm && do_inv) {
LOG_ERROR("SD_GGUF_CONVERT_HTP_PERMUTE and SD_GGUF_CONVERT_HTP_INVPERMUTE are both enabled; pick one");
return false;
}
if (!do_perm && !do_inv) {
return false;
}
if (dst_tensor == nullptr) {
return false;
}
const bool supported_dst_type =
ggml_is_quantized(dst_tensor->type) ||
dst_tensor->type == GGML_TYPE_F16 ||
dst_tensor->type == GGML_TYPE_BF16 ||
dst_tensor->type == GGML_TYPE_F32;
if (!supported_dst_type) {
return false;
}
if (tensor_storage.n_dims != 2) {
return false;
}
const int64_t k = tensor_storage.ne[0];
const int64_t n = tensor_storage.ne[1];
if ((n % 32) != 0) {
return false;
}
if (do_inv) {
// For INVPERMUTE, only handle quantized weights. In our diffusion exports, fp16 tensors are
// kept in vanilla basis (CPU-friendly) and should not be unpermuted.
if (!ggml_is_quantized(tensor_storage.type)) {
return false;
}
if ((k % 256) != 0) {
return false;
}
} else {
// Match HTP matmul constraints for the target weight dtype:
// - Quant (q4/q8/iq4): k % 256 == 0, n % 32 == 0
// - F16 weight matmul: k % 32 == 0, n % 32 == 0
if (ggml_is_quantized(dst_tensor->type)) {
if ((k % 256) != 0) {
return false;
}
} else if (dst_tensor->type == GGML_TYPE_F16) {
if ((k % 32) != 0) {
return false;
}
} else {
// NOTE: HTP offload currently consumes permuted weights for quant/f16 matmul only.
// Keep other dtypes conservative to avoid breaking CPU fallback correctness.
return false;
}
}
if (ends_with(tensor_storage.name, ".bias") || ends_with(tensor_storage.name, ".scale")) {
return false;
}
if (sd_convert_htp_permute_core_only()) {
const std::string& name = tensor_storage.name;
const bool core_linear =
ends_with(name, ".attention.qkv.weight") ||
ends_with(name, ".attention.out.weight") ||
ends_with(name, ".feed_forward.w1.weight") ||
ends_with(name, ".feed_forward.w2.weight") ||
ends_with(name, ".feed_forward.w3.weight");
if (!core_linear) {
return false;
}
}
if (!sd_convert_htp_permute_name_allowed(tensor_storage.name)) {
return false;
}
return true;
}
static void sd_hmx_permute_linear_weight_f32(const float* src, float* dst, int n, int k) {
const int n_chunks = n / 32;
const int k_chunks = k / 32;
const int k_stride = k_chunks * 32;
for (int r = 0; r < n; ++r) {
const int64_t row_base = (int64_t)r * k_stride;
for (int c = 0; c < k_stride; ++c) {
int64_t t = row_base + c;
int u = (int)(t & 1);
t >>= 1;
int i = (int)(t & 31);
t >>= 5;
int g = (int)(t & 15);
t >>= 4;
int b = (int)(t % k_chunks);
int a = (int)(t / k_chunks);
if (a < 0 || a >= n_chunks) {
continue;
}
int src_row = a * 32 + i;
int src_col = b * 32 + g * 2 + u;
dst[row_base + c] = src[(int64_t)src_row * k + src_col];
}
}
}
// Inverse mapping of sd_hmx_permute_linear_weight_f32():
// - src: permuted basis (as stored for HMX matmul)
// - dst: vanilla basis (row-major [n,k])
static void sd_hmx_invpermute_linear_weight_f32(const float* src, float* dst, int n, int k) {
const int n_chunks = n / 32;
const int k_chunks = k / 32;
const int k_stride = k_chunks * 32;
for (int r = 0; r < n; ++r) {
const int64_t row_base = (int64_t)r * k_stride;
for (int c = 0; c < k_stride; ++c) {
int64_t t = row_base + c;
int u = (int)(t & 1);
t >>= 1;
int i = (int)(t & 31);
t >>= 5;
int g = (int)(t & 15);
t >>= 4;
int b = (int)(t % k_chunks);
int a = (int)(t / k_chunks);
if (a < 0 || a >= n_chunks) {
continue;
}
int src_row = a * 32 + i;
int src_col = b * 32 + g * 2 + u;
dst[(int64_t)src_row * k + src_col] = src[row_base + c];
}
}
}
struct sd_std_block_q4_like {
uint16_t d;
uint8_t qs[16];
} __attribute__((packed));
static_assert(sizeof(sd_std_block_q4_like) == 18, "unexpected q4-like block size");
struct sd_std_block_q8_0 {
uint16_t d;
int8_t qs[32];
} __attribute__((packed));
static_assert(sizeof(sd_std_block_q8_0) == 34, "unexpected q8_0 block size");
struct sd_my_block_q4_0_like {
uint16_t scales[8];
uint8_t quants[8 * 16];
} __attribute__((packed));
static_assert(sizeof(sd_my_block_q4_0_like) == 144, "unexpected packed q4-like super-block size");
struct sd_my_block_q8_0 {
uint16_t scales[8];
int8_t quants[8 * 32];
} __attribute__((packed));
static_assert(sizeof(sd_my_block_q8_0) == 272, "unexpected packed q8_0 super-block size");
static void sd_hmx_repack_row_q4_like_inplace(uint8_t* row, size_t n_super_blocks) {
for (size_t sb = 0; sb < n_super_blocks; ++sb) {
const size_t src_off = sb * 8 * sizeof(sd_std_block_q4_like);
const auto* src_ptr = reinterpret_cast<const sd_std_block_q4_like*>(row + src_off);
sd_std_block_q4_like src_blocks[8];
std::memcpy(src_blocks, src_ptr, sizeof(src_blocks));
sd_my_block_q4_0_like dst_block{};
uint8_t unpacked_qs[256];
for (size_t bi = 0; bi < 8; ++bi) {
dst_block.scales[bi] = src_blocks[bi].d;
for (size_t j = 0; j < sizeof(src_blocks[bi].qs); ++j) {
uint8_t q = src_blocks[bi].qs[j];
unpacked_qs[bi * 32 + j + 0] = q & 0x0F;
unpacked_qs[bi * 32 + j + 16] = q >> 4;
}
}
for (size_t j = 0; j < sizeof(dst_block.quants) / 2; ++j) {
dst_block.quants[j * 2 + 0] = (uint8_t)((unpacked_qs[j + 128] << 4) | unpacked_qs[j + 0]);
dst_block.quants[j * 2 + 1] = (uint8_t)((unpacked_qs[j + 192] << 4) | unpacked_qs[j + 64]);
}
const size_t dst_off = sb * sizeof(sd_my_block_q4_0_like);
std::memcpy(row + dst_off, &dst_block, sizeof(dst_block));
}
}
static void sd_hmx_unrepack_row_q4_like_inplace(uint8_t* row, size_t n_super_blocks) {
for (size_t sb = 0; sb < n_super_blocks; ++sb) {
const size_t src_off = sb * sizeof(sd_my_block_q4_0_like);
const auto* src_ptr = reinterpret_cast<const sd_my_block_q4_0_like*>(row + src_off);
sd_my_block_q4_0_like src_block{};
std::memcpy(&src_block, src_ptr, sizeof(src_block));
uint8_t unpacked_qs[256];
for (size_t j = 0; j < sizeof(src_block.quants) / 2; ++j) {
const uint8_t q0 = src_block.quants[j * 2 + 0];
const uint8_t q1 = src_block.quants[j * 2 + 1];
unpacked_qs[j + 0] = q0 & 0x0F;
unpacked_qs[j + 128] = q0 >> 4;
unpacked_qs[j + 64] = q1 & 0x0F;
unpacked_qs[j + 192] = q1 >> 4;
}
sd_std_block_q4_like dst_blocks[8];
for (size_t bi = 0; bi < 8; ++bi) {
dst_blocks[bi].d = src_block.scales[bi];
for (size_t j = 0; j < sizeof(dst_blocks[bi].qs); ++j) {
const uint8_t lo = unpacked_qs[bi * 32 + j + 0];
const uint8_t hi = unpacked_qs[bi * 32 + j + 16];
dst_blocks[bi].qs[j] = (uint8_t)((hi << 4) | lo);
}
}
const size_t dst_off = sb * 8 * sizeof(sd_std_block_q4_like);
std::memcpy(row + dst_off, dst_blocks, sizeof(dst_blocks));
}
}
static void sd_hmx_repack_row_q8_0_inplace(uint8_t* row, size_t n_super_blocks) {
for (size_t sb = 0; sb < n_super_blocks; ++sb) {
const size_t src_off = sb * 8 * sizeof(sd_std_block_q8_0);
const auto* src_ptr = reinterpret_cast<const sd_std_block_q8_0*>(row + src_off);
sd_std_block_q8_0 src_blocks[8];
std::memcpy(src_blocks, src_ptr, sizeof(src_blocks));
sd_my_block_q8_0 dst_block{};
for (size_t i = 0; i < 8; ++i) {
dst_block.scales[i] = src_blocks[i].d;
std::memcpy(dst_block.quants + i * sizeof(src_blocks[i].qs), src_blocks[i].qs, sizeof(src_blocks[i].qs));
}
const size_t dst_off = sb * sizeof(sd_my_block_q8_0);
std::memcpy(row + dst_off, &dst_block, sizeof(dst_block));
}
}
static void sd_hmx_unrepack_row_q8_0_inplace(uint8_t* row, size_t n_super_blocks) {
for (size_t sb = 0; sb < n_super_blocks; ++sb) {
const size_t src_off = sb * sizeof(sd_my_block_q8_0);
const auto* src_ptr = reinterpret_cast<const sd_my_block_q8_0*>(row + src_off);
sd_my_block_q8_0 src_block{};
std::memcpy(&src_block, src_ptr, sizeof(src_block));
sd_std_block_q8_0 dst_blocks[8];
for (size_t bi = 0; bi < 8; ++bi) {
dst_blocks[bi].d = src_block.scales[bi];
std::memcpy(dst_blocks[bi].qs,
src_block.quants + bi * sizeof(dst_blocks[bi].qs),
sizeof(dst_blocks[bi].qs));
}
const size_t dst_off = sb * 8 * sizeof(sd_std_block_q8_0);
std::memcpy(row + dst_off, dst_blocks, sizeof(dst_blocks));
}
}
static void sd_hmx_repack_quant_weight_inplace_if_needed(char* data, ggml_type type, int nrows, int n_per_row, const std::string& name) {
if (!sd_convert_htp_repack_enabled()) {
return;
}
const bool is_q4_like = type == GGML_TYPE_Q4_0 || type == GGML_TYPE_IQ4_NL;
const bool is_q8_0 = type == GGML_TYPE_Q8_0;
if (!is_q4_like && !is_q8_0) {
return;
}
if (n_per_row <= 0 || (n_per_row % 256) != 0) {
return;
}
const size_t n_super_blocks = (size_t)n_per_row / 256;
const size_t row_size = ggml_row_size(type, n_per_row);
const size_t expected_row_size =
is_q4_like ? n_super_blocks * sizeof(sd_my_block_q4_0_like) : n_super_blocks * sizeof(sd_my_block_q8_0);
if (row_size != expected_row_size) {
if (sd_convert_htp_permute_log_enabled()) {
LOG_WARN("hmx repack skip (row-size mismatch): %s type=%s row=%zu expect=%zu",
name.c_str(), ggml_type_name(type), row_size, expected_row_size);
}
return;
}
for (int r = 0; r < nrows; ++r) {
uint8_t* row = reinterpret_cast<uint8_t*>(data + (size_t)r * row_size);
if (is_q4_like) {
sd_hmx_repack_row_q4_like_inplace(row, n_super_blocks);
} else {
sd_hmx_repack_row_q8_0_inplace(row, n_super_blocks);
}
}
const int repack_id = sd_convert_htp_repack_count().fetch_add(1) + 1;
if (sd_convert_htp_permute_log_enabled() && repack_id <= 128) {
LOG_INFO("hmx repack #%d: %s type=%s shape=[%d,%d]", repack_id, name.c_str(), ggml_type_name(type), n_per_row, nrows);
}
}
static void sd_hmx_unrepack_quant_weight_inplace_if_needed(char* data, ggml_type type, int nrows, int n_per_row, const std::string& name) {
// Unrepack is only used in GGUF conversion when reading a mixed-layout model exported
// with "repack-only-permuted": permuted 2D weights are repacked for HMX fast-path,
// while 1D weights remain vanilla ggml layout for CPU correctness.
const bool is_q4_like = type == GGML_TYPE_Q4_0 || type == GGML_TYPE_IQ4_NL;
const bool is_q8_0 = type == GGML_TYPE_Q8_0;
if (!is_q4_like && !is_q8_0) {
return;
}
if (n_per_row <= 0 || (n_per_row % 256) != 0) {
return;
}
const size_t n_super_blocks = (size_t)n_per_row / 256;
const size_t row_size = ggml_row_size(type, n_per_row);
const size_t expected_row_size =
is_q4_like ? n_super_blocks * sizeof(sd_my_block_q4_0_like) : n_super_blocks * sizeof(sd_my_block_q8_0);
if (row_size != expected_row_size) {
if (sd_convert_htp_permute_log_enabled()) {
LOG_WARN("hmx unrepack skip (row-size mismatch): %s type=%s row=%zu expect=%zu",
name.c_str(), ggml_type_name(type), row_size, expected_row_size);
}
return;
}
for (int r = 0; r < nrows; ++r) {