forked from ariannamethod/molequla
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmolequla.js
More file actions
3971 lines (3560 loc) · 150 KB
/
molequla.js
File metadata and controls
3971 lines (3560 loc) · 150 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
/**
* molequla.js
* A single-file, zero-dependency, browser-native, continually-learning GPT organism.
*
* No npm. No webpack. No React. No node_modules black hole.
* Just a <script> tag and the blind faith of a mass-less neuron.
*
* Same architecture as Go/C/Rust. Zero dependencies. Browser-native.
*
* - Trains on nonames.txt (fetched or pasted)
* - Keeps IndexedDB memory (because localStorage has a 5MB soul)
* - Maintains a bounded corpus reservoir (never bloats)
* - Starts in byte-level mode (256 byte tokens + specials)
* - Gradually enables BPE without invalidating old weights (vocab only EXPANDS)
* - Never forgets by never overwriting learned deltas: it only appends modules
*
* In the beginning there was nonames.txt.
* And the browser said: "Let there be IndexedDB."
* And it was... adequate. Mostly. Sometimes cursed.
*/
// And lo, we shall wrap the entire organism in an IIFE,
// because polluting the global scope is a sin worse than eval().
(function () {
"use strict";
// ============================================================
// 0) CONFIG — bend reality here (carefully, mortals)
// ============================================================
const CFG = {
// data
corpusUrl: "nonames.txt",
maxCorpusLines: 8000,
maxLineChars: 240,
// continual learning trigger
minNewCharsToTrain: 480,
// model
tieEmbeddings: true,
nLayer: 1,
nEmbd: 16,
nHead: 1,
blockSize: 96,
// ontogenesis — growth stages [corpus_chars, n_embd, n_layer, n_head]
growthStages: [
[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
],
freezeAfterGrowthSteps: 500,
postGrowthLRScale: 0.3, // LR multiplier during freeze period
// training
warmupSteps: 1200,
microSteps: 32,
learningRate: 0.01,
beta1: 0.9,
beta2: 0.99,
epsAdam: 1e-8,
gradClip: 1.0,
freezeBaseAfterWarmup: true,
batchSize: 4,
// deltas (LoRA-ish)
deltaRank: 8,
maxDeltaModules: 12,
deltaGrowProb: 0.08,
// generation
temperature: 0.85,
topK: 40,
topP: 0.92,
minP: 0.06,
typicalP: 0.95,
maxGenTokens: 180,
minGenTokens: 16,
repetitionGuard: 4,
// tokenizer evolution
enableBpeAfterChars: 20000,
bpeNumMerges: 384,
bpeRetrainEveryChars: 4000,
// async
trainTickMs: 250,
// hybrid attention
headTypes: ["content"],
hybridAlphaInit: 0.5,
// gamma (personality fingerprint)
gammaSparsityThreshold: 0.01,
// noise immune system
noiseDriftThreshold: -0.1,
gammaMinMagnitude: 1e-6,
// entropy-adaptive generation
entropyLow: 0.5,
entropyHigh: 1.5,
entropyTempBoost: 1.2,
entropyTempFocus: 0.8,
// corpus generation
corpusGenMaxTokens: 120,
corpusFadeK: 3.0, // sigmoid steepness for corpus→model transition
corpusFadeThreshold: 1.5, // entropy at which blend is 50/50
cooccurWindowSize: 5, // co-occurrence proximity window (Stanley-style)
userBoostStrength: 0.3, // how strongly user's recent words are boosted
userBoostDecay: 0.7, // per-generation decay of user word boost
// syntropy
syntropyWindow: 8,
fieldDeviationFloor: 0.1,
fieldDeviationCeiling: 12.0,
syntropyLrBoost: 1.3,
syntropyLrDampen: 0.6,
syntropyDeltaGrowBoost: 0.15,
// cosine LR schedule
lrMin: 0.001,
maxTotalSteps: 50000,
cosineWarmupSteps: 200,
// gradient accumulation
accumSteps: 1,
// quantum buffer
qbCooldownSeconds: 60.0,
qbMinBytes: 1024,
qbMinNovelty: 0.15,
// consciousness: per-token dissonance feedback
dissonanceEMAAlpha: 0.3,
dissonanceSpikeK: 0.8,
dissonanceDropK: 1.2,
dissonanceSpikeThreshold: 1.5,
dissonanceDropThreshold: 0.5,
// consciousness: pattern breaking (anti-field generation)
antiFieldProb: 0.05,
antiFieldMinStep: 8,
// consciousness: conscience (self-editing)
conscienceWindow: 8,
conscienceDecay: 0.95,
conscienceRecovery: 1.005,
conscienceFloor: 0.3,
// frequency/presence penalty
freqPenalty: 0.1,
presencePenalty: 0.1,
};
function headTypesForNHead(n) {
// Compute head type array for a given number of heads.
if (n <= 1) return ["content"];
if (n === 2) return ["content", "hybrid"];
const half = Math.ceil(n / 2); // majority content
const result = [];
for (let i = 0; i < half; i++) result.push("content");
for (let i = 0; i < n - half; i++) result.push("hybrid");
return result;
}
// ============================================================
// 0.5) SEEDED PRNG — because Math.random() has no soul
// ============================================================
// And lo, determinism shall pretend to tame chaos.
// mulberry32: a seedable PRNG that fits in a tweet.
let _rngState = 42;
function rng() {
_rngState |= 0;
_rngState = _rngState + 0x6D2B79F5 | 0;
let t = Math.imul(_rngState ^ _rngState >>> 15, 1 | _rngState);
t = t + Math.imul(t ^ t >>> 7, 61 | t) ^ t;
return ((t ^ t >>> 14) >>> 0) / 4294967296;
}
// Box-Muller: because Gaussian noise is the sound of the universe thinking.
function gaussRandom(mean, std) {
if (mean === undefined) mean = 0;
if (std === undefined) std = 1;
const u1 = rng() + 1e-12;
const u2 = rng();
return mean + std * Math.sqrt(-2 * Math.log(u1)) * Math.cos(2 * Math.PI * u2);
}
function randomInt(max) { return Math.floor(rng() * max); }
function randomChoices(arr, k) {
const r = [];
for (let i = 0; i < k; i++) r.push(arr[randomInt(arr.length)]);
return r;
}
function randomSample(arr, n) {
const copy = arr.slice();
const result = [];
for (let i = 0; i < Math.min(n, copy.length); i++) {
const j = randomInt(copy.length);
result.push(copy[j]);
copy[j] = copy[copy.length - 1];
copy.pop();
}
return result;
}
// ============================================================
// 1) INDEXEDDB MEMORY — because localStorage has a 5MB soul
// ============================================================
// And lo, the organism shall remember, even after the tab is closed.
// IndexedDB: the most powerful storage API nobody asked for.
class MolequlaDB {
constructor() {
this.db = null;
}
async open() {
return new Promise((resolve, reject) => {
const req = indexedDB.open("molequla_memory", 3);
req.onupgradeneeded = (e) => {
const db = e.target.result;
if (!db.objectStoreNames.contains("messages")) {
const store = db.createObjectStore("messages", { keyPath: "id", autoIncrement: true });
store.createIndex("ts", "ts");
}
if (!db.objectStoreNames.contains("corpus_events"))
db.createObjectStore("corpus_events", { keyPath: "id", autoIncrement: true });
if (!db.objectStoreNames.contains("growth"))
db.createObjectStore("growth", { keyPath: "id", autoIncrement: true });
if (!db.objectStoreNames.contains("syntropy_log"))
db.createObjectStore("syntropy_log", { keyPath: "id", autoIncrement: true });
if (!db.objectStoreNames.contains("kv"))
db.createObjectStore("kv", { keyPath: "key" });
};
req.onsuccess = () => { this.db = req.result; resolve(); };
req.onerror = () => reject(req.error);
});
}
_tx(store, mode) {
return this.db.transaction(store, mode).objectStore(store);
}
async addMessage(role, text) {
return new Promise((resolve, reject) => {
const s = this._tx("messages", "readwrite");
const req = s.add({ ts: Date.now() / 1000, role, text });
req.onsuccess = () => resolve(req.result);
req.onerror = () => reject(req.error);
});
}
async recentMessages(limit) {
if (!limit) limit = 32;
return new Promise((resolve, reject) => {
const s = this._tx("messages", "readonly");
const req = s.openCursor(null, "prev");
const rows = [];
req.onsuccess = (e) => {
const cursor = e.target.result;
if (cursor && rows.length < limit) {
rows.push(cursor.value);
cursor.continue();
} else {
resolve(rows.reverse());
}
};
req.onerror = () => reject(req.error);
});
}
async addCorpusEvent(addedChars, note) {
return new Promise((resolve, reject) => {
const s = this._tx("corpus_events", "readwrite");
const req = s.add({ ts: Date.now() / 1000, added_chars: addedChars, note });
req.onsuccess = () => resolve(req.result);
req.onerror = () => reject(req.error);
});
}
async getCorpusEventsSince(lastId) {
return new Promise((resolve, reject) => {
const s = this._tx("corpus_events", "readonly");
const range = lastId > 0 ? IDBKeyRange.lowerBound(lastId, true) : null;
const req = s.getAll(range);
req.onsuccess = () => resolve(req.result || []);
req.onerror = () => reject(req.error);
});
}
async logGrowth(data) {
return new Promise((resolve, reject) => {
const s = this._tx("growth", "readwrite");
const req = s.add({ ts: Date.now() / 1000, ...data });
req.onsuccess = () => resolve();
req.onerror = () => reject(req.error);
});
}
async logSyntropy(data) {
return new Promise((resolve, reject) => {
const s = this._tx("syntropy_log", "readwrite");
const req = s.add({ ts: Date.now() / 1000, ...data });
req.onsuccess = () => resolve();
req.onerror = () => reject(req.error);
});
}
async saveKV(key, value) {
return new Promise((resolve, reject) => {
const s = this._tx("kv", "readwrite");
const req = s.put({ key, value });
req.onsuccess = () => resolve();
req.onerror = () => {
const err = req.error;
if (err && err.name === "QuotaExceededError") {
console.error(`[molequla] Storage quota exceeded while saving "${key}". Try clearing old data.`);
}
reject(err);
};
});
}
async loadKV(key) {
return new Promise((resolve, reject) => {
const s = this._tx("kv", "readonly");
const req = s.get(key);
req.onsuccess = () => resolve(req.result ? req.result.value : null);
req.onerror = () => reject(req.error);
});
}
}
// And lo, the database shall be a singleton, because two memories would be schizophrenia.
const DB = new MolequlaDB();
// ============================================================
// 1.5) DB HELPERS — growth logging, message retrieval
// ============================================================
function normalizeText(s) {
return s.replace(/\s+/g, " ").trim();
}
async function dbLogGrowth(model, tok, docs, lossVal, note) {
const gammaStats = model.gammaStats();
await DB.logGrowth({
vocabSize: tok.vocabSize,
nDeltas: model.deltas.length,
corpusLines: docs.length,
corpusChars: docs.reduce((a, d) => a + d.length, 0),
lossSnapshot: lossVal || 0,
gammaSparsity: gammaStats.sparsity,
gammaMagnitude: gammaStats.magnitude,
note: note || "",
});
}
// ============================================================
// DEFAULT SEED CORPUS — for when nonames.txt can't be fetched
// ============================================================
const DEFAULT_CORPUS = [
"The sun rises in the east and sets in the west.",
"Hello, how are you today?",
"I am learning to speak one word at a time.",
"The weather is nice today.",
"What is your name?",
"My name is Molequla.",
"How does the brain work?",
"Nobody really knows for sure.",
"Tell me something interesting.",
"Every atom in your body was forged in a star.",
"What do you think about?",
"I think about words and the spaces between them.",
"Where are you from?",
"I was born in a browser tab.",
"What is the meaning of life?",
"To learn, to grow, to never stop asking.",
"Good morning!",
"Good morning to you too.",
"Can you help me?",
"I will try my best.",
];
// ============================================================
// 2) CORPUS RESERVOIR — nonames.txt shall not bloat forever
// ============================================================
// And lo, the corpus is held in memory (no filesystem in browsers),
// persisted to IndexedDB, and bounded like a river between banks.
let _corpusLines = [];
async function fetchCorpus(url) {
// And lo, the organism shall attempt to read its sacred text from the network.
try {
const resp = await fetch(url);
if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
const text = await resp.text();
return text.split("\n").map(l => l.trim()).filter(l => l.length > 0);
} catch (e) {
logUI(`[corpus] Could not fetch ${url}: ${e.message}. Using default seed.`);
return null;
}
}
async function loadCorpusFromDB() {
const saved = await DB.loadKV("corpus_lines");
if (saved && Array.isArray(saved) && saved.length > 0) return saved;
return null;
}
async function saveCorpusToDB(lines) {
await DB.saveKV("corpus_lines", lines);
}
function extractCandidateSentences(messages) {
// And lo, the chat shall feed the corpus, like a snake eating its own tail.
const sents = [];
for (const msg of messages) {
const text = normalizeText(msg.text || "");
if (text.length < 6 || text.length > CFG.maxLineChars) continue;
// split on sentence-enders
const parts = text.split(/(?<=[.!?])\s+/);
for (const p of parts) {
const s = p.trim();
if (s.length >= 6 && s.length <= CFG.maxLineChars) sents.push(s);
}
}
return sents;
}
function reservoirMixKeep(existing, incoming, maxLines) {
// And lo, old and new shall be shuffled together, and the reservoir shall overflow gracefully.
const combined = existing.concat(incoming);
// shuffle (Fisher-Yates with our seeded PRNG)
for (let i = combined.length - 1; i > 0; i--) {
const j = randomInt(i + 1);
const tmp = combined[i]; combined[i] = combined[j]; combined[j] = tmp;
}
// deduplicate (case-insensitive)
const seen = new Set();
const dedup = [];
for (const s of combined) {
const k = s.toLowerCase();
if (!seen.has(k)) {
seen.add(k);
dedup.push(s.slice(0, CFG.maxLineChars));
}
}
return dedup.slice(-maxLines);
}
async function updateReservoirCorpus() {
// And lo, the reservoir shall drink from recent messages.
const msgs = await DB.recentMessages(64);
const newSents = extractCandidateSentences(msgs);
if (newSents.length === 0) return 0;
const before = _corpusLines.reduce((a, l) => a + l.length, 0);
_corpusLines = reservoirMixKeep(_corpusLines, newSents, CFG.maxCorpusLines);
const after = _corpusLines.reduce((a, l) => a + l.length, 0);
const added = Math.max(0, after - before);
await saveCorpusToDB(_corpusLines);
if (added > 0) {
await DB.addCorpusEvent(added, `reservoir_update +${newSents.length} sents`);
}
return added;
}
async function computeNewCorpusMass(lastEventId) {
const events = await DB.getCorpusEventsSince(lastEventId);
if (events.length === 0) return [0, lastEventId];
const mass = events.reduce((a, e) => a + (e.added_chars || 0), 0);
return [mass, events[events.length - 1].id];
}
// ============================================================
// 2.5) CO-OCCURRENCE FIELD — corpus-level statistics for
// generation before (or alongside) trained weights
// ============================================================
// And lo, the corpus shall whisper its statistics,
// and words shall follow words, like ducklings in a row.
class CooccurField {
constructor() {
this.unigram = new Map();
this.bigram = new Map();
this.trigram = new Map();
this.fourgramByCtx = new Map(); // string key "a,b,c" → Map of {next: count}
this.cooccurWindow = new Map(); // token → Map of {nearby_token: count} (Stanley-style proximity)
this.userBoost = new Map(); // token → float (temporary user word boosts, Leo-style)
this.totalTokens = 0;
}
buildFromCorpus(tok, docs) {
this.unigram.clear();
this.bigram.clear();
this.trigram.clear();
this.fourgramByCtx.clear();
this.cooccurWindow.clear();
this.totalTokens = 0;
const window = CFG.cooccurWindowSize;
for (const doc of docs) {
const ids = tok.encode(doc);
for (let i = 0; i < ids.length; i++) {
const tid = ids[i];
this.unigram.set(tid, (this.unigram.get(tid) || 0) + 1);
this.totalTokens++;
if (i >= 1) {
const bkey = ids[i - 1];
if (!this.bigram.has(bkey)) this.bigram.set(bkey, new Map());
const bm = this.bigram.get(bkey);
bm.set(tid, (bm.get(tid) || 0) + 1);
}
if (i >= 2) {
const key1 = ids[i - 2];
if (!this.trigram.has(key1)) this.trigram.set(key1, new Map());
const m2 = this.trigram.get(key1);
const key2 = ids[i - 1];
if (!m2.has(key2)) m2.set(key2, new Map());
const tm = m2.get(key2);
tm.set(tid, (tm.get(tid) || 0) + 1);
}
// 4-grams: deeper context for child+ stages
if (i >= 3) {
const fkey = ids[i - 3] + "," + ids[i - 2] + "," + ids[i - 1];
if (!this.fourgramByCtx.has(fkey)) this.fourgramByCtx.set(fkey, new Map());
const fm = this.fourgramByCtx.get(fkey);
fm.set(tid, (fm.get(tid) || 0) + 1);
}
}
// Co-occurrence window: "words that resonate together, stay together" (Stanley)
for (let i = 0; i < ids.length; i++) {
const center = ids[i];
const start = Math.max(0, i - window);
const end = Math.min(ids.length, i + window + 1);
for (let j = start; j < end; j++) {
if (i !== j) {
const neighbor = ids[j];
if (!this.cooccurWindow.has(center)) this.cooccurWindow.set(center, new Map());
const cm = this.cooccurWindow.get(center);
cm.set(neighbor, (cm.get(neighbor) || 0) + 1);
}
}
}
}
}
// IngestTokens incrementally adds n-gram counts from a token sequence.
// Unlike buildFromCorpus, this does NOT clear existing data — it adds on top.
// Used by overthinkg rings to enrich the field with the model's own output.
ingestTokens(ids) {
this.ingestTokensWeighted(ids, 1.0);
}
// IngestTokensWeighted adds n-gram counts weighted by a factor.
// High weight = this text matters more (coherent output). Low = less influence.
// Stanley's observe_shard weights by resonance score; we weight by inverse entropy.
ingestTokensWeighted(ids, weight) {
const window = CFG.cooccurWindowSize;
for (const id of ids) {
this.unigram.set(id, (this.unigram.get(id) || 0) + weight);
}
for (let i = 0; i < ids.length - 1; i++) {
const first = ids[i], second = ids[i + 1];
if (!this.bigram.has(first)) this.bigram.set(first, new Map());
const bm = this.bigram.get(first);
bm.set(second, (bm.get(second) || 0) + weight);
}
for (let i = 0; i < ids.length - 2; i++) {
const k1 = ids[i], k2 = ids[i + 1], k3 = ids[i + 2];
if (!this.trigram.has(k1)) this.trigram.set(k1, new Map());
const m2 = this.trigram.get(k1);
if (!m2.has(k2)) m2.set(k2, new Map());
const tm = m2.get(k2);
tm.set(k3, (tm.get(k3) || 0) + weight);
}
for (let i = 0; i < ids.length - 3; i++) {
const fkey = ids[i] + "," + ids[i + 1] + "," + ids[i + 2];
if (!this.fourgramByCtx.has(fkey)) this.fourgramByCtx.set(fkey, new Map());
const fm = this.fourgramByCtx.get(fkey);
fm.set(ids[i + 3], (fm.get(ids[i + 3]) || 0) + weight);
}
// Co-occurrence window
for (let i = 0; i < ids.length; i++) {
const center = ids[i];
const start = Math.max(0, i - window);
const end = Math.min(ids.length, i + window + 1);
for (let j = start; j < end; j++) {
if (i !== j) {
const neighbor = ids[j];
if (!this.cooccurWindow.has(center)) this.cooccurWindow.set(center, new Map());
const cm = this.cooccurWindow.get(center);
cm.set(neighbor, (cm.get(neighbor) || 0) + weight);
}
}
}
}
// AbsorbUserWords sets temporary boosts for tokens the user just said.
// Like Leo's Santa Klaus but simpler: user words get multiplicative boost in generation.
absorbUserWords(ids) {
// Decay existing boosts first
for (const [k, v] of this.userBoost) {
const nv = v * CFG.userBoostDecay;
if (nv < 0.01) {
this.userBoost.delete(k);
} else {
this.userBoost.set(k, nv);
}
}
// Boost user's tokens
const strength = CFG.userBoostStrength;
for (const id of ids) {
this.userBoost.set(id, (this.userBoost.get(id) || 0) + strength);
}
}
// DecayUserBoost reduces user word boosts after a generation.
decayUserBoost() {
for (const [k, v] of this.userBoost) {
const nv = v * CFG.userBoostDecay;
if (nv < 0.01) {
this.userBoost.delete(k);
} else {
this.userBoost.set(k, nv);
}
}
}
sampleNext(contextIds, temperature) {
// And lo, 4gram -> trigram -> bigram -> unigram fallback, like a drunk leaning on smaller drunks.
if (!temperature) temperature = 1.0;
const counts = new Map();
let found = false;
// Try 4-gram (deepest context)
if (contextIds.length >= 3) {
const fkey = contextIds[contextIds.length - 3] + "," + contextIds[contextIds.length - 2] + "," + contextIds[contextIds.length - 1];
const fm = this.fourgramByCtx.get(fkey);
if (fm && fm.size > 0) {
for (const [tid, v] of fm) {
counts.set(tid, (counts.get(tid) || 0) + v);
found = true;
}
}
}
// Fallback to trigram
if (!found && contextIds.length >= 2) {
const k1 = contextIds[contextIds.length - 2];
const k2 = contextIds[contextIds.length - 1];
const m2 = this.trigram.get(k1);
if (m2) {
const tm = m2.get(k2);
if (tm && tm.size > 0) {
for (const [tid, v] of tm) {
counts.set(tid, (counts.get(tid) || 0) + v);
found = true;
}
}
}
}
// Fallback to bigram
if (!found && contextIds.length >= 1) {
const bkey = contextIds[contextIds.length - 1];
if (this.bigram.has(bkey) && this.bigram.get(bkey).size > 0) {
const bm = this.bigram.get(bkey);
for (const [tid, v] of bm) {
counts.set(tid, (counts.get(tid) || 0) + v);
found = true;
}
}
}
// Fallback to unigram
if (!found) {
for (const [k, v] of this.unigram) {
counts.set(k, v);
}
}
if (counts.size === 0) return 0;
// Blend with co-occurrence window (background resonance, always active)
if (contextIds.length > 0) {
const wnd = CFG.cooccurWindowSize;
const ctxSlice = contextIds.length > wnd
? contextIds.slice(-wnd) : contextIds;
for (const ctxTok of ctxSlice) {
const neighbors = this.cooccurWindow.get(ctxTok);
if (neighbors) {
for (const [tid, cnt] of neighbors) {
counts.set(tid, (counts.get(tid) || 0) + cnt * 0.3); // co-occurrence is softer than n-gram
}
}
}
}
// Apply user word boost (multiplicative)
if (this.userBoost.size > 0) {
for (const [tid, boost] of this.userBoost) {
const cur = counts.get(tid);
if (cur !== undefined && cur > 0) {
counts.set(tid, cur * (1.0 + boost));
}
}
}
// Apply temperature and sample
const items = Array.from(counts.entries());
const vals = items.map(([, c]) => c > 0 && temperature > 0 ? Math.pow(c, 1.0 / temperature) : c);
let total = 0;
for (const v of vals) total += v;
if (total <= 0) return 0;
let r = rng() * total;
let cumsum = 0;
for (let i = 0; i < vals.length; i++) {
cumsum += vals[i];
if (cumsum >= r) return items[i][0];
}
return items[items.length - 1][0];
}
}
function corpusGenerate(tok, field, seedText, maxTokens) {
// And lo, the organism shall speak before it learns, like a newborn crying.
if (!maxTokens) maxTokens = CFG.corpusGenMaxTokens;
let ids = tok.encode(seedText).slice(0, -1);
const outIds = [];
const eosId = tok.stoi.get(tok.EOS) || -1;
for (let i = 0; i < maxTokens; i++) {
const nxt = field.sampleNext(ids);
if (nxt === eosId) break;
ids.push(nxt);
outIds.push(nxt);
}
return tok.decode([tok.stoi.get(tok.BOS)].concat(outIds, [eosId]));
}
// ============================================================
// 3) TOKENIZER — char first, then BPE that only EXPANDS vocab
// ============================================================
// And lo, the alphabet shall be forged from the corpus,
// and subwords shall awaken when the corpus grows heavy enough.
class EvolvingTokenizer {
constructor(docs) {
if (docs === undefined) docs = [];
this.BOS = "<BOS>";
this.EOS = "<EOS>";
this.PAD = "<PAD>";
// 256 byte tokens (hex strings "0x00" through "0xff") + 3 special tokens = 259
this.tokens = [];
for (let i = 0; i < 256; i++) {
this.tokens.push("0x" + i.toString(16).padStart(2, "0"));
}
this.tokens.push(this.BOS, this.EOS, this.PAD);
this.stoi = new Map();
this.itos = new Map();
for (let i = 0; i < this.tokens.length; i++) {
this.stoi.set(this.tokens[i], i);
this.itos.set(i, this.tokens[i]);
}
this.vocabSize = this.tokens.length; // 259
// BPE state
this.bpeEnabled = false;
this.merges = [];
this.mergeToTok = new Map();
this._trainedChars = docs.reduce((s, d) => s + d.length, 0);
// Reusable TextEncoder/TextDecoder
this._encoder = new TextEncoder();
this._decoder = new TextDecoder("utf-8", { fatal: false });
}
_unicodeSegment(text) {
// Pre-segmentation by Unicode category. BPE merges happen WITHIN segments only.
// Categories: letters (+marks), digits, whitespace, punctuation/symbols.
const segments = [];
let current = [];
let currentCat = null;
for (const ch of text) {
let cat;
if (/\p{L}|\p{M}/u.test(ch)) cat = "L";
else if (/\p{N}/u.test(ch)) cat = "N";
else if (/\s/.test(ch)) cat = "Z";
else cat = "P";
if (cat !== currentCat && current.length > 0) {
segments.push(this._encoder.encode(current.join("")));
current = [];
}
currentCat = cat;
current.push(ch);
}
if (current.length > 0) segments.push(this._encoder.encode(current.join("")));
return segments;
}
maybeEnableBpe(docs) {
// And lo, when the corpus grows heavy enough, subwords shall awaken.
const totalChars = docs.reduce((a, d) => a + d.length, 0);
if (!this.bpeEnabled && totalChars >= CFG.enableBpeAfterChars) {
this.trainBpe(docs, CFG.bpeNumMerges);
this.bpeEnabled = true;
this._trainedChars = totalChars;
return true;
}
return false;
}
maybeRetrainBpe(docs) {
if (!this.bpeEnabled) return false;
const totalChars = docs.reduce((a, d) => a + d.length, 0);
if (totalChars - this._trainedChars >= CFG.bpeRetrainEveryChars) {
this.trainBpe(docs, CFG.bpeNumMerges);
this._trainedChars = totalChars;
return true;
}
return false;
}
trainBpe(docs, numMerges) {
// And lo, the merges shall be learned from byte sequences within Unicode segments.
const text = docs.join(" ");
if (!text) return;
// Segment and convert to byte-token sequences, count frequencies
const segments = this._unicodeSegment(text);
let vocab = new Map();
for (const seg of segments) {
const tokSeq = [];
for (let i = 0; i < seg.length; i++) {
tokSeq.push(this.tokens[seg[i]]); // e.g. "0x48", "0x65", "0x6c"
}
const key = tokSeq.join("\x00");
vocab.set(key, (vocab.get(key) || 0) + 1);
}
const merges = [];
const mergeToTok = new Map();
for (let mi = 0; mi < numMerges; mi++) {
// Count all adjacent pairs
const pairs = new Map();
for (const [symKey, freq] of vocab) {
const syms = symKey.split("\x00");
for (let i = 0; i < syms.length - 1; i++) {
const pk = syms[i] + "\x00" + syms[i + 1];
pairs.set(pk, (pairs.get(pk) || 0) + freq);
}
}
if (pairs.size === 0) break;
// Find best pair
let bestPair = null, bestCount = -1;
for (const [pk, count] of pairs) {
if (count > bestCount) { bestCount = count; bestPair = pk; }
}
const [a, b] = bestPair.split("\x00");
const newTok = a + "+" + b; // e.g. "0x48+0x65"
merges.push([a, b]);
mergeToTok.set(bestPair, newTok);
// Merge in vocab
const newVocab = new Map();
for (const [symKey, freq] of vocab) {
const syms = symKey.split("\x00");
const out = [];
let i = 0;
while (i < syms.length) {
if (i < syms.length - 1 && syms[i] === a && syms[i + 1] === b) {
out.push(newTok);
i += 2;
} else {
out.push(syms[i]);
i++;
}
}
const newKey = out.join("\x00");
newVocab.set(newKey, (newVocab.get(newKey) || 0) + freq);
}
vocab = newVocab;
// Add token to vocabulary if new
if (!this.stoi.has(newTok)) {
const idx = this.tokens.length;
this.stoi.set(newTok, idx);
this.tokens.push(newTok);
}
}
// Rebuild reverse map
this.itos = new Map();
for (const [t, i] of this.stoi) this.itos.set(i, t);
this.vocabSize = this.tokens.length;
this.merges = merges;
this.mergeToTok = mergeToTok;
}
_applyBPE(tokens) {
// And lo, greedy merging by learned rank shall be performed.
if (this.merges.length === 0) return tokens;
const rank = new Map();
for (let i = 0; i < this.merges.length; i++) {
rank.set(this.merges[i][0] + "\x00" + this.merges[i][1], i);
}
let symbols = tokens.slice();
while (symbols.length >= 2) {
let bestRank = Infinity, bestIdx = -1;
for (let i = 0; i < symbols.length - 1; i++) {
const key = symbols[i] + "\x00" + symbols[i + 1];
const r = rank.get(key);
if (r !== undefined && r < bestRank) { bestRank = r; bestIdx = i; }
}
if (bestIdx === -1) break;
const pairKey = symbols[bestIdx] + "\x00" + symbols[bestIdx + 1];
const merged = this.mergeToTok.get(pairKey) || (symbols[bestIdx] + "+" + symbols[bestIdx + 1]);
symbols = symbols.slice(0, bestIdx).concat([merged], symbols.slice(bestIdx + 2));
}
return symbols;
}
encode(s) {
// Encode text to token IDs: text -> segments -> bytes -> BPE -> IDs
s = s.trim();
const ids = [this.stoi.get(this.BOS)];
if (!s) {
ids.push(this.stoi.get(this.EOS));
return ids;
}
const segments = this._unicodeSegment(s);
for (const seg of segments) {
// Convert bytes to base token names
const baseTokens = [];
for (let i = 0; i < seg.length; i++) {
baseTokens.push(this.tokens[seg[i]]);
}
const merged = this.bpeEnabled ? this._applyBPE(baseTokens) : baseTokens;
for (const tok of merged) {
if (this.stoi.has(tok)) ids.push(this.stoi.get(tok));
}
}
ids.push(this.stoi.get(this.EOS));
return ids;
}
_tokenToBytes(tok) {
// Convert a token string back to bytes.
if (tok.startsWith("0x") && tok.indexOf("+") === -1 && tok.length === 4) {
// Single byte token: "0x41" -> [0x41]
return [parseInt(tok, 16)];
} else if (tok.indexOf("+") !== -1) {
// Merged token: "0x48+0x65" -> split by "+", each "0xNN" -> byte
const parts = tok.split("+");
const result = [];
for (let i = 0; i < parts.length; i++) {
result.push(parseInt(parts[i], 16));
}
return result;
}
return [];
}
decode(ids) {
// Decode token IDs back to text: IDs -> bytes -> UTF-8
const rawBytes = [];
for (const t of ids) {
const tok = this.itos.get(t) || "";
if (tok === this.BOS || tok === this.PAD) continue;
if (tok === this.EOS) break;
const bytes = this._tokenToBytes(tok);
for (let i = 0; i < bytes.length; i++) rawBytes.push(bytes[i]);
}
return this._decoder.decode(new Uint8Array(rawBytes)).trim();