aboutsummaryrefslogtreecommitdiff
path: root/pplx_embed.c
blob: a117b1071c5c3e89d65e4d44946334d9c56292f7 (plain) (blame)
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
#include "pplx_embed.h"
#include "qwen_asr_kernels.h"
#include "qwen_asr_safetensors.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <limits.h>

typedef struct {
    const float *wq;            /* [q_dim,   hidden] */
    const float *wk;            /* [kv_dim,  hidden] */
    const float *wv;            /* [kv_dim,  hidden] */
    const float *wo;            /* [hidden,  q_dim]  */
    const float *q_norm;        /* [head_dim] */
    const float *k_norm;        /* [head_dim] */
    const float *input_norm;    /* [hidden] */
    const float *post_attn_norm;/* [hidden] */
    const float *gate_proj;     /* [intermediate, hidden] */
    const float *up_proj;       /* [intermediate, hidden] */
    const float *down_proj;     /* [hidden, intermediate] */
} pplx_layer_t;

typedef struct {
    const float *embed_tokens;  /* [vocab_size, hidden] */
    pplx_layer_t *layers;       /* [n_layers] heap-allocated */
    const float *norm;          /* [hidden] */
} pplx_weights_t;

struct pplx_model {
    pplx_config_t  config;
    pplx_weights_t weights;
    void *safetensors;          /* multi_safetensors_t*, keeps mmap alive */
};

struct pplx_workspace {
    const pplx_model_t *model;  /* immutable model this workspace belongs to */
    int    buf_seq_cap;
    float *x;                   /* [seq, hidden]       */
    float *x_norm;              /* [seq, hidden]       */
    float *q;                   /* [seq, q_dim]        */
    float *k;                   /* [seq, kv_dim]       */
    float *v;                   /* [seq, kv_dim]       */
    float *attn_out;            /* [seq, q_dim]        */
    float *proj_out;            /* [seq, hidden]       */
    float *ffn_gate;            /* [seq, intermediate] */
    float *ffn_up;              /* [seq, intermediate] */
    float *ffn_out;             /* [seq, hidden]       */

    /* RoPE cosine/sine cache [n_pos, head_dim], grown lazily. */
    float *rope_cos;
    float *rope_sin;
    int    rope_cache_cap;
};

/* ========================================================================
 * Globals
 * ======================================================================== */

int pplx_verbose = 0;
int qwen_verbose = 0;

/* ========================================================================
 * Size helpers
 * ======================================================================== */

static int mul_size(size_t a, size_t b, size_t *out)
{
    if (a != 0 && b > SIZE_MAX / a) return -1;
    *out = a * b;
    return 0;
}

static int grow_cap(int current, int needed, int *out)
{
    if (needed <= 0) return -1;

    int cap = current > 0 ? current : 64;
    while (cap < needed) {
        if (cap > INT_MAX / 2) return -1;
        cap *= 2;
    }
    *out = cap;
    return 0;
}

static int realloc_floats(float **ptr, size_t count)
{
    size_t bytes;
    if (mul_size(count, sizeof(float), &bytes) != 0) return -1;

    void *p = realloc(*ptr, bytes);
    if (!p && bytes != 0) return -1;
    *ptr = (float *)p;
    return 0;
}

static float *malloc_floats(size_t count)
{
    size_t bytes;
    if (mul_size(count, sizeof(float), &bytes) != 0) return NULL;
    return (float *)malloc(bytes);
}

static int realloc_floats_2d(float **ptr, int rows, int cols)
{
    if (rows < 0 || cols < 0) return -1;

    size_t count;
    if (mul_size((size_t)rows, (size_t)cols, &count) != 0) return -1;
    return realloc_floats(ptr, count);
}

/* ========================================================================
 * Minimal JSON helpers for config.json parsing
 * ======================================================================== */

static const char *skip_ws(const char *p)
{
    while (*p == ' ' || *p == '\n' || *p == '\r' || *p == '\t') p++;
    return p;
}

/* Find "key": <value> in a flat JSON object. Returns pointer to value start. */
static const char *json_find_key(const char *json, const char *key)
{
    size_t klen = strlen(key);
    const char *p = json;
    while ((p = strstr(p, key)) != NULL) {
        /* Check it's actually a quoted key: "key" */
        if (p > json && *(p - 1) == '"') {
            const char *after = p + klen;
            if (*after == '"') {
                after = skip_ws(after + 1);
                if (*after == ':') return skip_ws(after + 1);
            }
        }
        p += klen;
    }
    return NULL;
}

static int json_get_int(const char *json, const char *key, int fallback)
{
    const char *v = json_find_key(json, key);
    if (!v) return fallback;
    return atoi(v);
}

static double json_get_double(const char *json, const char *key, double fallback)
{
    const char *v = json_find_key(json, key);
    if (!v) return fallback;
    return atof(v);
}

static int parse_config(pplx_config_t *cfg, const char *model_dir)
{
    char path[1024];
    int n = snprintf(path, sizeof(path), "%s/config.json", model_dir);
    if (n < 0 || (size_t)n >= sizeof(path)) {
        fprintf(stderr, "pplx_model_load: model path too long\n");
        return -1;
    }

    FILE *f = fopen(path, "rb");
    if (!f) {
        fprintf(stderr, "pplx_model_load: cannot open %s\n", path);
        return -1;
    }

    if (fseek(f, 0, SEEK_END) != 0) {
        fclose(f);
        return -1;
    }
    long sz = ftell(f);
    if (sz < 0 || (size_t)sz == SIZE_MAX || fseek(f, 0, SEEK_SET) != 0) {
        fclose(f);
        return -1;
    }
    char *buf = (char *)malloc((size_t)sz + 1);
    if (!buf || fread(buf, 1, (size_t)sz, f) != (size_t)sz) {
        fclose(f); free(buf); return -1;
    }
    fclose(f);
    buf[sz] = '\0';

    cfg->hidden_size      = json_get_int(buf, "hidden_size", 0);
    cfg->n_layers         = json_get_int(buf, "num_hidden_layers", 0);
    cfg->n_heads          = json_get_int(buf, "num_attention_heads", 0);
    cfg->n_kv_heads       = json_get_int(buf, "num_key_value_heads", 0);
    cfg->head_dim         = json_get_int(buf, "head_dim", PPLX_HEAD_DIM);
    cfg->intermediate_size = json_get_int(buf, "intermediate_size", 0);
    cfg->vocab_size       = json_get_int(buf, "vocab_size", PPLX_VOCAB_SIZE);
    cfg->rms_norm_eps     = (float)json_get_double(buf, "rms_norm_eps", 1e-6);
    cfg->rope_theta       = (float)json_get_double(buf, "rope_theta", 1000000.0);

    cfg->q_dim = 0;
    cfg->kv_dim = 0;
    if (cfg->n_heads > 0 && cfg->head_dim > 0 &&
        cfg->n_heads <= INT_MAX / cfg->head_dim)
        cfg->q_dim = cfg->n_heads * cfg->head_dim;
    if (cfg->n_kv_heads > 0 && cfg->head_dim > 0 &&
        cfg->n_kv_heads <= INT_MAX / cfg->head_dim)
        cfg->kv_dim = cfg->n_kv_heads * cfg->head_dim;

    free(buf);

    /* Sanity checks */
    if (cfg->hidden_size <= 0 || cfg->n_layers <= 0 ||
        cfg->n_heads <= 0 || cfg->n_kv_heads <= 0 ||
        cfg->head_dim <= 0 || cfg->intermediate_size <= 0 ||
        cfg->vocab_size <= 0 || cfg->q_dim <= 0 || cfg->kv_dim <= 0 ||
        (cfg->head_dim & 1) || cfg->n_heads % cfg->n_kv_heads != 0 ||
        !isfinite(cfg->rms_norm_eps) || cfg->rms_norm_eps <= 0.0f ||
        !isfinite(cfg->rope_theta) || cfg->rope_theta <= 0.0f) {
        fprintf(stderr, "pplx_model_load: invalid config in %s "
                "(hidden=%d, layers=%d, heads=%d/%d, head_dim=%d, inter=%d)\n",
                path, cfg->hidden_size, cfg->n_layers, cfg->n_heads,
                cfg->n_kv_heads, cfg->head_dim, cfg->intermediate_size);
        return -1;
    }
    if (cfg->n_layers > PPLX_MAX_LAYERS) {
        fprintf(stderr, "pplx_model_load: too many layers (%d > %d)\n",
                cfg->n_layers, PPLX_MAX_LAYERS);
        return -1;
    }

    if (pplx_verbose >= 1)
        fprintf(stderr, "config: hidden=%d, layers=%d, heads=%d/%d, "
                "inter=%d, head_dim=%d\n",
                cfg->hidden_size, cfg->n_layers,
                cfg->n_heads, cfg->n_kv_heads,
                cfg->intermediate_size, cfg->head_dim);

    return 0;
}

/* ========================================================================
 * Weight loading (direct mmap pointers into safetensors)
 * ======================================================================== */

static int tensor_has_f32_shape(const safetensors_file_t *sf,
                                const safetensor_t *t, const char *name,
                                const int64_t *shape, int ndim)
{
    if (t->dtype != DTYPE_F32) {
        fprintf(stderr, "pplx: expected F32 for %s, got dtype=%d\n",
                name, (int)t->dtype);
        return 0;
    }
    if (t->ndim != ndim) {
        fprintf(stderr, "pplx: bad rank for %s: got %d, expected %d\n",
                name, t->ndim, ndim);
        return 0;
    }

    size_t numel = 1;
    for (int i = 0; i < ndim; i++) {
        if (t->shape[i] != shape[i]) {
            fprintf(stderr, "pplx: bad shape for %s at dim %d: "
                    "got %lld, expected %lld\n",
                    name, i, (long long)t->shape[i], (long long)shape[i]);
            return 0;
        }
        if (shape[i] < 0 || (uint64_t)shape[i] > SIZE_MAX / numel) {
            fprintf(stderr, "pplx: shape too large for %s\n", name);
            return 0;
        }
        numel *= (size_t)shape[i];
    }

    size_t bytes;
    if (mul_size(numel, sizeof(float), &bytes) != 0 ||
        t->data_size != bytes) {
        fprintf(stderr, "pplx: bad data size for %s: got %zu, expected %zu\n",
                name, t->data_size, bytes);
        return 0;
    }

    size_t data_start = 8 + sf->header_size;
    if (data_start > sf->file_size ||
        t->data_offset > sf->file_size - data_start ||
        t->data_size > sf->file_size - data_start - t->data_offset) {
        fprintf(stderr, "pplx: tensor data out of bounds for %s\n", name);
        return 0;
    }
    return 1;
}

static const float *load_f32_direct(multi_safetensors_t *ms, const char *name,
                                    const int64_t *shape, int ndim)
{
    safetensors_file_t *sf = NULL;
    const safetensor_t *t  = multi_safetensors_find(ms, name, &sf);
    if (!t) {
        fprintf(stderr, "pplx: tensor not found: %s\n", name);
        return NULL;
    }
    if (!tensor_has_f32_shape(sf, t, name, shape, ndim))
        return NULL;
    return (const float *)safetensors_data(sf, t);
}

/* ========================================================================
 * Working buffer management
 * ======================================================================== */

static int ensure_buffers(pplx_workspace_t *ws, const pplx_config_t *c, int seq)
{
    if (seq <= ws->buf_seq_cap) return 0;

    int cap;
    if (grow_cap(ws->buf_seq_cap, seq, &cap) != 0) return -1;

#define R(ptr, n) do {                                          \
    if (realloc_floats_2d(&(ptr), cap, (n)) != 0) return -1;     \
} while (0)

    R(ws->x,        c->hidden_size);
    R(ws->x_norm,   c->hidden_size);
    R(ws->q,        c->q_dim);
    R(ws->k,        c->kv_dim);
    R(ws->v,        c->kv_dim);
    R(ws->attn_out, c->q_dim);
    R(ws->proj_out, c->hidden_size);
    R(ws->ffn_gate, c->intermediate_size);
    R(ws->ffn_up,   c->intermediate_size);
    R(ws->ffn_out,  c->hidden_size);

#undef R

    ws->buf_seq_cap = cap;
    return 0;
}

/* ========================================================================
 * RoPE cache
 * ======================================================================== */

static int ensure_rope_cache(pplx_workspace_t *ws, const pplx_config_t *cfg,
                             int n_pos)
{
    if (n_pos <= ws->rope_cache_cap) return 0;

    int cap = ws->rope_cache_cap > 0 ? ws->rope_cache_cap : 512;
    while (cap < n_pos) {
        if (cap > INT_MAX / 2) return -1;
        cap *= 2;
    }

    int   head_dim = cfg->head_dim;
    int   half     = head_dim / 2;
    float theta    = cfg->rope_theta;

    size_t count;
    if (mul_size((size_t)cap, (size_t)head_dim, &count) != 0)
        return -1;
    if (realloc_floats(&ws->rope_cos, count) != 0)
        return -1;
    if (realloc_floats(&ws->rope_sin, count) != 0)
        return -1;

    for (int pos = ws->rope_cache_cap; pos < cap; pos++) {
        float fp = (float)pos;
        float *c = ws->rope_cos + (size_t)pos * head_dim;
        float *s = ws->rope_sin + (size_t)pos * head_dim;
        for (int d = 0; d < half; d++) {
            float inv = 1.0f / powf(theta, (float)(2 * d) / (float)head_dim);
            float angle = fp * inv;
            float cv = cosf(angle), sv = sinf(angle);
            c[d] = cv;  c[half + d] = cv;
            s[d] = sv;  s[half + d] = sv;
        }
    }

    ws->rope_cache_cap = cap;
    return 0;
}

/* ========================================================================
 * Model / workspace load and free
 * ======================================================================== */

pplx_model_t *pplx_model_load(const char *model_dir)
{
    pplx_model_t *model = (pplx_model_t *)calloc(1, sizeof(pplx_model_t));
    if (!model) return NULL;

    /* Parse config.json */
    if (parse_config(&model->config, model_dir) != 0) {
        free(model);
        return NULL;
    }

    const pplx_config_t *cfg = &model->config;

    /* Open safetensors (handles single file or multi-shard) */
    multi_safetensors_t *ms = multi_safetensors_open(model_dir);
    if (!ms) {
        fprintf(stderr, "pplx_model_load: failed to open safetensors in %s\n", model_dir);
        free(model);
        return NULL;
    }
    model->safetensors = ms;

    if (pplx_verbose >= 1)
        fprintf(stderr, "pplx_model_load: loading weights from %s\n", model_dir);

    /* Token embeddings */
    pplx_weights_t *w = &model->weights;
    const int64_t embed_shape[2] = { cfg->vocab_size, cfg->hidden_size };
    w->embed_tokens = load_f32_direct(ms, "embed_tokens.weight",
                                      embed_shape, 2);
    if (!w->embed_tokens) goto fail;

    /* Allocate layer array */
    w->layers = (pplx_layer_t *)calloc(cfg->n_layers, sizeof(pplx_layer_t));
    if (!w->layers) goto fail;

    /* Per-layer weights */
    char name[256];
    for (int i = 0; i < cfg->n_layers; i++) {
        pplx_layer_t *l = &w->layers[i];

#define LOAD1(field, fmt, d0) do {                          \
    const int64_t expect[1] = { (d0) };                     \
    snprintf(name, sizeof(name), fmt, i);                   \
    l->field = load_f32_direct(ms, name, expect, 1);        \
    if (!l->field) goto fail;                               \
} while (0)

#define LOAD2(field, fmt, d0, d1) do {                      \
    const int64_t expect[2] = { (d0), (d1) };                \
    snprintf(name, sizeof(name), fmt, i);                   \
    l->field = load_f32_direct(ms, name, expect, 2);        \
    if (!l->field) goto fail;                               \
} while (0)

        LOAD2(wq,             "layers.%d.self_attn.q_proj.weight",
              cfg->q_dim, cfg->hidden_size);
        LOAD2(wk,             "layers.%d.self_attn.k_proj.weight",
              cfg->kv_dim, cfg->hidden_size);
        LOAD2(wv,             "layers.%d.self_attn.v_proj.weight",
              cfg->kv_dim, cfg->hidden_size);
        LOAD2(wo,             "layers.%d.self_attn.o_proj.weight",
              cfg->hidden_size, cfg->q_dim);
        LOAD1(q_norm,         "layers.%d.self_attn.q_norm.weight",
              cfg->head_dim);
        LOAD1(k_norm,         "layers.%d.self_attn.k_norm.weight",
              cfg->head_dim);
        LOAD1(input_norm,     "layers.%d.input_layernorm.weight",
              cfg->hidden_size);
        LOAD1(post_attn_norm, "layers.%d.post_attention_layernorm.weight",
              cfg->hidden_size);
        LOAD2(gate_proj,      "layers.%d.mlp.gate_proj.weight",
              cfg->intermediate_size, cfg->hidden_size);
        LOAD2(up_proj,        "layers.%d.mlp.up_proj.weight",
              cfg->intermediate_size, cfg->hidden_size);
        LOAD2(down_proj,      "layers.%d.mlp.down_proj.weight",
              cfg->hidden_size, cfg->intermediate_size);

#undef LOAD2
#undef LOAD1

        if (pplx_verbose >= 2)
            fprintf(stderr, "  layer %d loaded\n", i);
    }

    /* Final RMSNorm */
    const int64_t norm_shape[1] = { cfg->hidden_size };
    w->norm = load_f32_direct(ms, "norm.weight", norm_shape, 1);
    if (!w->norm) goto fail;

    if (pplx_verbose >= 1)
        fprintf(stderr, "pplx_model_load: %d layers loaded (%d-dim embeddings)\n",
                cfg->n_layers, cfg->hidden_size);

    return model;

fail:
    pplx_model_free(model);
    return NULL;
}

void pplx_model_free(pplx_model_t *model)
{
    if (!model) return;
    if (model->safetensors)
        multi_safetensors_close((multi_safetensors_t *)model->safetensors);
    free(model->weights.layers);
    free(model);
}

pplx_workspace_t *pplx_workspace_new(const pplx_model_t *model)
{
    if (!model) return NULL;
    pplx_workspace_t *ws = (pplx_workspace_t *)calloc(1, sizeof(pplx_workspace_t));
    if (!ws) return NULL;
    ws->model = model;
    return ws;
}

void pplx_workspace_free(pplx_workspace_t *ws)
{
    if (!ws) return;
    free(ws->x);       free(ws->x_norm);
    free(ws->q);       free(ws->k);        free(ws->v);
    free(ws->attn_out); free(ws->proj_out);
    free(ws->ffn_gate); free(ws->ffn_up);   free(ws->ffn_out);
    free(ws->rope_cos); free(ws->rope_sin);
    free(ws);
}

const pplx_config_t *pplx_model_config(const pplx_model_t *model)
{
    return model ? &model->config : NULL;
}

/* ========================================================================
 * Packed forward pass
 * ======================================================================== */

static int build_offsets(const pplx_input_t *inputs, int batch,
                         int *offsets, int *total_out, int *max_out)
{
    if (!inputs || batch <= 0 || !offsets || !total_out || !max_out)
        return -1;

    int total = 0;
    int max_seq = 0;
    for (int b = 0; b < batch; b++) {
        if (!inputs[b].ids || inputs[b].n_tokens <= 0)
            return -1;
        if (total > INT32_MAX - inputs[b].n_tokens)
            return -1;
        offsets[b] = total;
        total += inputs[b].n_tokens;
        if (inputs[b].n_tokens > max_seq)
            max_seq = inputs[b].n_tokens;
    }
    offsets[batch] = total;
    *total_out = total;
    *max_out = max_seq;
    return 0;
}

static int forward_packed_inplace(const pplx_model_t *model,
                                  pplx_workspace_t *ws,
                                  const pplx_input_t *inputs,
                                  int batch, const int *offsets,
                                  int total_seq, int max_seq)
{
    if (!model || !ws || ws->model != model || !inputs ||
        batch <= 0 || !offsets || total_seq <= 0 || max_seq <= 0)
        return -1;

    const pplx_config_t  *cfg = &model->config;
    const pplx_weights_t *w   = &model->weights;

    int hidden     = cfg->hidden_size;
    int n_heads    = cfg->n_heads;
    int n_kv_heads = cfg->n_kv_heads;
    int head_dim   = cfg->head_dim;
    int q_dim      = cfg->q_dim;
    int kv_dim     = cfg->kv_dim;
    int inter      = cfg->intermediate_size;
    float eps      = cfg->rms_norm_eps;

    if (ensure_buffers(ws, cfg, total_seq) != 0) return -1;
    if (ensure_rope_cache(ws, cfg, max_seq) != 0) return -1;

    const float *rope_cos = ws->rope_cos;
    const float *rope_sin = ws->rope_sin;

    float *x        = ws->x;
    float *x_norm   = ws->x_norm;
    float *q_buf    = ws->q;
    float *k_buf    = ws->k;
    float *v_buf    = ws->v;
    float *attn_out = ws->attn_out;
    float *proj_out = ws->proj_out;
    float *ffn_gate = ws->ffn_gate;
    float *ffn_up   = ws->ffn_up;
    float *ffn_out  = ws->ffn_out;

    /* 1. Token embedding lookup into packed [total_seq, hidden]. */
    for (int b = 0; b < batch; b++) {
        int start = offsets[b];
        for (int i = 0; i < inputs[b].n_tokens; i++) {
            int id = inputs[b].ids[i];
            if (id < 0 || id >= cfg->vocab_size) {
                fprintf(stderr, "pplx: invalid token id %d at input %d position %d\n",
                        id, b, i);
                return -1;
            }
            memcpy(x + (size_t)(start + i) * hidden,
                   w->embed_tokens + (size_t)id * hidden,
                   (size_t)hidden * sizeof(float));
        }
    }

    float scale = 1.0f / sqrtf((float)head_dim);

    /* 2. Transformer layers. Linear/MLP ops run over all packed tokens;
     * attention is explicitly block-diagonal by sequence offsets. */
    for (int layer = 0; layer < cfg->n_layers; layer++) {
        const pplx_layer_t *l = &w->layers[layer];

        qwen_rms_norm(x_norm, x, l->input_norm, total_seq, hidden, eps);

        qwen_linear_nobias(q_buf, x_norm, l->wq, total_seq, hidden, q_dim);
        qwen_linear_nobias(k_buf, x_norm, l->wk, total_seq, hidden, kv_dim);
        qwen_linear_nobias(v_buf, x_norm, l->wv, total_seq, hidden, kv_dim);

        qwen_rms_norm_per_head(q_buf, l->q_norm, total_seq, n_heads,    head_dim, eps);
        qwen_rms_norm_per_head(k_buf, l->k_norm, total_seq, n_kv_heads, head_dim, eps);

        for (int b = 0; b < batch; b++) {
            int start = offsets[b];
            int len = offsets[b + 1] - start;
            qwen_apply_rope_neox(q_buf + (size_t)start * q_dim,
                                 rope_cos, rope_sin, len, n_heads, head_dim);
            qwen_apply_rope_neox(k_buf + (size_t)start * kv_dim,
                                 rope_cos, rope_sin, len, n_kv_heads, head_dim);
        }

        qwen_bidirectional_gqa_attention_packed(attn_out, q_buf, k_buf, v_buf,
                                                offsets, batch, n_heads,
                                                n_kv_heads, head_dim, scale);

        qwen_linear_nobias(proj_out, attn_out, l->wo, total_seq, q_dim, hidden);
        qwen_add_inplace(x, proj_out, total_seq * hidden);

        qwen_rms_norm(x_norm, x, l->post_attn_norm, total_seq, hidden, eps);

        qwen_linear_nobias(ffn_gate, x_norm, l->gate_proj, total_seq, hidden, inter);
        qwen_linear_nobias(ffn_up,   x_norm, l->up_proj,   total_seq, hidden, inter);
        qwen_silu(ffn_gate, total_seq * inter);
        qwen_mul_inplace(ffn_gate, ffn_up, total_seq * inter);
        qwen_linear_nobias(ffn_out, ffn_gate, l->down_proj, total_seq, inter, hidden);
        qwen_add_inplace(x, ffn_out, total_seq * hidden);
    }

    qwen_rms_norm(x, x, w->norm, total_seq, hidden, eps);
    return 0;
}

static void pool_embeddings(const pplx_model_t *model, const pplx_workspace_t *ws,
                            const int *offsets, int batch, float *out_embeddings)
{
    int hidden = model->config.hidden_size;
    const float *x = ws->x;

    for (int b = 0; b < batch; b++) {
        int start = offsets[b];
        int end = offsets[b + 1];
        int len = end - start;
        float *emb = out_embeddings + (size_t)b * hidden;

        memset(emb, 0, (size_t)hidden * sizeof(float));
        for (int i = start; i < end; i++) {
            const float *row = x + (size_t)i * hidden;
            for (int d = 0; d < hidden; d++)
                emb[d] += row[d];
        }

        float inv_len = 1.0f / (float)len;
        for (int d = 0; d < hidden; d++)
            emb[d] *= inv_len;

        float norm_sq = 0.0f;
        for (int d = 0; d < hidden; d++)
            norm_sq += emb[d] * emb[d];
        float nv = sqrtf(norm_sq);
        if (nv > 1e-8f) {
            float inv = 1.0f / nv;
            for (int d = 0; d < hidden; d++)
                emb[d] *= inv;
        }
    }
}

/* ========================================================================
 * Public forward/embed APIs
 * ======================================================================== */

int pplx_model_forward_into(const pplx_model_t *model, pplx_workspace_t *ws,
                            const int *token_ids, int n_tokens,
                            float *out_states)
{
    if (!model || !ws || !token_ids || n_tokens <= 0 || !out_states) return -1;

    size_t count, bytes;
    if (mul_size((size_t)n_tokens, (size_t)model->config.hidden_size,
                 &count) != 0 ||
        mul_size(count, sizeof(float), &bytes) != 0)
        return -1;

    pplx_input_t input = { token_ids, n_tokens };
    int offsets[2] = { 0, n_tokens };
    if (forward_packed_inplace(model, ws, &input, 1, offsets,
                               n_tokens, n_tokens) != 0)
        return -1;

    memcpy(out_states, ws->x, bytes);
    return 0;
}

float *pplx_model_forward(const pplx_model_t *model, pplx_workspace_t *ws,
                          const int *token_ids, int n_tokens)
{
    if (!model || !ws || !token_ids || n_tokens <= 0) return NULL;

    size_t n;
    if (mul_size((size_t)n_tokens, (size_t)model->config.hidden_size, &n) != 0)
        return NULL;
    float *out = malloc_floats(n);
    if (!out) return NULL;

    if (pplx_model_forward_into(model, ws, token_ids, n_tokens, out) != 0) {
        free(out);
        return NULL;
    }
    return out;
}

int pplx_model_embed_batch(const pplx_model_t *model, pplx_workspace_t *ws,
                           const pplx_input_t *inputs, int batch,
                           float *out_embeddings)
{
    if (!model || !ws || !inputs || batch <= 0 || !out_embeddings) return -1;

    if (batch == INT_MAX) return -1;
    size_t offset_bytes;
    if (mul_size((size_t)batch + 1, sizeof(int), &offset_bytes) != 0)
        return -1;
    int *offsets = (int *)malloc(offset_bytes);
    if (!offsets) return -1;

    int total_seq = 0;
    int max_seq = 0;
    if (build_offsets(inputs, batch, offsets, &total_seq, &max_seq) != 0) {
        free(offsets);
        return -1;
    }

    int rc = forward_packed_inplace(model, ws, inputs, batch, offsets,
                                    total_seq, max_seq);
    if (rc == 0)
        pool_embeddings(model, ws, offsets, batch, out_embeddings);

    free(offsets);
    return rc;
}

int pplx_model_embed_into(const pplx_model_t *model, pplx_workspace_t *ws,
                          const int *token_ids, int n_tokens,
                          float *out_embedding)
{
    pplx_input_t input = { token_ids, n_tokens };
    return pplx_model_embed_batch(model, ws, &input, 1, out_embedding);
}

float *pplx_model_embed(const pplx_model_t *model, pplx_workspace_t *ws,
                        const int *token_ids, int n_tokens)
{
    if (!model || !ws || !token_ids || n_tokens <= 0) return NULL;

    int hidden = model->config.hidden_size;
    float *emb = malloc_floats((size_t)hidden);
    if (!emb) return NULL;

    if (pplx_model_embed_into(model, ws, token_ids, n_tokens, emb) != 0) {
        free(emb);
        return NULL;
    }
    return emb;
}

/* ========================================================================
 * Cosine similarity
 * ======================================================================== */

float pplx_cosine_similarity(const float *a, const float *b, int dim)
{
    float dot = 0.0f;
    for (int i = 0; i < dim; i++) dot += a[i] * b[i];
    return dot;
}