forked from 0xShug0/audio.cpp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdecoder.cpp
More file actions
1718 lines (1629 loc) · 78.1 KB
/
Copy pathdecoder.cpp
File metadata and controls
1718 lines (1629 loc) · 78.1 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 "engine/models/muscriptor/decoder.h"
#include "engine/framework/core/backend.h"
#include "engine/framework/debug/profiler.h"
#include "engine/framework/modules/attention/scaled_dot_product_attention.h"
#include "engine/framework/modules/lookup_modules.h"
#include "engine/framework/modules/optimizations/fast_kv_modules.h"
#include "engine/framework/modules/primitive_modules.h"
#include "engine/framework/modules/structural_modules.h"
#include "engine/framework/modules/transformers/qwen_causal_decoder.h"
#include "engine/framework/sampling/hf_sampler.h"
#include <ggml-alloc.h>
#include <ggml-backend.h>
#include <ggml.h>
#include <algorithm>
#include <chrono>
#include <cmath>
#include <limits>
#include <memory>
#include <optional>
#include <random>
#include <stdexcept>
#include <string>
#include <utility>
namespace engine::models::muscriptor {
namespace {
namespace modules = engine::modules;
using Clock = std::chrono::steady_clock;
constexpr int64_t kGraphNodes = 262144;
constexpr int64_t kReservedVocabStart = 1393;
struct GgmlContextDeleter {
void operator()(ggml_context * ctx) const noexcept {
if (ctx != nullptr) {
ggml_free(ctx);
}
}
};
int64_t head_dim(const MuScriptorConfig & config) {
if (config.dim % config.num_heads != 0) {
throw std::runtime_error("MuScriptor hidden size must be divisible by attention heads");
}
return config.dim / config.num_heads;
}
int64_t decode_attention_bucket(int64_t required_steps, int64_t max_steps) {
if (required_steps <= 0 || max_steps <= 0 || required_steps > max_steps) {
throw std::runtime_error("MuScriptor decode attention bucket shape is invalid");
}
constexpr int64_t kMinBucket = 1024;
constexpr int64_t kBucketMultiple = 512;
const int64_t bucket = required_steps <= kMinBucket
? kMinBucket
: ((required_steps + kBucketMultiple - 1) / kBucketMultiple) * kBucketMultiple;
return std::min(bucket, max_steps);
}
assets::TensorStorageType supported_weight_storage(assets::TensorStorageType storage_type) {
if (storage_type == assets::TensorStorageType::Native ||
storage_type == assets::TensorStorageType::F32 ||
storage_type == assets::TensorStorageType::F16 ||
storage_type == assets::TensorStorageType::BF16 ||
storage_type == assets::TensorStorageType::Q8_0) {
return storage_type;
}
throw std::runtime_error("muscriptor.weight_type supports native, f32, f16, bf16, and q8_0");
}
std::vector<float> sinusoidal_position_embedding(int64_t steps, int64_t dim, int64_t offset = 0) {
if (steps <= 0 || dim <= 0 || dim % 2 != 0) {
throw std::runtime_error("MuScriptor positional embedding shape is invalid");
}
const int64_t half = dim / 2;
const double log_base = std::log(10000.0);
const double denom = static_cast<double>(half - 1);
std::vector<double> inv_freq(static_cast<size_t>(half), 0.0);
for (int64_t i = 0; i < half; ++i) {
inv_freq[static_cast<size_t>(i)] = std::exp(-log_base * static_cast<double>(i) / denom);
}
std::vector<float> values(static_cast<size_t>(steps * dim), 0.0F);
for (int64_t t = 0; t < steps; ++t) {
const double position = static_cast<double>(offset + t);
for (int64_t i = 0; i < half; ++i) {
const double phase = position * inv_freq[static_cast<size_t>(i)];
values[static_cast<size_t>(t * dim + i)] = static_cast<float>(std::cos(phase));
values[static_cast<size_t>(t * dim + half + i)] = static_cast<float>(std::sin(phase));
}
}
return values;
}
void fill_masked_logits(
std::vector<float> & out,
const float * logits,
int64_t logits_size,
const std::vector<uint8_t> & forbidden_mask) {
const int64_t vocab = std::min<int64_t>(kReservedVocabStart, logits_size);
out.resize(static_cast<size_t>(vocab));
std::copy_n(logits, static_cast<size_t>(vocab), out.begin());
const float neg_inf = -std::numeric_limits<float>::infinity();
for (size_t i = 0; i < out.size() && i < forbidden_mask.size(); ++i) {
if (forbidden_mask[i] != 0) {
out[i] = neg_inf;
}
}
}
void fill_guided_logits(
std::vector<float> & out,
const float * conditional,
const float * unconditional,
int64_t logits_size,
float guidance_scale,
const std::vector<uint8_t> & forbidden_mask) {
const int64_t vocab = std::min<int64_t>(kReservedVocabStart, logits_size);
out.resize(static_cast<size_t>(vocab));
const float neg_inf = -std::numeric_limits<float>::infinity();
for (int64_t i = 0; i < vocab; ++i) {
out[static_cast<size_t>(i)] = unconditional[static_cast<size_t>(i)] +
(conditional[static_cast<size_t>(i)] - unconditional[static_cast<size_t>(i)]) * guidance_scale;
}
for (size_t i = 0; i < out.size() && i < forbidden_mask.size(); ++i) {
if (forbidden_mask[i] != 0) {
out[i] = neg_inf;
}
}
}
void log_softmax_in_place(std::vector<float> & scores) {
float max_score = -std::numeric_limits<float>::infinity();
for (const float value : scores) {
if (value > max_score) {
max_score = value;
}
}
if (!std::isfinite(max_score)) {
throw std::runtime_error("MuScriptor beam search has no finite logits");
}
double sum = 0.0;
for (const float value : scores) {
if (std::isfinite(value)) {
sum += std::exp(static_cast<double>(value - max_score));
}
}
const float log_sum = static_cast<float>(std::log(sum));
for (float & value : scores) {
value = std::isfinite(value) ? value - max_score - log_sum : -std::numeric_limits<float>::infinity();
}
}
struct TokenScore {
int32_t token = 0;
float score = -std::numeric_limits<float>::infinity();
};
std::vector<TokenScore> top_k_scores(std::vector<float> scores, int64_t k) {
if (k <= 0 || scores.empty()) {
throw std::runtime_error("MuScriptor top-k requires a positive k");
}
log_softmax_in_place(scores);
std::vector<TokenScore> out;
out.reserve(static_cast<size_t>(std::min<int64_t>(k, static_cast<int64_t>(scores.size()))));
for (int64_t token = 0; token < static_cast<int64_t>(scores.size()); ++token) {
const float score = scores[static_cast<size_t>(token)];
if (!std::isfinite(score)) {
continue;
}
out.push_back({static_cast<int32_t>(token), score});
}
const auto keep = static_cast<size_t>(std::min<int64_t>(k, static_cast<int64_t>(out.size())));
if (keep == 0) {
throw std::runtime_error("MuScriptor top-k found no valid tokens");
}
std::partial_sort(
out.begin(),
out.begin() + static_cast<ptrdiff_t>(keep),
out.end(),
[](const TokenScore & lhs, const TokenScore & rhs) {
return lhs.score > rhs.score;
});
out.resize(keep);
return out;
}
core::TensorValue view_batched_kv_cache_steps(
core::ModuleBuildContext & ctx,
const core::TensorValue & cache,
int64_t start,
int64_t steps,
const MuScriptorConfig & config,
const char * label,
ggml_type view_type = GGML_TYPE_F32) {
const int64_t dim = head_dim(config);
if (cache.shape.rank != 4 ||
cache.shape.dims[1] < start + steps ||
cache.shape.dims[2] != config.num_heads ||
cache.shape.dims[3] != dim) {
throw std::runtime_error(std::string(label) + " batched KV cache view shape mismatch");
}
return core::wrap_tensor(
ggml_view_4d(
ctx.ggml,
cache.tensor,
dim,
config.num_heads,
steps,
cache.shape.dims[0],
cache.tensor->nb[1],
cache.tensor->nb[2],
cache.tensor->nb[3],
static_cast<size_t>(start) * cache.tensor->nb[2]),
core::TensorShape::from_dims({cache.shape.dims[0], steps, config.num_heads, dim}),
view_type);
}
class DecodeKVCache {
public:
DecodeKVCache() = default;
DecodeKVCache(
int64_t cache_steps,
int64_t step_elems,
std::vector<core::TensorValue> keys,
std::vector<core::TensorValue> values,
ggml_type storage_type)
: cache_steps_(cache_steps),
storage_type_(storage_type),
keys_(std::move(keys)),
values_(std::move(values)) {
if (cache_steps_ <= 0 || step_elems <= 0) {
throw std::runtime_error("MuScriptor decode KV cache requires positive shape");
}
if (keys_.size() != values_.size()) {
throw std::runtime_error("MuScriptor decode KV cache key/value layer count mismatch");
}
for (size_t layer = 0; layer < keys_.size(); ++layer) {
core::validate_shape(keys_[layer], values_[layer].shape, "muscriptor decode KV cache");
if (keys_[layer].type != storage_type_ || values_[layer].type != storage_type_) {
throw std::runtime_error("MuScriptor decode KV cache storage type mismatch");
}
}
}
void adopt_direct_prefix(int64_t steps) {
if (steps < 0 || steps > cache_steps_) {
throw std::runtime_error("MuScriptor decode KV cache direct prefix exceeds capacity");
}
valid_steps_ = steps;
current_end_ = steps;
}
void advance_after_direct_append(int64_t steps) {
if (steps <= 0) {
return;
}
if (valid_steps_ + steps > cache_steps_) {
throw std::runtime_error("MuScriptor decode KV cache direct append exceeds capacity");
}
valid_steps_ += steps;
current_end_ += steps;
}
int64_t valid_steps() const noexcept {
return valid_steps_;
}
int64_t current_end() const noexcept {
return current_end_;
}
const core::TensorValue & key_tensor(size_t layer) const {
return keys_.at(layer);
}
const core::TensorValue & value_tensor(size_t layer) const {
return values_.at(layer);
}
size_t layer_count() const noexcept {
return keys_.size();
}
private:
int64_t cache_steps_ = 0;
int64_t valid_steps_ = 0;
int64_t current_end_ = 0;
ggml_type storage_type_ = GGML_TYPE_F32;
std::vector<core::TensorValue> keys_;
std::vector<core::TensorValue> values_;
};
core::TensorValue build_transformer_layer(
core::ModuleBuildContext & ctx,
ggml_cgraph * graph,
const core::TensorValue & input,
const MuScriptorLayerWeights & weights,
const MuScriptorConfig & config,
std::optional<core::TensorValue> cache_key,
std::optional<core::TensorValue> cache_value,
std::optional<core::TensorValue> cache_slot,
std::optional<int64_t> attention_steps,
std::optional<core::TensorValue> attention_mask,
MuScriptorPerfMode perf_mode,
core::TensorValue * key_out,
core::TensorValue * value_out) {
const int64_t dim = head_dim(config);
const int64_t batch = input.shape.dims[0];
const int64_t steps = input.shape.dims[1];
auto x_norm = modules::LayerNormModule({config.dim, 1.0e-5F, true, true}).build(ctx, input, weights.norm1);
auto qkv = modules::LinearModule({config.dim, config.dim * 3, false}).build(ctx, x_norm, weights.in_proj);
auto q = modules::SliceModule({2, 0, config.dim}).build(ctx, qkv);
auto k = modules::SliceModule({2, config.dim, config.dim}).build(ctx, qkv);
auto v = modules::SliceModule({2, config.dim * 2, config.dim}).build(ctx, qkv);
q = core::ensure_backend_addressable_layout(ctx, q);
k = core::ensure_backend_addressable_layout(ctx, k);
v = core::ensure_backend_addressable_layout(ctx, v);
q = core::reshape_tensor(ctx, q, core::TensorShape::from_dims({batch, steps, config.num_heads, dim}));
k = core::reshape_tensor(ctx, k, core::TensorShape::from_dims({batch, steps, config.num_heads, dim}));
v = core::reshape_tensor(ctx, v, core::TensorShape::from_dims({batch, steps, config.num_heads, dim}));
core::TensorValue attn_k = k;
core::TensorValue attn_v = v;
if (cache_key.has_value() && cache_value.has_value()) {
if (!cache_slot.has_value()) {
throw std::runtime_error("MuScriptor cached decode requires cache_slot");
}
const modules::FastKVSetRowsModule set_rows({modules::FastKVSetRowsMode::BackendViewOptimized});
attn_k = set_rows.build(ctx, *cache_key, k, *cache_slot);
attn_v = set_rows.build(ctx, *cache_value, v, *cache_slot);
if (attention_steps.has_value()) {
if (*attention_steps <= 0 || *attention_steps > attn_k.shape.dims[1]) {
throw std::runtime_error("MuScriptor decode attention cache view shape is invalid");
}
attn_k = view_batched_kv_cache_steps(
ctx,
attn_k,
0,
*attention_steps,
config,
"MuScriptor decode key attention view",
attn_k.type);
attn_v = view_batched_kv_cache_steps(
ctx,
attn_v,
0,
*attention_steps,
config,
"MuScriptor decode value attention view",
attn_v.type);
}
}
if (key_out != nullptr) {
*key_out = attn_k;
}
if (value_out != nullptr) {
*value_out = attn_v;
}
auto q_heads = modules::TransposeModule({{0, 2, 1, 3}, q.shape.rank}).build(ctx, q);
q_heads = core::ensure_backend_addressable_layout(ctx, q_heads);
auto k_heads = modules::TransposeModule({{0, 2, 1, 3}, attn_k.shape.rank}).build(ctx, attn_k);
auto v_heads = modules::TransposeModule({{0, 2, 1, 3}, attn_v.shape.rank}).build(ctx, attn_v);
const bool prefill = !cache_key.has_value();
const bool use_flash_attention = perf_mode == MuScriptorPerfMode::FlashAttention && attention_mask.has_value();
auto context = modules::ScaledDotProductAttentionModule({
dim,
use_flash_attention
? modules::ScaledDotProductAttentionLowering::FlashPreserveViews
: modules::ScaledDotProductAttentionLowering::Explicit,
GGML_PREC_F32,
prefill ? modules::AttentionCausality::Causal : modules::AttentionCausality::NonCausal,
}).build(ctx, q_heads, k_heads, v_heads, attention_mask);
context = core::ensure_backend_addressable_layout(ctx, context);
context = core::reshape_tensor(ctx, context, core::TensorShape::from_dims({batch, steps, config.dim}));
auto attn = modules::LinearModule({config.dim, config.dim, false}).build(ctx, context, weights.out_proj);
auto x = modules::ResidualAddModule().build(ctx, attn, input);
auto ffn_norm = modules::LayerNormModule({config.dim, 1.0e-5F, true, true}).build(ctx, x, weights.norm2);
auto ffn = modules::FeedForwardModule({config.dim, config.dim * 4, false, modules::GeluApproximation::ExactErf})
.build(ctx, ffn_norm, weights.mlp);
if (graph != nullptr && cache_key.has_value()) {
ggml_build_forward_expand(graph, attn_k.tensor);
ggml_build_forward_expand(graph, attn_v.tensor);
}
return modules::ResidualAddModule().build(ctx, ffn, x);
}
MuScriptorWeights load_weights(
const MuScriptorAssets & assets,
core::ExecutionContext & execution,
const MuScriptorDecoderOptions & options) {
const auto & config = assets.config;
const auto & source = *assets.model_weights;
MuScriptorWeights weights;
weights.store = std::make_shared<core::BackendWeightStore>(
execution.backend(),
execution.backend_type(),
"muscriptor.weights",
options.weight_context_bytes);
const auto storage = supported_weight_storage(options.weight_type);
weights.mel_projection.weight = weights.store->load_tensor(
source,
"condition_provider.conditioners.self_wav.output_proj.weight",
storage,
{config.dim, config.n_mels});
weights.mel_projection.bias = weights.store->load_f32_tensor(
source,
"condition_provider.conditioners.self_wav.output_proj.bias",
{config.dim});
weights.instrument_embedding = weights.store->load_f32_tensor(
source,
"condition_provider.conditioners.instrument_group.embed.weight",
{1001, config.dim});
weights.dataset_embedding = weights.store->load_f32_tensor(
source,
"condition_provider.conditioners.dataset_name.embed.weight",
{5, config.dim});
weights.token_embedding = weights.store->load_f32_tensor(source, "emb.0.weight", {config.card + 1, config.dim});
weights.layers.reserve(static_cast<size_t>(config.num_layers));
for (int64_t layer = 0; layer < config.num_layers; ++layer) {
const std::string prefix = "transformer.layers." + std::to_string(layer) + ".";
MuScriptorLayerWeights layer_weights;
layer_weights.in_proj.weight = weights.store->load_tensor(
source,
prefix + "self_attn.in_proj_weight",
storage,
{config.dim * 3, config.dim});
layer_weights.out_proj.weight = weights.store->load_tensor(
source,
prefix + "self_attn.out_proj.weight",
storage,
{config.dim, config.dim});
layer_weights.norm1.weight = weights.store->load_f32_tensor(source, prefix + "norm1.weight", {config.dim});
layer_weights.norm1.bias = weights.store->load_f32_tensor(source, prefix + "norm1.bias", {config.dim});
layer_weights.norm2.weight = weights.store->load_f32_tensor(source, prefix + "norm2.weight", {config.dim});
layer_weights.norm2.bias = weights.store->load_f32_tensor(source, prefix + "norm2.bias", {config.dim});
layer_weights.mlp.fc1_weight = weights.store->load_tensor(source, prefix + "linear1.weight", storage, {config.dim * 4, config.dim});
layer_weights.mlp.fc2_weight = weights.store->load_tensor(source, prefix + "linear2.weight", storage, {config.dim, config.dim * 4});
weights.layers.push_back(std::move(layer_weights));
}
weights.output_norm.weight = weights.store->load_f32_tensor(source, "out_norm.weight", {config.dim});
weights.output_norm.bias = weights.store->load_f32_tensor(source, "out_norm.bias", {config.dim});
weights.output_head.weight = weights.store->load_tensor(source, "linears.0.weight", storage, {config.card, config.dim});
weights.store->upload();
return weights;
}
} // namespace
class MuScriptorDecodeCacheStorage {
public:
MuScriptorDecodeCacheStorage(
core::ExecutionContext & execution,
const MuScriptorConfig & config,
int64_t cache_steps,
int64_t batch,
bool enable_reorder_scratch,
ggml_type storage_type)
: execution_(execution),
cache_steps_(cache_steps),
batch_(batch),
reorder_scratch_enabled_(enable_reorder_scratch),
storage_type_(storage_type) {
const int64_t dim = head_dim(config);
ggml_init_params state_params{reorder_scratch_enabled_ ? 64ull * 1024ull * 1024ull : 4ull * 1024ull * 1024ull, nullptr, true};
state_ctx_.reset(ggml_init(state_params));
if (state_ctx_ == nullptr) {
throw std::runtime_error("failed to initialize MuScriptor decode state context");
}
core::ModuleBuildContext state_ctx{state_ctx_.get(), "muscriptor.decode.state", execution_.backend_type()};
std::vector<core::TensorValue> keys;
std::vector<core::TensorValue> values;
keys.reserve(static_cast<size_t>(config.num_layers));
values.reserve(static_cast<size_t>(config.num_layers));
for (int64_t layer = 0; layer < config.num_layers; ++layer) {
keys.push_back(core::make_tensor(
state_ctx,
storage_type_,
core::TensorShape::from_dims({batch_, cache_steps_, config.num_heads, dim})));
values.push_back(core::make_tensor(
state_ctx,
storage_type_,
core::TensorShape::from_dims({batch_, cache_steps_, config.num_heads, dim})));
}
if (reorder_scratch_enabled_) {
reorder_key_scratch_ = core::make_tensor(
state_ctx,
storage_type_,
core::TensorShape::from_dims({batch_, cache_steps_, config.num_heads, dim}));
reorder_value_scratch_ = core::make_tensor(
state_ctx,
storage_type_,
core::TensorShape::from_dims({batch_, cache_steps_, config.num_heads, dim}));
}
const auto state_alloc_start = Clock::now();
state_buffer_ = ggml_backend_alloc_ctx_tensors(state_ctx_.get(), execution_.backend());
if (state_buffer_ == nullptr) {
throw std::runtime_error("failed to allocate MuScriptor decode state tensors");
}
engine::debug::timing_log_scalar("muscriptor.decode.cache.state_alloc_ms", engine::debug::elapsed_ms(state_alloc_start, Clock::now()));
cache_ = DecodeKVCache(
cache_steps_,
batch_ * config.num_heads * dim,
std::move(keys),
std::move(values),
storage_type_);
if (reorder_scratch_enabled_) {
build_reorder_prefix_views(config);
}
}
~MuScriptorDecodeCacheStorage() {
if (state_buffer_ != nullptr) {
ggml_backend_buffer_free(state_buffer_);
}
}
bool matches(int64_t required_steps, int64_t batch, bool enable_reorder_scratch, ggml_type storage_type) const {
return cache_steps_ >= required_steps &&
batch_ == batch &&
reorder_scratch_enabled_ == enable_reorder_scratch &&
storage_type_ == storage_type;
}
void adopt_direct_prefix(int64_t steps) {
cache_.adopt_direct_prefix(steps);
}
void advance_after_direct_append(int64_t steps) {
cache_.advance_after_direct_append(steps);
}
int64_t cache_steps() const noexcept {
return cache_steps_;
}
int64_t batch() const noexcept {
return batch_;
}
int64_t valid_steps() const noexcept {
return cache_.valid_steps();
}
int64_t current_end() const noexcept {
return cache_.current_end();
}
const core::TensorValue & key_tensor(size_t layer) const {
return cache_.key_tensor(layer);
}
const core::TensorValue & value_tensor(size_t layer) const {
return cache_.value_tensor(layer);
}
size_t layer_count() const noexcept {
return cache_.layer_count();
}
void copy_batch_prefixes(
const std::vector<int64_t> & parent_rows,
const std::vector<int64_t> & child_rows,
int64_t valid_steps) {
const auto reorder_start = Clock::now();
++profile_reorder_calls_;
if (valid_steps <= 0) {
profile_reorder_ms_ += engine::debug::elapsed_ms(reorder_start, Clock::now());
return;
}
if (parent_rows.size() != child_rows.size() || static_cast<int64_t>(parent_rows.size()) > batch_) {
throw std::runtime_error("MuScriptor decode beam prefix copy shape mismatch");
}
changed_prefix_copies_.clear();
changed_prefix_copies_.reserve(parent_rows.size());
for (size_t i = 0; i < parent_rows.size(); ++i) {
const int64_t parent = parent_rows[i];
const int64_t child = child_rows[i];
if (parent < 0 || parent >= batch_ || child < 0 || child >= batch_) {
throw std::runtime_error("MuScriptor decode beam prefix copy row is out of range");
}
if (parent != child) {
changed_prefix_copies_.push_back({static_cast<size_t>(parent), static_cast<size_t>(child)});
}
}
if (changed_prefix_copies_.empty()) {
profile_reorder_ms_ += engine::debug::elapsed_ms(reorder_start, Clock::now());
return;
}
if (!reorder_scratch_enabled_) {
throw std::runtime_error("MuScriptor decode beam reorder scratch is not enabled");
}
++profile_reorder_changed_calls_;
profile_reorder_changed_rows_ += changed_prefix_copies_.size();
for (size_t layer = 0; layer < cache_.layer_count(); ++layer) {
for (size_t index = 0; index < changed_prefix_copies_.size(); ++index) {
const auto [parent, child] = changed_prefix_copies_[index];
(void)child;
ggml_backend_tensor_copy(
key_prefix_views_[parent][static_cast<size_t>(valid_steps)][layer],
scratch_key_prefix_views_[index][static_cast<size_t>(valid_steps)]);
ggml_backend_tensor_copy(
value_prefix_views_[parent][static_cast<size_t>(valid_steps)][layer],
scratch_value_prefix_views_[index][static_cast<size_t>(valid_steps)]);
}
for (size_t index = 0; index < changed_prefix_copies_.size(); ++index) {
const auto [parent, child] = changed_prefix_copies_[index];
(void)parent;
ggml_backend_tensor_copy(
scratch_key_prefix_views_[index][static_cast<size_t>(valid_steps)],
key_prefix_views_[child][static_cast<size_t>(valid_steps)][layer]);
ggml_backend_tensor_copy(
scratch_value_prefix_views_[index][static_cast<size_t>(valid_steps)],
value_prefix_views_[child][static_cast<size_t>(valid_steps)][layer]);
}
}
profile_reorder_ms_ += engine::debug::elapsed_ms(reorder_start, Clock::now());
}
void reset_reorder_profile() {
profile_reorder_ms_ = 0.0;
profile_reorder_calls_ = 0;
profile_reorder_changed_calls_ = 0;
profile_reorder_changed_rows_ = 0;
}
double reorder_ms() const noexcept {
return profile_reorder_ms_;
}
int64_t reorder_calls() const noexcept {
return profile_reorder_calls_;
}
int64_t reorder_changed_calls() const noexcept {
return profile_reorder_changed_calls_;
}
int64_t reorder_changed_rows() const noexcept {
return profile_reorder_changed_rows_;
}
private:
void build_reorder_prefix_views(const MuScriptorConfig & config) {
const int64_t dim = head_dim(config);
const int64_t step_elems = config.num_heads * dim;
key_prefix_views_.assign(static_cast<size_t>(batch_), {});
value_prefix_views_.assign(static_cast<size_t>(batch_), {});
scratch_key_prefix_views_.assign(static_cast<size_t>(batch_), {});
scratch_value_prefix_views_.assign(static_cast<size_t>(batch_), {});
const size_t element_size = ggml_type_size(storage_type_);
for (int64_t row = 0; row < batch_; ++row) {
auto & key_steps = key_prefix_views_[static_cast<size_t>(row)];
auto & value_steps = value_prefix_views_[static_cast<size_t>(row)];
key_steps.assign(static_cast<size_t>(cache_steps_ + 1), {});
value_steps.assign(static_cast<size_t>(cache_steps_ + 1), {});
auto & scratch_key_steps = scratch_key_prefix_views_[static_cast<size_t>(row)];
auto & scratch_value_steps = scratch_value_prefix_views_[static_cast<size_t>(row)];
scratch_key_steps.assign(static_cast<size_t>(cache_steps_ + 1), nullptr);
scratch_value_steps.assign(static_cast<size_t>(cache_steps_ + 1), nullptr);
const size_t byte_offset = static_cast<size_t>(row * cache_steps_ * step_elems) * element_size;
for (int64_t steps = 1; steps <= cache_steps_; ++steps) {
auto & key_layers = key_steps[static_cast<size_t>(steps)];
auto & value_layers = value_steps[static_cast<size_t>(steps)];
key_layers.reserve(cache_.layer_count());
value_layers.reserve(cache_.layer_count());
const int64_t elems = steps * step_elems;
for (size_t layer = 0; layer < cache_.layer_count(); ++layer) {
key_layers.push_back(ggml_view_1d(
state_ctx_.get(),
cache_.key_tensor(layer).tensor,
elems,
byte_offset));
value_layers.push_back(ggml_view_1d(
state_ctx_.get(),
cache_.value_tensor(layer).tensor,
elems,
byte_offset));
}
scratch_key_steps[static_cast<size_t>(steps)] =
ggml_view_1d(state_ctx_.get(), reorder_key_scratch_.tensor, elems, byte_offset);
scratch_value_steps[static_cast<size_t>(steps)] =
ggml_view_1d(state_ctx_.get(), reorder_value_scratch_.tensor, elems, byte_offset);
}
}
}
core::ExecutionContext & execution_;
int64_t cache_steps_ = 0;
int64_t batch_ = 1;
bool reorder_scratch_enabled_ = false;
ggml_type storage_type_ = GGML_TYPE_F32;
DecodeKVCache cache_;
core::TensorValue reorder_key_scratch_;
core::TensorValue reorder_value_scratch_;
std::vector<std::pair<size_t, size_t>> changed_prefix_copies_;
std::vector<std::vector<std::vector<ggml_tensor *>>> key_prefix_views_;
std::vector<std::vector<std::vector<ggml_tensor *>>> value_prefix_views_;
std::vector<std::vector<ggml_tensor *>> scratch_key_prefix_views_;
std::vector<std::vector<ggml_tensor *>> scratch_value_prefix_views_;
double profile_reorder_ms_ = 0.0;
int64_t profile_reorder_calls_ = 0;
int64_t profile_reorder_changed_calls_ = 0;
int64_t profile_reorder_changed_rows_ = 0;
std::unique_ptr<ggml_context, GgmlContextDeleter> state_ctx_;
ggml_backend_buffer_t state_buffer_ = nullptr;
};
class MuScriptorDecoderRuntime::ConditionGraph {
public:
ConditionGraph(
core::ExecutionContext & execution,
std::shared_ptr<MuScriptorWeights> weights,
const MuScriptorConfig & config,
int64_t frames,
int64_t instrument_steps,
int64_t batch,
size_t arena_bytes)
: execution_(execution),
weights_(std::move(weights)),
frames_(frames),
instrument_steps_(instrument_steps),
batch_(batch) {
const auto start = Clock::now();
ggml_init_params params{arena_bytes, nullptr, true};
ctx_.reset(ggml_init(params));
if (ctx_ == nullptr) {
throw std::runtime_error("failed to initialize MuScriptor condition graph context");
}
core::ModuleBuildContext ctx{ctx_.get(), "muscriptor.condition", execution_.backend_type()};
log_mel_ = ggml_new_tensor_3d(ctx_.get(), GGML_TYPE_F32, config.n_mels, frames_, batch_);
ggml_set_input(log_mel_);
mel_mask_ = ggml_new_tensor_2d(ctx_.get(), GGML_TYPE_I32, frames_, batch_);
ggml_set_input(mel_mask_);
instrument_ids_ = ggml_new_tensor_2d(ctx_.get(), GGML_TYPE_I32, instrument_steps_, batch_);
ggml_set_input(instrument_ids_);
dataset_id_ = ggml_new_tensor_1d(ctx_.get(), GGML_TYPE_I32, batch_);
ggml_set_input(dataset_id_);
auto mel = core::wrap_tensor(log_mel_, core::TensorShape::from_dims({batch_, frames_, config.n_mels}), GGML_TYPE_F32);
auto mel_embed = modules::LinearModule({config.n_mels, config.dim, true}).build(ctx, mel, weights_->mel_projection);
mel_embed = modules::MaskingModule().build(
ctx,
mel_embed,
core::wrap_tensor(mel_mask_, core::TensorShape::from_dims({batch_, frames_}), GGML_TYPE_I32));
auto instrument = modules::EmbeddingModule({1001, config.dim}).build(
ctx,
core::wrap_tensor(instrument_ids_, core::TensorShape::from_dims({batch_, instrument_steps_}), GGML_TYPE_I32),
weights_->instrument_embedding);
auto dataset = modules::EmbeddingModule({5, config.dim}).build(
ctx,
core::wrap_tensor(dataset_id_, core::TensorShape::from_dims({batch_}), GGML_TYPE_I32),
weights_->dataset_embedding);
dataset = core::reshape_tensor(ctx, dataset, core::TensorShape::from_dims({batch_, 1, config.dim}));
auto text = modules::ConcatModule({1}).build(ctx, mel_embed, dataset);
output_ = modules::ConcatModule({1}).build(ctx, text, instrument).tensor;
ggml_set_output(output_);
graph_ = ggml_new_graph_custom(ctx_.get(), kGraphNodes, false);
ggml_build_forward_expand(graph_, output_);
gallocr_ = ggml_gallocr_new(ggml_backend_get_default_buffer_type(execution_.backend()));
if (gallocr_ == nullptr || !ggml_gallocr_reserve(gallocr_, graph_) || !ggml_gallocr_alloc_graph(gallocr_, graph_)) {
throw std::runtime_error("failed to allocate MuScriptor condition graph");
}
engine::debug::timing_log_scalar("muscriptor.condition.graph.build_ms", engine::debug::elapsed_ms(start, Clock::now()));
}
~ConditionGraph() {
engine::core::release_backend_graph_resources(execution_.backend(), graph_);
if (gallocr_ != nullptr) {
ggml_gallocr_free(gallocr_);
}
}
bool matches(const MuScriptorWeights & weights, int64_t frames, int64_t instrument_steps, int64_t batch) const {
return weights_.get() == &weights && frames_ == frames && instrument_steps_ == instrument_steps && batch_ == batch;
}
MuScriptorConditioning run(
const std::vector<float> & log_mel,
const std::vector<int32_t> & mel_mask,
const std::vector<int32_t> & instrument_ids,
const std::vector<int32_t> & dataset_ids,
int64_t dim) {
if (static_cast<int64_t>(log_mel.size()) != batch_ * frames_ * weights_->mel_projection.weight.shape.dims[1]) {
throw std::runtime_error("MuScriptor condition log-mel size mismatch");
}
if (static_cast<int64_t>(mel_mask.size()) != batch_ * frames_) {
throw std::runtime_error("MuScriptor condition mask size mismatch");
}
if (static_cast<int64_t>(instrument_ids.size()) != batch_ * instrument_steps_) {
throw std::runtime_error("MuScriptor condition instrument id count mismatch");
}
if (static_cast<int64_t>(dataset_ids.size()) != batch_) {
throw std::runtime_error("MuScriptor condition dataset id count mismatch");
}
ggml_backend_tensor_set(log_mel_, log_mel.data(), 0, log_mel.size() * sizeof(float));
ggml_backend_tensor_set(mel_mask_, mel_mask.data(), 0, mel_mask.size() * sizeof(int32_t));
ggml_backend_tensor_set(instrument_ids_, instrument_ids.data(), 0, instrument_ids.size() * sizeof(int32_t));
ggml_backend_tensor_set(dataset_id_, dataset_ids.data(), 0, dataset_ids.size() * sizeof(int32_t));
core::set_backend_threads(execution_.backend(), execution_.config().threads);
const auto start = Clock::now();
const ggml_status status = engine::core::compute_backend_graph(execution_.backend(), graph_);
ggml_backend_synchronize(execution_.backend());
engine::debug::timing_log_scalar("muscriptor.condition.graph.compute_ms", engine::debug::elapsed_ms(start, Clock::now()));
if (status != GGML_STATUS_SUCCESS) {
throw std::runtime_error("MuScriptor condition graph compute failed");
}
MuScriptorConditioning out;
out.batch = batch_;
out.steps = frames_ + instrument_steps_ + 1;
out.dim = dim;
out.values.resize(static_cast<size_t>(out.batch * out.steps * dim));
const auto read_start = Clock::now();
ggml_backend_tensor_get(output_, out.values.data(), 0, out.values.size() * sizeof(float));
engine::debug::timing_log_scalar("muscriptor.condition.output_read_ms", engine::debug::elapsed_ms(read_start, Clock::now()));
return out;
}
private:
core::ExecutionContext & execution_;
std::shared_ptr<MuScriptorWeights> weights_;
int64_t frames_ = 0;
int64_t instrument_steps_ = 0;
int64_t batch_ = 1;
std::unique_ptr<ggml_context, GgmlContextDeleter> ctx_;
ggml_tensor * log_mel_ = nullptr;
ggml_tensor * mel_mask_ = nullptr;
ggml_tensor * instrument_ids_ = nullptr;
ggml_tensor * dataset_id_ = nullptr;
ggml_tensor * output_ = nullptr;
ggml_cgraph * graph_ = nullptr;
ggml_gallocr_t gallocr_ = nullptr;
};
class MuScriptorDecoderRuntime::PrefillGraph {
public:
struct Output {
std::vector<float> logits;
int64_t current_end = 0;
};
PrefillGraph(
core::ExecutionContext & execution,
std::shared_ptr<MuScriptorWeights> weights,
const MuScriptorConfig & config,
int64_t condition_steps,
int64_t token_steps,
int64_t batch,
const std::vector<core::TensorValue> & target_keys,
const std::vector<core::TensorValue> & target_values,
MuScriptorPerfMode perf_mode,
size_t arena_bytes)
: execution_(execution),
weights_(std::move(weights)),
condition_steps_(condition_steps),
token_steps_(token_steps),
total_steps_(condition_steps + token_steps),
batch_(batch),
target_key0_(target_keys.empty() ? nullptr : target_keys.front().tensor),
perf_mode_(perf_mode) {
const auto start = Clock::now();
if (target_keys.size() != weights_->layers.size() || target_values.size() != weights_->layers.size()) {
throw std::runtime_error("MuScriptor prefill target cache layer count mismatch");
}
ggml_init_params params{arena_bytes, nullptr, true};
ctx_.reset(ggml_init(params));
if (ctx_ == nullptr) {
throw std::runtime_error("failed to initialize MuScriptor prefill graph context");
}
ggml_init_params input_params{16ull * 1024ull * 1024ull, nullptr, true};
input_ctx_.reset(ggml_init(input_params));
if (input_ctx_ == nullptr) {
throw std::runtime_error("failed to initialize MuScriptor prefill input context");
}
core::ModuleBuildContext ctx{ctx_.get(), "muscriptor.prefill", execution_.backend_type()};
condition_ = ggml_new_tensor_3d(input_ctx_.get(), GGML_TYPE_F32, config.dim, condition_steps_, batch_);
ggml_set_input(condition_);
token_ids_ = ggml_new_tensor_2d(input_ctx_.get(), GGML_TYPE_I32, token_steps_, batch_);
ggml_set_input(token_ids_);
positions_ = ggml_new_tensor_3d(input_ctx_.get(), GGML_TYPE_F32, config.dim, total_steps_, batch_);
ggml_set_input(positions_);
auto condition = core::wrap_tensor(condition_, core::TensorShape::from_dims({batch_, condition_steps_, config.dim}), GGML_TYPE_F32);
auto tokens = modules::EmbeddingModule({config.card + 1, config.dim}).build(
ctx,
core::wrap_tensor(token_ids_, core::TensorShape::from_dims({batch_, token_steps_}), GGML_TYPE_I32),
weights_->token_embedding);
auto x = modules::ConcatModule({1}).build(ctx, condition, tokens);
x = modules::AddModule().build(ctx, x, core::wrap_tensor(positions_, core::TensorShape::from_dims({batch_, total_steps_, config.dim}), GGML_TYPE_F32));
graph_ = ggml_new_graph_custom(ctx_.get(), kGraphNodes, false);
for (size_t layer_index = 0; layer_index < weights_->layers.size(); ++layer_index) {
core::TensorValue key;
core::TensorValue value;
x = build_transformer_layer(
ctx,
graph_,
x,
weights_->layers[layer_index],
config,
std::nullopt,
std::nullopt,
std::nullopt,
std::nullopt,
std::nullopt,
perf_mode_,
&key,
&value);
auto key_dest = view_batched_kv_cache_steps(
ctx,
target_keys[layer_index],
0,
total_steps_,
config,
"MuScriptor prefill key target",
target_keys[layer_index].type);
auto value_dest = view_batched_kv_cache_steps(
ctx,
target_values[layer_index],
0,
total_steps_,
config,
"MuScriptor prefill value target",
target_values[layer_index].type);
ggml_build_forward_expand(graph_, ggml_cpy(ctx_.get(), key.tensor, key_dest.tensor));
ggml_build_forward_expand(graph_, ggml_cpy(ctx_.get(), value.tensor, value_dest.tensor));
}
x = modules::LayerNormModule({config.dim, 1.0e-5F, true, true}).build(ctx, x, weights_->output_norm);
auto tail = modules::SliceModule({1, total_steps_ - 1, 1}).build(ctx, x);
logits_ = modules::LinearModule({config.dim, config.card, false}).build(ctx, tail, weights_->output_head).tensor;
ggml_set_output(logits_);
ggml_build_forward_expand(graph_, logits_);
input_buffer_ = ggml_backend_alloc_ctx_tensors(input_ctx_.get(), execution_.backend());
if (input_buffer_ == nullptr) {
throw std::runtime_error("failed to allocate MuScriptor prefill input tensors");
}
gallocr_ = ggml_gallocr_new(ggml_backend_get_default_buffer_type(execution_.backend()));
if (gallocr_ == nullptr || !ggml_gallocr_reserve(gallocr_, graph_) || !ggml_gallocr_alloc_graph(gallocr_, graph_)) {
throw std::runtime_error("failed to allocate MuScriptor prefill graph");
}
const auto one_row_pos = sinusoidal_position_embedding(total_steps_, config.dim);
std::vector<float> pos(static_cast<size_t>(batch_ * total_steps_ * config.dim));
for (int64_t batch = 0; batch < batch_; ++batch) {
std::copy(
one_row_pos.begin(),
one_row_pos.end(),
pos.begin() + static_cast<ptrdiff_t>(batch * total_steps_ * config.dim));
}
ggml_backend_tensor_set(positions_, pos.data(), 0, pos.size() * sizeof(float));
engine::debug::timing_log_scalar("muscriptor.prefill.graph.build_ms", engine::debug::elapsed_ms(start, Clock::now()));
}
~PrefillGraph() {
engine::core::release_backend_graph_resources(execution_.backend(), graph_);
if (gallocr_ != nullptr) {
ggml_gallocr_free(gallocr_);
}
if (input_buffer_ != nullptr) {
ggml_backend_buffer_free(input_buffer_);
}
}
bool matches(const MuScriptorWeights & weights, int64_t condition_steps, int64_t token_steps, int64_t batch, ggml_tensor * target_key0) const {
return weights_.get() == &weights &&
condition_steps_ == condition_steps &&
token_steps_ == token_steps &&
batch_ == batch &&
target_key0_ == target_key0;
}
Output run(const MuScriptorConditioning & condition, const std::vector<int32_t> & token_ids, const MuScriptorConfig & config) {
if (condition.batch != batch_ || condition.steps != condition_steps_ || condition.dim != config.dim) {
throw std::runtime_error("MuScriptor prefill condition shape mismatch");
}
if (static_cast<int64_t>(token_ids.size()) != batch_ * token_steps_) {
throw std::runtime_error("MuScriptor prefill token count mismatch");
}
ggml_backend_tensor_set(condition_, condition.values.data(), 0, condition.values.size() * sizeof(float));
ggml_backend_tensor_set(token_ids_, token_ids.data(), 0, token_ids.size() * sizeof(int32_t));
core::set_backend_threads(execution_.backend(), execution_.config().threads);
const auto start = Clock::now();
const ggml_status status = engine::core::compute_backend_graph(execution_.backend(), graph_);
ggml_backend_synchronize(execution_.backend());
engine::debug::timing_log_scalar("muscriptor.prefill.graph.compute_ms", engine::debug::elapsed_ms(start, Clock::now()));
if (status != GGML_STATUS_SUCCESS) {
throw std::runtime_error("MuScriptor prefill graph compute failed");
}
Output out;
out.logits.resize(static_cast<size_t>(batch_ * config.card));
const auto logits_read_start = Clock::now();
ggml_backend_tensor_get(logits_, out.logits.data(), 0, out.logits.size() * sizeof(float));
engine::debug::timing_log_scalar("muscriptor.prefill.logits_read_ms", engine::debug::elapsed_ms(logits_read_start, Clock::now()));
out.current_end = total_steps_;
engine::debug::timing_log_scalar("muscriptor.prefill.kv_read_ms", 0.0);
return out;
}