forked from ariannamethod/molequla
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmolequla.c
More file actions
5594 lines (5006 loc) · 210 KB
/
molequla.c
File metadata and controls
5594 lines (5006 loc) · 210 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
//go:build ignore
/*
* molequla.c
* A dependency-free, single-file, continually-learning GPT organism in pure C.
*
* Compile: gcc -O2 -o molequla molequla.c -lsqlite3 -lpthread -lm
* With BLAS: gcc -O2 -DUSE_BLAS -o molequla molequla.c -lsqlite3 -lpthread -lm -lopenblas
* macOS: gcc -O2 -DUSE_BLAS -o molequla molequla.c -lsqlite3 -lpthread -lm -framework Accelerate
*
* In the beginning there was nonames.txt.
* And it was good. Mostly. Sometimes cursed.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <time.h>
#include <pthread.h>
#include <unistd.h>
#include <signal.h>
#include <sys/stat.h>
#include <dirent.h>
#include <sqlite3.h>
#ifdef USE_BLAS
#ifdef __APPLE__
#ifndef ACCELERATE_NEW_LAPACK
#define ACCELERATE_NEW_LAPACK
#endif
#include <Accelerate/Accelerate.h>
#else
#include <cblas.h>
#endif
#define HAS_BLAS 1
/* Thread-local reusable buffer for packing row-per-vec into contiguous for BLAS */
static __thread double *blas_buf = NULL;
static __thread int blas_buf_cap = 0;
#else
#define HAS_BLAS 0
#endif
/* And lo, when the organism speaks, it shall not waste breath building
* a backward graph it will never use. grad_enabled is mercy for inference. */
static int grad_enabled = 1;
/* ============================================================
* 0) CONFIG
* ============================================================ */
typedef struct {
const char *corpus_path;
const char *db_path;
const char *ckpt_path;
int max_corpus_lines;
int max_line_chars;
int min_new_chars;
int tie_embeddings;
int n_layer;
int n_embd;
int n_head;
int block_size;
int warmup_steps;
int micro_steps;
double learning_rate;
double beta1, beta2, eps_adam;
double grad_clip;
int freeze_base_after_warmup;
int batch_size;
int delta_rank;
int max_delta_modules;
double delta_grow_prob;
double temperature;
int top_k;
double top_p;
double min_p; /* GPT-3/4 style: filter tokens below min_p * max_prob */
double typical_p; /* Typical sampling: prefer tokens with typical information content */
int max_gen_tokens;
int min_gen_tokens;
int repetition_guard;
int enable_bpe_after_chars;
int bpe_num_merges;
int bpe_retrain_every_chars;
double train_tick_seconds;
/* hybrid attention */
const char *head_types[8];
int n_head_types;
double hybrid_alpha_init;
/* gamma */
double gamma_sparsity_threshold;
/* noise immune system */
double noise_drift_threshold;
double gamma_min_magnitude; /* skip immune check when gamma direction is near-zero */
/* entropy temperature */
double entropy_low, entropy_high;
double entropy_temp_boost, entropy_temp_focus;
/* corpus field */
int corpus_gen_max_tokens;
double corpus_fade_k; /* sigmoid steepness for corpus->model transition */
double corpus_fade_threshold; /* entropy at which blend is 50/50 */
int cooccur_window_size; /* co-occurrence proximity window (Stanley-style) */
double user_boost_strength; /* how strongly user's recent words are boosted */
double user_boost_decay; /* per-generation decay of user word boost */
/* quantum buffer */
int qb_min_bytes;
double qb_min_novelty;
double qb_cooldown_seconds;
/* syntropy tracker (mathematical self-awareness) */
int syntropy_window; /* rolling window for syntropy trend */
double field_deviation_ceiling; /* KL divergence above this = drifted too far */
double field_deviation_floor; /* below this = not learning, just parroting */
double syntropy_lr_boost; /* boost LR when syntropy is rising */
double syntropy_lr_dampen; /* dampen LR when syntropy is falling */
double syntropy_delta_grow_boost; /* higher delta grow prob when syntropy is good */
/* Phase 1: cosine LR schedule */
double lr_min;
int max_total_steps;
int cosine_warmup_steps;
/* Phase 1: gradient accumulation */
int accum_steps;
/* Phase 3A: ontogenesis — growth stages */
/* Each stage: (corpus_chars_threshold, n_embd, n_layer, n_head) */
int growth_stages[6][4];
int n_growth_stages;
int freeze_after_growth_steps;
double post_growth_lr_scale; /* LR multiplier during freeze period */
/* frequency / presence penalty */
double freq_penalty;
double presence_penalty;
/* consciousness: per-token dissonance feedback */
double dissonance_ema_alpha; /* EMA smoothing for entropy within generation */
double dissonance_spike_k; /* temp multiplier when entropy spikes */
double dissonance_drop_k; /* temp multiplier when entropy drops */
double dissonance_spike_threshold; /* entropy/EMA ratio triggering spike */
double dissonance_drop_threshold; /* entropy/EMA ratio triggering drop */
/* consciousness: pattern breaking (anti-field generation) */
double anti_field_prob; /* probability of pure-model token (bypass corpus) */
int anti_field_min_step; /* don't anti-field before this many tokens */
/* consciousness: conscience (self-editing) */
int conscience_window; /* rolling window for generation entropy trend */
double conscience_decay; /* deltaAlphaScale reduction factor */
double conscience_recovery; /* deltaAlphaScale recovery factor */
double conscience_floor; /* minimum deltaAlphaScale */
} Config;
static Config CFG = {
.corpus_path = "nonames.txt",
.db_path = "memory.sqlite3",
.ckpt_path = "molequla.ckpt",
.max_corpus_lines = 8000,
.max_line_chars = 240,
.min_new_chars = 480,
.tie_embeddings = 1,
.n_layer = 1,
.n_embd = 16,
.n_head = 1,
.block_size = 96,
.warmup_steps = 1200,
.micro_steps = 32,
.learning_rate = 0.01,
.beta1 = 0.9, .beta2 = 0.99, .eps_adam = 1e-8,
.grad_clip = 1.0,
.freeze_base_after_warmup = 1,
.batch_size = 4,
.delta_rank = 8,
.max_delta_modules = 12,
.delta_grow_prob = 0.08,
.temperature = 0.85,
.top_k = 40,
.top_p = 0.92,
.min_p = 0.06,
.typical_p = 0.95,
.max_gen_tokens = 180,
.min_gen_tokens = 16,
.repetition_guard = 4,
.enable_bpe_after_chars = 20000,
.bpe_num_merges = 384,
.bpe_retrain_every_chars = 4000,
.train_tick_seconds = 0.25,
.head_types = {"content", NULL, NULL, NULL},
.n_head_types = 1,
.hybrid_alpha_init = 0.5,
.gamma_sparsity_threshold = 0.01,
.noise_drift_threshold = -0.1,
.gamma_min_magnitude = 1e-6,
.entropy_low = 0.5, .entropy_high = 1.5,
.entropy_temp_boost = 1.2, .entropy_temp_focus = 0.8,
.corpus_gen_max_tokens = 120,
.corpus_fade_k = 3.0,
.corpus_fade_threshold = 1.5,
.cooccur_window_size = 5,
.user_boost_strength = 0.3,
.user_boost_decay = 0.7,
.qb_min_bytes = 1024,
.qb_min_novelty = 0.15,
.qb_cooldown_seconds = 60.0,
.syntropy_window = 8,
.field_deviation_ceiling = 12.0,
.field_deviation_floor = 0.1,
.syntropy_lr_boost = 1.3,
.syntropy_lr_dampen = 0.6,
.syntropy_delta_grow_boost = 0.15,
.lr_min = 0.001,
.max_total_steps = 50000,
.cosine_warmup_steps = 200,
.accum_steps = 1,
/* Phase 3A: ontogenesis growth stages */
.growth_stages = {
{0, 16, 1, 1}, /* embryo: ~10K params */
{20000, 32, 1, 2}, /* infant: ~28K params */
{50000, 64, 2, 4}, /* child: ~154K params */
{200000, 128, 4, 4}, /* adolescent: ~1.1M params */
{350000, 224, 5, 8}, /* teen: ~4.1M params */
{500000, 320, 6, 8}, /* adult: ~10M params */
},
.n_growth_stages = 6,
.freeze_after_growth_steps = 500,
.post_growth_lr_scale = 0.3,
/* frequency / presence penalty */
.freq_penalty = 0.1,
.presence_penalty = 0.1,
/* consciousness defaults */
.dissonance_ema_alpha = 0.3,
.dissonance_spike_k = 0.8,
.dissonance_drop_k = 1.2,
.dissonance_spike_threshold = 1.5,
.dissonance_drop_threshold = 0.5,
.anti_field_prob = 0.05,
.anti_field_min_step = 8,
.conscience_window = 8,
.conscience_decay = 0.95,
.conscience_recovery = 1.005,
.conscience_floor = 0.3,
};
/* Head types helper: compute head_types array for a given number of heads.
* Writes into the global CFG.head_types and updates CFG.n_head_types.
* 1→content, 2→content+hybrid, 4→2c+2h, 8→4c+4h */
static void head_types_for_n_head(int n) {
if (n <= 0) n = 1;
if (n > 8) n = 8; /* max 8 slots in head_types array */
if (n <= 1) {
CFG.head_types[0] = "content";
CFG.n_head_types = 1;
} else if (n == 2) {
CFG.head_types[0] = "content";
CFG.head_types[1] = "hybrid";
CFG.n_head_types = 2;
} else {
/* majority content, rest hybrid: 5→3c+2h, 8→4c+4h */
int half = (n + 1) / 2;
for (int i = 0; i < half; i++) CFG.head_types[i] = "content";
for (int i = half; i < n; i++) CFG.head_types[i] = "hybrid";
CFG.n_head_types = n;
}
}
/* ============================================================
* 0.5) RNG — xorshift64, because rand() is for cowards
* ============================================================ */
static unsigned long long rng_state = 42;
static double rand_uniform(void) {
rng_state ^= rng_state << 13;
rng_state ^= rng_state >> 7;
rng_state ^= rng_state << 17;
return (double)(rng_state & 0x7FFFFFFFFFFFFFFFULL) / (double)0x7FFFFFFFFFFFFFFFULL;
}
static double rand_normal(void) {
double u1 = rand_uniform();
double u2 = rand_uniform();
if (u1 < 1e-15) u1 = 1e-15;
return sqrt(-2.0 * log(u1)) * cos(2.0 * M_PI * u2);
}
static int rand_int(int n) {
return (int)(rand_uniform() * n) % n;
}
/* ============================================================
* 0.6) DYNAMIC ARRAYS
* ============================================================ */
typedef struct { char **items; int len, cap; } StrArr;
typedef struct { int *items; int len, cap; } IntArr;
static void sa_push(StrArr *a, const char *s) {
if (a->len >= a->cap) {
a->cap = a->cap ? a->cap * 2 : 16;
void *tmp = realloc(a->items, sizeof(char*) * a->cap);
if (!tmp) { fprintf(stderr, "[sa_push] realloc failed\n"); return; }
a->items = tmp;
}
a->items[a->len++] = strdup(s);
}
static void sa_free(StrArr *a) {
for (int i = 0; i < a->len; i++) free(a->items[i]);
free(a->items);
a->items = NULL; a->len = a->cap = 0;
}
static void ia_push(IntArr *a, int v) {
if (a->len >= a->cap) {
a->cap = a->cap ? a->cap * 2 : 16;
void *tmp = realloc(a->items, sizeof(int) * a->cap);
if (!tmp) { fprintf(stderr, "[ia_push] realloc failed\n"); return; }
a->items = tmp;
}
a->items[a->len++] = v;
}
static void ia_free(IntArr *a) {
free(a->items);
a->items = NULL; a->len = a->cap = 0;
}
/* ============================================================
* 1) ARENA ALLOCATOR — for autograd graphs
* ============================================================ */
#define ARENA_SIZE (512 * 1024 * 1024) /* 512 MB — child stage (embd=64) needs >256 MB */
typedef struct {
char *buf;
size_t used, cap;
} Arena;
static Arena arena_new(size_t cap) {
Arena a;
a.buf = malloc(cap);
a.used = 0;
a.cap = cap;
return a;
}
static void *arena_alloc(Arena *a, size_t size) {
size = (size + 7) & ~(size_t)7; /* align to 8 bytes */
if (a->used + size > a->cap) {
fprintf(stderr, "arena: out of memory (%zu/%zu)\n", a->used + size, a->cap);
exit(1);
}
void *p = a->buf + a->used;
a->used += size;
memset(p, 0, size);
return p;
}
static void arena_reset(Arena *a) { a->used = 0; }
static void arena_destroy(Arena *a) { free(a->buf); }
static Arena G_arena; /* global arena for autograd */
/* ============================================================
* 2) AUTOGRAD — Node = Vec or Scalar (len=1)
* ============================================================ */
typedef struct Node Node;
typedef void (*BackFn)(Node *self);
struct Node {
double *data;
double *grad;
int len;
Node **children;
int n_children;
BackFn backward;
void *ctx;
int visited;
};
static Node *node_new(int len) {
Node *n = arena_alloc(&G_arena, sizeof(Node));
n->data = arena_alloc(&G_arena, sizeof(double) * len);
n->grad = arena_alloc(&G_arena, sizeof(double) * len);
n->len = len;
return n;
}
static void node_set_children(Node *n, Node **kids, int count) {
n->children = arena_alloc(&G_arena, sizeof(Node*) * count);
memcpy(n->children, kids, sizeof(Node*) * count);
n->n_children = count;
}
/* Wrap persistent weight data as a node (data/grad are NOT arena-allocated) */
static Node *node_wrap(double *data, double *grad, int len) {
Node *n = arena_alloc(&G_arena, sizeof(Node));
n->data = data;
n->grad = grad;
n->len = len;
return n;
}
/* --- Vec ops --- */
typedef struct { Node *a, *b; int len; } BinCtx;
static void back_add(Node *self) {
BinCtx *c = self->ctx;
for (int i = 0; i < c->len; i++) {
c->a->grad[i] += self->grad[i];
c->b->grad[i] += self->grad[i];
}
}
static Node *vec_add(Node *a, Node *b) {
int n = a->len;
Node *out = node_new(n);
for (int i = 0; i < n; i++) out->data[i] = a->data[i] + b->data[i];
if (grad_enabled) {
BinCtx *c = arena_alloc(&G_arena, sizeof(BinCtx));
c->a = a; c->b = b; c->len = n;
out->ctx = c;
out->backward = back_add;
Node *kids[] = {a, b};
node_set_children(out, kids, 2);
}
return out;
}
static void back_sub(Node *self) {
BinCtx *c = self->ctx;
for (int i = 0; i < c->len; i++) {
c->a->grad[i] += self->grad[i];
c->b->grad[i] -= self->grad[i];
}
}
static Node *vec_sub(Node *a, Node *b) {
int n = a->len;
Node *out = node_new(n);
for (int i = 0; i < n; i++) out->data[i] = a->data[i] - b->data[i];
if (grad_enabled) {
BinCtx *c = arena_alloc(&G_arena, sizeof(BinCtx));
c->a = a; c->b = b; c->len = n;
out->ctx = c;
out->backward = back_sub;
Node *kids[] = {a, b};
node_set_children(out, kids, 2);
}
return out;
}
static void back_mul_vec(Node *self) {
BinCtx *c = self->ctx;
for (int i = 0; i < c->len; i++) {
c->a->grad[i] += c->b->data[i] * self->grad[i];
c->b->grad[i] += c->a->data[i] * self->grad[i];
}
}
static Node *vec_mul(Node *a, Node *b) {
int n = a->len;
Node *out = node_new(n);
for (int i = 0; i < n; i++) out->data[i] = a->data[i] * b->data[i];
if (grad_enabled) {
BinCtx *c = arena_alloc(&G_arena, sizeof(BinCtx));
c->a = a; c->b = b; c->len = n;
out->ctx = c;
out->backward = back_mul_vec;
Node *kids[] = {a, b};
node_set_children(out, kids, 2);
}
return out;
}
typedef struct { Node *a; double s; int len; } ScaleCtx;
static void back_scale(Node *self) {
ScaleCtx *c = self->ctx;
for (int i = 0; i < c->len; i++)
c->a->grad[i] += c->s * self->grad[i];
}
static Node *vec_scale(Node *a, double s) {
int n = a->len;
Node *out = node_new(n);
for (int i = 0; i < n; i++) out->data[i] = a->data[i] * s;
if (grad_enabled) {
ScaleCtx *c = arena_alloc(&G_arena, sizeof(ScaleCtx));
c->a = a; c->s = s; c->len = n;
out->ctx = c;
out->backward = back_scale;
Node *kids[] = {a};
node_set_children(out, kids, 1);
}
return out;
}
static void back_relu(Node *self) {
BinCtx *c = self->ctx; /* reuse: a = input */
for (int i = 0; i < c->len; i++)
if (c->a->data[i] > 0) c->a->grad[i] += self->grad[i];
}
static Node *vec_relu(Node *a) {
int n = a->len;
Node *out = node_new(n);
for (int i = 0; i < n; i++) out->data[i] = a->data[i] > 0 ? a->data[i] : 0;
if (grad_enabled) {
BinCtx *c = arena_alloc(&G_arena, sizeof(BinCtx));
c->a = a; c->len = n;
out->ctx = c;
out->backward = back_relu;
Node *kids[] = {a};
node_set_children(out, kids, 1);
}
return out;
}
/* SiLU (Swish): silu(x) = x * sigmoid(x) — real SwiGLU activation */
static void back_silu(Node *self) {
BinCtx *c = self->ctx;
for (int i = 0; i < c->len; i++) {
double x = c->a->data[i];
double sig = 1.0 / (1.0 + exp(-x));
c->a->grad[i] += (sig + x * sig * (1.0 - sig)) * self->grad[i];
}
}
static Node *vec_silu(Node *a) {
int n = a->len;
Node *out = node_new(n);
for (int i = 0; i < n; i++) {
double x = a->data[i];
double sig = 1.0 / (1.0 + exp(-x));
out->data[i] = x * sig;
}
if (grad_enabled) {
BinCtx *c = arena_alloc(&G_arena, sizeof(BinCtx));
c->a = a; c->len = n;
out->ctx = c;
out->backward = back_silu;
Node *kids[] = {a};
node_set_children(out, kids, 1);
}
return out;
}
/* Dot product: returns scalar (len=1) */
typedef struct { Node *a, *b; int len; } DotCtx;
static void back_dot(Node *self) {
DotCtx *c = self->ctx;
double g = self->grad[0];
for (int i = 0; i < c->len; i++) {
c->a->grad[i] += c->b->data[i] * g;
c->b->grad[i] += c->a->data[i] * g;
}
}
static Node *vec_dot(Node *a, Node *b) {
int n = a->len;
double val = 0;
for (int i = 0; i < n; i++) val += a->data[i] * b->data[i];
Node *out = node_new(1);
out->data[0] = val;
if (grad_enabled) {
DotCtx *c = arena_alloc(&G_arena, sizeof(DotCtx));
c->a = a; c->b = b; c->len = n;
out->ctx = c;
out->backward = back_dot;
Node *kids[] = {a, b};
node_set_children(out, kids, 2);
}
return out;
}
/* MeanSq: scalar = mean(x^2) */
typedef struct { Node *a; int len; } MeanSqCtx;
static void back_meansq(Node *self) {
MeanSqCtx *c = self->ctx;
double g = self->grad[0];
double nf = (double)c->len;
for (int i = 0; i < c->len; i++)
c->a->grad[i] += (2.0 * c->a->data[i] / nf) * g;
}
static Node *vec_meansq(Node *a) {
int n = a->len;
double val = 0;
for (int i = 0; i < n; i++) val += a->data[i] * a->data[i];
val /= (double)n;
Node *out = node_new(1);
out->data[0] = val;
if (grad_enabled) {
MeanSqCtx *c = arena_alloc(&G_arena, sizeof(MeanSqCtx));
c->a = a; c->len = n;
out->ctx = c;
out->backward = back_meansq;
Node *kids[] = {a};
node_set_children(out, kids, 1);
}
return out;
}
/* Slice: out = a[start:end] */
typedef struct { Node *a; int start, end; } SliceCtx;
static void back_slice(Node *self) {
SliceCtx *c = self->ctx;
for (int i = 0, j = c->start; j < c->end; i++, j++)
c->a->grad[j] += self->grad[i];
}
static Node *vec_slice(Node *a, int start, int end) {
int n = end - start;
Node *out = node_new(n);
memcpy(out->data, a->data + start, sizeof(double) * n);
if (grad_enabled) {
SliceCtx *c = arena_alloc(&G_arena, sizeof(SliceCtx));
c->a = a; c->start = start; c->end = end;
out->ctx = c;
out->backward = back_slice;
Node *kids[] = {a};
node_set_children(out, kids, 1);
}
return out;
}
/* Element: extract one element as scalar node (len=1) with gradient flow */
/* And lo, one number shall be plucked from the vector, and gradients shall follow. */
typedef struct { Node *a; int idx; } ElemCtx;
static void back_elem(Node *self) {
ElemCtx *c = self->ctx;
c->a->grad[c->idx] += self->grad[0];
}
static Node *vec_element(Node *a, int idx) {
Node *out = node_new(1);
out->data[0] = a->data[idx];
if (grad_enabled) {
ElemCtx *c = arena_alloc(&G_arena, sizeof(ElemCtx));
c->a = a; c->idx = idx;
out->ctx = c;
out->backward = back_elem;
Node *kids[] = {a};
node_set_children(out, kids, 1);
}
return out;
}
/* Scalar mul: s1 * s2 (both scalar nodes) */
static void back_scalar_mul(Node *self) {
Node *a = self->children[0], *b = self->children[1];
a->grad[0] += b->data[0] * self->grad[0];
b->grad[0] += a->data[0] * self->grad[0];
}
static Node *scalar_mul(Node *a, Node *b) {
Node *out = node_new(1);
out->data[0] = a->data[0] * b->data[0];
if (grad_enabled) {
out->backward = back_scalar_mul;
Node *kids[] = {a, b};
node_set_children(out, kids, 2);
}
return out;
}
/* Concat: join multiple vecs */
typedef struct { Node **vecs; int n_vecs; int *offsets; } ConcatCtx;
static void back_concat(Node *self) {
ConcatCtx *c = self->ctx;
for (int v = 0; v < c->n_vecs; v++) {
int off = c->offsets[v];
int len = c->vecs[v]->len;
for (int i = 0; i < len; i++)
c->vecs[v]->grad[i] += self->grad[off + i];
}
}
static Node *vec_concat(Node **vecs, int n_vecs) {
int total = 0;
for (int i = 0; i < n_vecs; i++) total += vecs[i]->len;
Node *out = node_new(total);
int off = 0;
int *offsets = arena_alloc(&G_arena, sizeof(int) * n_vecs);
for (int i = 0; i < n_vecs; i++) {
offsets[i] = off;
memcpy(out->data + off, vecs[i]->data, sizeof(double) * vecs[i]->len);
off += vecs[i]->len;
}
if (grad_enabled) {
ConcatCtx *c = arena_alloc(&G_arena, sizeof(ConcatCtx));
c->vecs = arena_alloc(&G_arena, sizeof(Node*) * n_vecs);
memcpy(c->vecs, vecs, sizeof(Node*) * n_vecs);
c->n_vecs = n_vecs;
c->offsets = offsets;
out->ctx = c;
out->backward = back_concat;
node_set_children(out, vecs, n_vecs);
}
return out;
}
/* Scalar add */
static void back_scalar_add(Node *self) {
double g = self->grad[0];
self->children[0]->grad[0] += g;
self->children[1]->grad[0] += g;
}
static Node *scalar_add(Node *a, Node *b) {
Node *out = node_new(1);
out->data[0] = a->data[0] + b->data[0];
if (grad_enabled) {
out->backward = back_scalar_add;
Node *kids[] = {a, b};
node_set_children(out, kids, 2);
}
return out;
}
/* Scalar mul by float */
static void back_scalar_mulf(Node *self) {
ScaleCtx *c = self->ctx;
c->a->grad[0] += c->s * self->grad[0];
}
static Node *scalar_mulf(Node *a, double f) {
Node *out = node_new(1);
out->data[0] = a->data[0] * f;
if (grad_enabled) {
ScaleCtx *c = arena_alloc(&G_arena, sizeof(ScaleCtx));
c->a = a; c->s = f;
out->ctx = c;
out->backward = back_scalar_mulf;
Node *kids[] = {a};
node_set_children(out, kids, 1);
}
return out;
}
/* Scalar sigmoid: σ(x) = 1/(1+exp(-x)) with gradient flow */
static void back_scalar_sigmoid(Node *self) {
double sig = self->data[0];
self->children[0]->grad[0] += sig * (1.0 - sig) * self->grad[0];
}
static Node *scalar_sigmoid(Node *a) {
Node *out = node_new(1);
out->data[0] = 1.0 / (1.0 + exp(-a->data[0]));
if (grad_enabled) {
out->backward = back_scalar_sigmoid;
Node *kids[] = {a};
node_set_children(out, kids, 1);
}
return out;
}
/* Scalar add float: a + f (constant, gradient only to a) */
static Node *scalar_addf(Node *a, double f) {
Node *out = node_new(1);
out->data[0] = a->data[0] + f;
if (grad_enabled) {
ScaleCtx *c = arena_alloc(&G_arena, sizeof(ScaleCtx));
c->a = a; c->s = 1.0;
out->ctx = c;
out->backward = back_scalar_mulf; /* same: grad flows 1:1 to a */
Node *kids[] = {a};
node_set_children(out, kids, 1);
}
return out;
}
/* --- Backward (topological sort) --- */
/* And lo, the graph shall be walked backwards, like a salmon with regrets. */
#define MAX_TOPO 262144
static void backward(Node *root) {
/* Heap-allocated to avoid stack overflow in threads */
Node **topo = (Node **)malloc(MAX_TOPO * sizeof(Node *));
Node **stack = (Node **)malloc(MAX_TOPO * sizeof(Node *));
int topo_len = 0;
int stack_len = 0;
stack[stack_len++] = root;
while (stack_len > 0) {
Node *n = stack[stack_len - 1];
if (n->visited == 1) {
stack_len--;
if (n->visited != 2) {
n->visited = 2;
if (topo_len < MAX_TOPO) topo[topo_len++] = n;
}
continue;
}
n->visited = 1;
for (int i = 0; i < n->n_children; i++) {
if (n->children[i] && n->children[i]->visited == 0) {
if (stack_len < MAX_TOPO) stack[stack_len++] = n->children[i];
}
}
}
root->grad[0] = 1.0;
for (int i = topo_len - 1; i >= 0; i--) {
if (topo[i]->backward)
topo[i]->backward(topo[i]);
}
free(topo);
free(stack);
}
/* ============================================================
* 3) HIGH-LEVEL OPS
* ============================================================ */
/* Persistent weight matrix (NOT arena allocated) */
typedef struct {
double **row_data; /* [nout][nin] */
double **row_grad; /* [nout][nin] */
int nout, nin;
} MatrixParam;
static MatrixParam *mat_new(int nout, int nin, double std) {
MatrixParam *m = calloc(1, sizeof(MatrixParam));
m->nout = nout; m->nin = nin;
m->row_data = calloc(nout, sizeof(double*));
m->row_grad = calloc(nout, sizeof(double*));
for (int i = 0; i < nout; i++) {
m->row_data[i] = calloc(nin, sizeof(double));
m->row_grad[i] = calloc(nin, sizeof(double));
for (int j = 0; j < nin; j++)
m->row_data[i][j] = rand_normal() * std;
}
return m;
}
static void mat_grow_rows(MatrixParam *m, int new_nout, double std) {
if (new_nout <= m->nout) return;
void *tmp_data = realloc(m->row_data, sizeof(double*) * new_nout);
void *tmp_grad = realloc(m->row_grad, sizeof(double*) * new_nout);
if (!tmp_data || !tmp_grad) {
fprintf(stderr, "[mat_grow_rows] realloc failed\n");
if (tmp_data) m->row_data = tmp_data;
if (tmp_grad) m->row_grad = tmp_grad;
return;
}
m->row_data = tmp_data;
m->row_grad = tmp_grad;
for (int i = m->nout; i < new_nout; i++) {
m->row_data[i] = calloc(m->nin, sizeof(double));
m->row_grad[i] = calloc(m->nin, sizeof(double));
for (int j = 0; j < m->nin; j++)
m->row_data[i][j] = rand_normal() * std;
}
m->nout = new_nout;
}
/* Grow columns (input dimension) of a matrix: extend each row with gaussian noise */
static void mat_grow_cols(MatrixParam *m, int new_nin, double std) {
if (new_nin <= m->nin) return;
for (int i = 0; i < m->nout; i++) {
void *tmp_d = realloc(m->row_data[i], sizeof(double) * new_nin);
void *tmp_g = realloc(m->row_grad[i], sizeof(double) * new_nin);
if (!tmp_d || !tmp_g) {
fprintf(stderr, "[mat_grow_cols] realloc failed at row %d\n", i);
if (tmp_d) m->row_data[i] = tmp_d;
if (tmp_g) m->row_grad[i] = tmp_g;
return;
}
m->row_data[i] = tmp_d;
m->row_grad[i] = tmp_g;
for (int j = m->nin; j < new_nin; j++) {
m->row_data[i][j] = rand_normal() * std;
m->row_grad[i][j] = 0.0;
}
}
m->nin = new_nin;
}
/* Grow both dimensions: cols first (so new rows get full width), then rows */
static void mat_grow(MatrixParam *m, int new_nout, int new_nin, double std) {
mat_grow_cols(m, new_nin, std);
mat_grow_rows(m, new_nout, std);
}
/* Matvec: out = M @ x */
typedef struct { MatrixParam *m; Node *x; int nout, nin; } MatvecCtx;
static void back_matvec(Node *self) {
MatvecCtx *c = self->ctx;
for (int i = 0; i < c->nout; i++) {
double g = self->grad[i];
for (int j = 0; j < c->nin; j++) {
c->m->row_grad[i][j] += g * c->x->data[j];
c->x->grad[j] += g * c->m->row_data[i][j];
}
}
}
static Node *mat_matvec(MatrixParam *m, Node *x) {
int nout = m->nout, nin = x->len;
Node *out = node_new(nout);
#if HAS_BLAS
if (nout * nin >= 256) {
/* Pack row pointers into contiguous thread-local buffer for cblas_dgemv */
int needed = nout * nin;
if (needed > blas_buf_cap) {
free(blas_buf);
blas_buf = malloc(sizeof(double) * needed);
blas_buf_cap = needed;
}
for (int i = 0; i < nout; i++)
memcpy(blas_buf + i * nin, m->row_data[i], nin * sizeof(double));
cblas_dgemv(CblasRowMajor, CblasNoTrans, nout, nin,
1.0, blas_buf, nin, x->data, 1, 0.0, out->data, 1);
} else
#endif
{
for (int i = 0; i < nout; i++) {
double s = 0;
for (int j = 0; j < nin; j++) s += m->row_data[i][j] * x->data[j];
out->data[i] = s;
}
}
if (grad_enabled) {
/* Wrap each row as a node for the graph */
Node **kids = arena_alloc(&G_arena, sizeof(Node*) * (nout + 1));
for (int i = 0; i < nout; i++)
kids[i] = node_wrap(m->row_data[i], m->row_grad[i], nin);
kids[nout] = x;
node_set_children(out, kids, nout + 1);
MatvecCtx *c = arena_alloc(&G_arena, sizeof(MatvecCtx));
c->m = m; c->x = x; c->nout = nout; c->nin = nin;
out->ctx = c;
out->backward = back_matvec;
}
return out;
}
/* RMSNorm */
typedef struct { Node *x; double scale_val; double ms_data; int len; } RMSCtx;
static void back_rmsnorm(Node *self) {
RMSCtx *c = self->ctx;
double s = c->scale_val;
double ds = -0.5 * pow(c->ms_data + 1e-5, -1.5);
double cross = 0;
for (int j = 0; j < c->len; j++) cross += self->grad[j] * c->x->data[j];
double nf = (double)c->len;
for (int i = 0; i < c->len; i++) {
c->x->grad[i] += s * self->grad[i];
c->x->grad[i] += cross * ds * (2.0 * c->x->data[i] / nf);
}
}
static Node *rmsnorm(Node *x) {
int n = x->len;
double ms = 0;
for (int i = 0; i < n; i++) ms += x->data[i] * x->data[i];
ms /= (double)n;
double scale = pow(ms + 1e-5, -0.5);
Node *out = node_new(n);
for (int i = 0; i < n; i++) out->data[i] = x->data[i] * scale;
if (grad_enabled) {
RMSCtx *c = arena_alloc(&G_arena, sizeof(RMSCtx));
c->x = x; c->scale_val = scale; c->ms_data = ms; c->len = n;
out->ctx = c;
out->backward = back_rmsnorm;
Node *kids[] = {x};
node_set_children(out, kids, 1);