-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlm.cpp
More file actions
634 lines (557 loc) · 24.9 KB
/
Copy pathlm.cpp
File metadata and controls
634 lines (557 loc) · 24.9 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
#include "lm.h"
#include <algorithm>
#include <cmath>
#include <cstring>
#include <limits>
#include <numeric>
#include <random>
#include <stdexcept>
#include "ggml.h"
#include "ggml-alloc.h"
#include "ggml-backend.h"
#include "gguf_util.h"
#include "sampling.h"
namespace muscriptor {
namespace {
constexpr size_t kMaxGraphNodes = 16384;
struct LayerTensors {
ggml_tensor* in_proj = nullptr; // [dim, 3*dim]
ggml_tensor* out_proj = nullptr; // [dim, dim]
ggml_tensor* norm1_w = nullptr;
ggml_tensor* norm1_b = nullptr;
ggml_tensor* norm2_w = nullptr;
ggml_tensor* norm2_b = nullptr;
ggml_tensor* linear1 = nullptr; // [dim, 4*dim]
ggml_tensor* linear2 = nullptr; // [4*dim, dim]
};
std::vector<float> softmax_vec(const std::vector<float>& logits) {
float m = *std::max_element(logits.begin(), logits.end());
std::vector<float> p(logits.size());
float sum = 0.f;
for (size_t i = 0; i < logits.size(); ++i) {
p[i] = std::exp(logits[i] - m);
sum += p[i];
}
for (float& v : p) v /= sum;
return p;
}
} // namespace
struct LMModel::Impl {
LMConfig cfg;
BackendPair bp{};
ggml_backend_sched_t sched = nullptr;
// Owned GGUF (load_gguf) — weights live on backend
std::unique_ptr<GgufModelGPU> gguf;
// Random-model weight storage
WeightCtx wctx{};
bool owns_wctx = false;
ggml_tensor* emb = nullptr; // [dim, card+1]
ggml_tensor* out_norm_w = nullptr;
ggml_tensor* out_norm_b = nullptr;
ggml_tensor* lm_head = nullptr; // [dim, card]
std::vector<LayerTensors> layers;
// Device KV cache: per layer K,V as [head_dim, max_seq, n_heads] F32
std::vector<ggml_tensor*> cache_k;
std::vector<ggml_tensor*> cache_v;
ggml_context* cache_ctx = nullptr;
ggml_backend_buffer_t cache_buf = nullptr;
int cache_capacity = 0;
int kv_pos = 0; // next write position (= current sequence length in cache)
~Impl() {
free_cache();
if (sched) {
ggml_backend_sched_free(sched);
sched = nullptr;
}
if (owns_wctx) {
wctx_free(&wctx);
}
// gguf unique_ptr frees itself; do not free shared global backends
}
void free_cache() {
if (cache_buf) {
ggml_backend_buffer_free(cache_buf);
cache_buf = nullptr;
}
if (cache_ctx) {
ggml_free(cache_ctx);
cache_ctx = nullptr;
}
cache_k.clear();
cache_v.clear();
cache_capacity = 0;
kv_pos = 0;
}
void init_backend() {
bp = backend_init("muscriptor");
sched = backend_sched_new(bp, kMaxGraphNodes);
}
void log_backend() {
std::fprintf(stderr, "[muscriptor] LM backend=%s gpu=%d dim=%d layers=%d heads=%d card=%d\n",
ggml_backend_name(bp.backend), bp.has_gpu ? 1 : 0,
cfg.dim, cfg.num_layers, cfg.num_heads, cfg.card);
}
void ensure_cache(int max_seq) {
if (max_seq <= cache_capacity && cache_ctx) return;
free_cache();
const int n_layers = cfg.num_layers;
const int n_heads = cfg.num_heads;
const int head_dim = cfg.dim / cfg.num_heads;
const size_t n_tensors = static_cast<size_t>(n_layers) * 2;
size_t ctx_size = ggml_tensor_overhead() * n_tensors + 1024;
ggml_init_params ip = {ctx_size, nullptr, true};
cache_ctx = ggml_init(ip);
cache_k.resize(n_layers);
cache_v.resize(n_layers);
for (int i = 0; i < n_layers; ++i) {
cache_k[i] = ggml_new_tensor_3d(cache_ctx, GGML_TYPE_F32, head_dim, max_seq, n_heads);
cache_v[i] = ggml_new_tensor_3d(cache_ctx, GGML_TYPE_F32, head_dim, max_seq, n_heads);
ggml_set_name(cache_k[i], ("cache_k_" + std::to_string(i)).c_str());
ggml_set_name(cache_v[i], ("cache_v_" + std::to_string(i)).c_str());
}
cache_buf = ggml_backend_alloc_ctx_tensors(cache_ctx, bp.backend);
if (!cache_buf) {
throw std::runtime_error("failed to allocate KV cache on backend");
}
cache_capacity = max_seq;
kv_pos = 0;
// Zero-fill
std::vector<float> zeros(static_cast<size_t>(head_dim) * max_seq * n_heads, 0.f);
for (int i = 0; i < n_layers; ++i) {
ggml_backend_tensor_set(cache_k[i], zeros.data(), 0, zeros.size() * sizeof(float));
ggml_backend_tensor_set(cache_v[i], zeros.data(), 0, zeros.size() * sizeof(float));
}
}
ggml_tensor* layernorm(ggml_context* ctx, ggml_tensor* x, ggml_tensor* w, ggml_tensor* b) {
auto* n = ggml_norm(ctx, x, 1e-5f);
n = ggml_mul(ctx, n, w);
n = ggml_add(ctx, n, b);
return n;
}
// x: [dim, T]; returns [dim, T]. Writes K/V into cache at kv_pos, attends to [0, kv_pos+T).
ggml_tensor* attn_layer(ggml_context* ctx, ggml_cgraph* gf, int layer_i,
ggml_tensor* x, int T, int n_past) {
const int dim = cfg.dim;
const int n_heads = cfg.num_heads;
const int head_dim = dim / n_heads;
auto& ly = layers[layer_i];
// QKV: [3*dim, T]
auto* qkv = ggml_mul_mat(ctx, ly.in_proj, x);
auto* q = ggml_view_2d(ctx, qkv, dim, T, qkv->nb[1], 0);
auto* k = ggml_view_2d(ctx, qkv, dim, T, qkv->nb[1],
static_cast<size_t>(dim) * qkv->nb[0]);
auto* v = ggml_view_2d(ctx, qkv, dim, T, qkv->nb[1],
static_cast<size_t>(2 * dim) * qkv->nb[0]);
q = ggml_cont(ctx, q);
k = ggml_cont(ctx, k);
v = ggml_cont(ctx, v);
// [head_dim, n_heads, T]
q = ggml_reshape_3d(ctx, q, head_dim, n_heads, T);
k = ggml_reshape_3d(ctx, k, head_dim, n_heads, T);
v = ggml_reshape_3d(ctx, v, head_dim, n_heads, T);
// Permute to [head_dim, T, n_heads] for cache / flash_attn
q = ggml_cont(ctx, ggml_permute(ctx, q, 0, 2, 1, 3));
k = ggml_cont(ctx, ggml_permute(ctx, k, 0, 2, 1, 3));
v = ggml_cont(ctx, ggml_permute(ctx, v, 0, 2, 1, 3));
// Write into cache at n_past
const size_t nb1 = cache_k[layer_i]->nb[1];
const size_t nb2 = cache_k[layer_i]->nb[2];
const size_t off = static_cast<size_t>(n_past) * nb1;
auto* k_dst = ggml_view_3d(ctx, cache_k[layer_i], head_dim, T, n_heads, nb1, nb2, off);
auto* v_dst = ggml_view_3d(ctx, cache_v[layer_i], head_dim, T, n_heads, nb1, nb2, off);
ggml_build_forward_expand(gf, ggml_cpy(ctx, k, k_dst));
ggml_build_forward_expand(gf, ggml_cpy(ctx, v, v_dst));
const int kv_len = n_past + T;
auto* k_full = ggml_view_3d(ctx, cache_k[layer_i], head_dim, kv_len, n_heads, nb1, nb2, 0);
auto* v_full = ggml_view_3d(ctx, cache_v[layer_i], head_dim, kv_len, n_heads, nb1, nb2, 0);
const float scale = 1.f / std::sqrt(static_cast<float>(head_dim));
ggml_tensor* attn_out = nullptr;
if (T == 1) {
// Decode: flash_attn without mask (attend to all past)
attn_out = ggml_flash_attn_ext(ctx, q, k_full, v_full, nullptr, scale, 0.f, 0.f);
ggml_flash_attn_ext_set_prec(attn_out, GGML_PREC_F32);
} else if (n_past == 0 && T == kv_len) {
// Square prefill: causal flash_attn — build F16 mask [kv_len, T]
auto* mask = ggml_new_tensor_2d(ctx, GGML_TYPE_F16, kv_len, T);
ggml_set_input(mask);
ggml_set_name(mask, ("attn_mask_" + std::to_string(layer_i)).c_str());
// We'll set mask data after alloc; for now build with soft_max fallback
// that uses diag_mask which doesn't need external mask data.
// Prefer diag_mask path for prefill reliability across backends:
auto* q_h = ggml_cont(ctx, ggml_permute(ctx, q, 0, 2, 1, 3)); // [hd, nh, T]
auto* k_h = ggml_cont(ctx, ggml_permute(ctx, k_full, 0, 2, 1, 3));
auto* v_h = ggml_cont(ctx, ggml_permute(ctx, v_full, 0, 2, 1, 3));
// scores: mul_mat(k,q) with k,q as [hd, T, nh] → need [T_k, T_q, nh]
// Using flash with causal via soft_max + diag_mask on [T,T,nh]:
auto* k2 = ggml_cont(ctx, ggml_permute(ctx, k_h, 1, 0, 2, 3)); // [T, hd, nh] for mul?
// Standard ggml pattern from t5: q,k as [hd, seq, nh]
auto* scores = ggml_mul_mat(ctx, k_full, q); // [kv_len, T, nh]
scores = ggml_scale(ctx, scores, scale);
scores = ggml_diag_mask_inf(ctx, scores, n_past);
auto* probs = ggml_soft_max(ctx, scores);
// v as [kv_len, hd, nh] for mul_mat with probs [kv_len, T, nh]
auto* v_perm = ggml_cont(ctx, ggml_permute(ctx, v_full, 1, 0, 2, 3)); // [kv_len, hd, nh]
auto* kqv = ggml_mul_mat(ctx, v_perm, probs); // [hd, T, nh]
attn_out = ggml_cont(ctx, ggml_permute(ctx, kqv, 0, 2, 1, 3)); // [hd, nh, T]
(void)mask;
(void)q_h;
(void)k_h;
(void)v_h;
(void)k2;
} else {
// General rectangular: soft_max path
auto* scores = ggml_mul_mat(ctx, k_full, q);
scores = ggml_scale(ctx, scores, scale);
if (n_past == 0) {
scores = ggml_diag_mask_inf(ctx, scores, 0);
}
auto* probs = ggml_soft_max(ctx, scores);
auto* v_perm = ggml_cont(ctx, ggml_permute(ctx, v_full, 1, 0, 2, 3));
auto* kqv = ggml_mul_mat(ctx, v_perm, probs);
attn_out = ggml_cont(ctx, ggml_permute(ctx, kqv, 0, 2, 1, 3));
}
// attn_out expected [hd, nh, T] or flash output [hd, nh, T]
attn_out = ggml_reshape_2d(ctx, attn_out, dim, T);
return ggml_mul_mat(ctx, ly.out_proj, attn_out);
}
ggml_tensor* ffn_layer(ggml_context* ctx, ggml_tensor* x, int layer_i) {
auto& ly = layers[layer_i];
auto* h = ggml_mul_mat(ctx, ly.linear1, x);
h = ggml_gelu_erf(ctx, h); // match PyTorch F.gelu (erf)
return ggml_mul_mat(ctx, ly.linear2, h);
}
// Returns logits for all S token positions: row-major [S, card] on host.
// Advances kv_pos by (prepend + S) on first_step or by S otherwise.
std::vector<float> forward_tokens(
const std::vector<int>& sequence,
const std::vector<ConditionTensor>& conditions,
bool first_step) {
const int S = static_cast<int>(sequence.size());
const int dim = cfg.dim;
if (S <= 0) return {};
int prepend = 0;
if (first_step) {
for (const auto& c : conditions) prepend += c.T;
}
const int T_full = prepend + S;
const int n_past = kv_pos;
ensure_cache(n_past + T_full + 8);
size_t ctx_size = ggml_tensor_overhead() * kMaxGraphNodes + ggml_graph_overhead_custom(kMaxGraphNodes, false);
ggml_init_params ip = {ctx_size, nullptr, true};
ggml_context* ctx = ggml_init(ip);
if (!ctx) throw std::runtime_error("ggml_init failed");
ggml_cgraph* gf = ggml_new_graph_custom(ctx, kMaxGraphNodes, false);
// Token ids input
auto* token_ids = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, S);
ggml_set_name(token_ids, "token_ids");
ggml_set_input(token_ids);
auto* tok_emb = ggml_get_rows(ctx, emb, token_ids); // [dim, S]
ggml_tensor* hidden = tok_emb;
if (prepend > 0) {
// Build condition tensor [dim, prepend] as input (already projected mel etc.)
auto* cond = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, dim, prepend);
ggml_set_name(cond, "cond");
ggml_set_input(cond);
hidden = ggml_concat(ctx, cond, tok_emb, 1); // concat on seq axis
}
// Sin PE [dim, T_full] as input
auto* pos_emb = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, dim, T_full);
ggml_set_name(pos_emb, "pos_emb");
ggml_set_input(pos_emb);
hidden = ggml_add(ctx, hidden, pos_emb);
for (int li = 0; li < cfg.num_layers; ++li) {
auto& ly = layers[li];
auto* n1 = layernorm(ctx, hidden, ly.norm1_w, ly.norm1_b);
auto* a = attn_layer(ctx, gf, li, n1, T_full, n_past);
hidden = ggml_add(ctx, hidden, a);
auto* n2 = layernorm(ctx, hidden, ly.norm2_w, ly.norm2_b);
auto* f = ffn_layer(ctx, n2, li);
hidden = ggml_add(ctx, hidden, f);
}
hidden = layernorm(ctx, hidden, out_norm_w, out_norm_b);
// Take last S positions: view [dim, S] at offset prepend
if (prepend > 0) {
hidden = ggml_view_2d(ctx, hidden, dim, S, hidden->nb[1],
static_cast<size_t>(prepend) * hidden->nb[1]);
hidden = ggml_cont(ctx, hidden);
}
auto* logits = ggml_mul_mat(ctx, lm_head, hidden); // [card, S]
ggml_set_output(logits);
ggml_build_forward_expand(gf, logits);
ggml_backend_sched_reset(sched);
if (!ggml_backend_sched_alloc_graph(sched, gf)) {
ggml_free(ctx);
throw std::runtime_error("ggml_backend_sched_alloc_graph failed");
}
// Set inputs
ggml_backend_tensor_set(token_ids, sequence.data(), 0, S * sizeof(int));
if (prepend > 0) {
auto* cond_t = ggml_graph_get_tensor(gf, "cond");
std::vector<float> cond_col(static_cast<size_t>(dim) * prepend);
// conditions are row-major [T, dim]; ggml wants [dim, T]
int off_t = 0;
for (const auto& c : conditions) {
for (int t = 0; t < c.T; ++t) {
for (int d = 0; d < dim; ++d) {
cond_col[static_cast<size_t>(d) + static_cast<size_t>(off_t + t) * dim] =
c.data[static_cast<size_t>(t) * dim + d];
}
}
off_t += c.T;
}
ggml_backend_tensor_set(cond_t, cond_col.data(), 0, cond_col.size() * sizeof(float));
}
{
std::vector<int64_t> positions(T_full);
for (int t = 0; t < T_full; ++t) positions[t] = n_past + t;
auto pe = create_sin_embedding(positions, dim, cfg.max_period);
// pe is row-major [T, dim] → column-major [dim, T]
std::vector<float> pe_col(static_cast<size_t>(dim) * T_full);
for (int t = 0; t < T_full; ++t) {
for (int d = 0; d < dim; ++d) {
pe_col[static_cast<size_t>(d) + static_cast<size_t>(t) * dim] =
pe[static_cast<size_t>(t) * dim + d];
}
}
auto* pos_t = ggml_graph_get_tensor(gf, "pos_emb");
ggml_backend_tensor_set(pos_t, pe_col.data(), 0, pe_col.size() * sizeof(float));
}
if (ggml_backend_sched_graph_compute(sched, gf) != GGML_STATUS_SUCCESS) {
ggml_free(ctx);
throw std::runtime_error("ggml_backend_sched_graph_compute failed");
}
// logits [card, S] → host row-major [S, card]
std::vector<float> logits_col(static_cast<size_t>(cfg.card) * S);
ggml_backend_tensor_get(logits, logits_col.data(), 0, logits_col.size() * sizeof(float));
std::vector<float> out(static_cast<size_t>(S) * cfg.card);
for (int s = 0; s < S; ++s) {
for (int c = 0; c < cfg.card; ++c) {
out[static_cast<size_t>(s) * cfg.card + c] =
logits_col[static_cast<size_t>(c) + static_cast<size_t>(s) * cfg.card];
}
}
kv_pos = n_past + T_full;
ggml_backend_sched_reset(sched);
ggml_free(ctx);
return out;
}
};
LMModel::LMModel() : impl_(std::make_unique<Impl>()) {}
LMModel::~LMModel() = default;
LMModel::LMModel(LMModel&&) = default;
LMModel& LMModel::operator=(LMModel&&) = default;
int LMModel::card() const { return impl_->cfg.card; }
int LMModel::dim() const { return impl_->cfg.dim; }
int LMModel::initial_token_id() const { return impl_->cfg.card; }
const LMConfig& LMModel::config() const { return impl_->cfg; }
bool LMModel::on_gpu() const { return impl_->bp.has_gpu; }
const char* LMModel::backend_name() const {
return impl_->bp.backend ? ggml_backend_name(impl_->bp.backend) : "none";
}
int LMModel::emb_rows() const { return impl_->cfg.card + 1; }
TransformerConfig LMModel::transformer_config() const {
TransformerConfig tc;
tc.dim = impl_->cfg.dim;
tc.num_heads = impl_->cfg.num_heads;
tc.num_layers = impl_->cfg.num_layers;
tc.dim_ff = impl_->cfg.hidden_scale * impl_->cfg.dim;
tc.max_period = impl_->cfg.max_period;
return tc;
}
void LMModel::reset_cache() { impl_->kv_pos = 0; }
void LMModel::ensure_cache(int max_seq) { impl_->ensure_cache(max_seq); }
LMModel LMModel::create_random(const LMConfig& cfg, uint32_t seed) {
LMModel m;
m.impl_->cfg = cfg;
m.impl_->init_backend();
m.impl_->log_backend();
const int dim = cfg.dim;
const int ff = cfg.hidden_scale * dim;
const int n_tensors = 2 + 2 + cfg.num_layers * 8; // emb, head, norms, layers
if (!wctx_init(&m.impl_->wctx, static_cast<size_t>(n_tensors) + 8)) {
throw std::runtime_error("wctx_init failed");
}
m.impl_->owns_wctx = true;
std::mt19937 rng(seed);
std::normal_distribution<float> dist(0.f, 0.02f);
auto alloc = [&](const char* name, std::initializer_list<int64_t> ne) -> ggml_tensor* {
ggml_tensor* t = nullptr;
if (ne.size() == 1) {
t = ggml_new_tensor_1d(m.impl_->wctx.ctx, GGML_TYPE_F32, *ne.begin());
} else if (ne.size() == 2) {
auto it = ne.begin();
int64_t n0 = *it++;
int64_t n1 = *it;
t = ggml_new_tensor_2d(m.impl_->wctx.ctx, GGML_TYPE_F32, n0, n1);
}
ggml_set_name(t, name);
size_t n = ggml_nelements(t);
auto* buf = new float[n];
for (size_t i = 0; i < n; ++i) buf[i] = dist(rng);
m.impl_->wctx.pending.push_back({t, buf, n * sizeof(float), 0});
return t;
};
// emb [dim, card+1]
m.impl_->emb = alloc("emb.weight", {dim, cfg.card + 1});
m.impl_->out_norm_w = alloc("out_norm.weight", {dim});
m.impl_->out_norm_b = alloc("out_norm.bias", {dim});
// init LN scale to 1
{
auto& p = m.impl_->wctx.pending[m.impl_->wctx.pending.size() - 2];
float* w = const_cast<float*>(static_cast<const float*>(p.src));
std::fill(w, w + dim, 1.f);
float* b = const_cast<float*>(static_cast<const float*>(
m.impl_->wctx.pending.back().src));
std::fill(b, b + dim, 0.f);
}
m.impl_->lm_head = alloc("linear.weight", {dim, cfg.card});
m.impl_->layers.resize(cfg.num_layers);
for (int i = 0; i < cfg.num_layers; ++i) {
std::string p = "L" + std::to_string(i) + ".";
auto& ly = m.impl_->layers[i];
ly.in_proj = alloc((p + "in").c_str(), {dim, 3 * dim});
ly.out_proj = alloc((p + "out").c_str(), {dim, dim});
ly.norm1_w = alloc((p + "n1w").c_str(), {dim});
ly.norm1_b = alloc((p + "n1b").c_str(), {dim});
ly.norm2_w = alloc((p + "n2w").c_str(), {dim});
ly.norm2_b = alloc((p + "n2b").c_str(), {dim});
// LN = 1
for (int k = 0; k < 2; ++k) {
auto& pw = m.impl_->wctx.pending[m.impl_->wctx.pending.size() - 4 + k * 2];
float* w = const_cast<float*>(static_cast<const float*>(pw.src));
std::fill(w, w + dim, 1.f);
auto& pb = m.impl_->wctx.pending[m.impl_->wctx.pending.size() - 3 + k * 2];
float* b = const_cast<float*>(static_cast<const float*>(pb.src));
std::fill(b, b + dim, 0.f);
}
ly.linear1 = alloc((p + "ff1").c_str(), {dim, ff});
ly.linear2 = alloc((p + "ff2").c_str(), {ff, dim});
}
if (!wctx_alloc(&m.impl_->wctx, m.impl_->bp.backend)) {
throw std::runtime_error("wctx_alloc failed");
}
// Leak pending host buffers intentionally for test lifetime (pointed into by backend copy already done)
for (auto& p : m.impl_->wctx.pending) {
delete[] static_cast<const float*>(p.src);
}
m.impl_->wctx.pending.clear();
return m;
}
LMModel LMModel::load_gguf(const std::string& path) {
LMModel m;
m.impl_->init_backend();
m.impl_->gguf = std::make_unique<GgufModelGPU>(path, m.impl_->bp.backend);
auto& g = *m.impl_->gguf;
m.impl_->cfg.dim = g.kv_i32("muscriptor.dim");
m.impl_->cfg.num_heads = g.kv_i32("muscriptor.num_heads");
m.impl_->cfg.num_layers = g.kv_i32("muscriptor.num_layers");
m.impl_->cfg.card = g.kv_i32("muscriptor.card");
m.impl_->cfg.hidden_scale = g.kv_i32_or("muscriptor.hidden_scale", 4);
m.impl_->cfg.max_period = g.kv_f32_or("muscriptor.max_period", 10000.f);
m.impl_->log_backend();
auto must = [&](const std::string& name) { return g.tensor(name); };
m.impl_->emb = must("emb.weight");
m.impl_->out_norm_w = must("out_norm.weight");
m.impl_->out_norm_b = must("out_norm.bias");
m.impl_->lm_head = must("linear.weight");
m.impl_->layers.resize(m.impl_->cfg.num_layers);
for (int i = 0; i < m.impl_->cfg.num_layers; ++i) {
std::string p = "transformer.layers." + std::to_string(i) + ".";
auto& ly = m.impl_->layers[i];
ly.in_proj = must(p + "self_attn.in_proj_weight");
ly.out_proj = must(p + "self_attn.out_proj.weight");
ly.norm1_w = must(p + "norm1.weight");
ly.norm1_b = must(p + "norm1.bias");
ly.norm2_w = must(p + "norm2.weight");
ly.norm2_b = must(p + "norm2.bias");
ly.linear1 = must(p + "linear1.weight");
ly.linear2 = must(p + "linear2.weight");
}
return m;
}
std::vector<float> LMModel::forward(
const std::vector<int>& sequence,
const std::vector<ConditionTensor>& conditions,
bool first_step,
KVCache* /*host_cache*/) {
return impl_->forward_tokens(sequence, conditions, first_step);
}
std::vector<int> LMModel::generate(
const std::vector<ConditionTensor>& conditions,
const GenerateConfig& gen_cfg,
std::function<void(int token)> on_token) {
reset_cache();
int prepend = 0;
for (const auto& c : conditions) prepend += c.T;
ensure_cache(prepend + gen_cfg.max_gen_len + 8);
std::vector<int> gen_sequence(gen_cfg.max_gen_len + 1, -2);
gen_sequence[0] = initial_token_id();
int start_offset = 0;
if (!gen_cfg.prompt.empty()) {
for (size_t i = 0; i < gen_cfg.prompt.size() &&
i < static_cast<size_t>(gen_cfg.max_gen_len); ++i) {
gen_sequence[i + 1] = gen_cfg.prompt[i];
}
start_offset = static_cast<int>(gen_cfg.prompt.size());
}
std::vector<int> yielded;
// Emit prompt tokens
for (int t = 0; t < start_offset; ++t) {
yielded.push_back(gen_sequence[t + 1]);
if (on_token) on_token(gen_sequence[t + 1]);
}
// Beam search still falls back to greedy for now if beam_size>1 with a warning
if (gen_cfg.beam_size > 1) {
std::fprintf(stderr, "[muscriptor] warning: beam_size>1 not yet on ggml path; using greedy\n");
}
for (int offset = start_offset; offset < gen_cfg.max_gen_len; ++offset) {
if (gen_cfg.early_stop_on_token >= 0) {
bool done = false;
for (int i = 1; i <= offset; ++i) {
if (gen_sequence[i] == gen_cfg.early_stop_on_token) {
done = true;
break;
}
}
if (done) break;
}
bool first_iter = (offset == start_offset);
std::vector<int> input;
if (first_iter) {
input.assign(gen_sequence.begin(), gen_sequence.begin() + offset + 1);
} else {
input = {gen_sequence[offset]};
}
auto logits_full = impl_->forward_tokens(
input, first_iter ? conditions : std::vector<ConditionTensor>{}, first_iter);
// last timestep logits
const int card = impl_->cfg.card;
std::vector<float> logits(logits_full.end() - card, logits_full.end());
for (int i = 1393; i < card; ++i) {
logits[i] = -std::numeric_limits<float>::infinity();
}
for (int id : gen_cfg.forbidden_tokens) {
if (id >= 0 && id < card) logits[id] = -std::numeric_limits<float>::infinity();
}
int next_token;
if (gen_cfg.use_sampling && gen_cfg.temp > 0.f) {
std::vector<float> scaled = logits;
for (float& v : scaled) v /= gen_cfg.temp;
next_token = sample_from_probs(softmax_vec(scaled), gen_cfg.top_p, gen_cfg.top_k);
} else {
next_token = static_cast<int>(
std::distance(logits.begin(), std::max_element(logits.begin(), logits.end())));
}
if (gen_sequence[offset + 1] == -2) {
gen_sequence[offset + 1] = next_token;
}
yielded.push_back(gen_sequence[offset + 1]);
if (on_token) on_token(gen_sequence[offset + 1]);
if (gen_cfg.early_stop_on_token >= 0 &&
gen_sequence[offset + 1] == gen_cfg.early_stop_on_token) {
break;
}
}
return yielded;
}
} // namespace muscriptor