@dniskav/neuron 0.1.6 → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +43 -2
- package/dist/index.d.mts +110 -1
- package/dist/index.d.ts +110 -1
- package/dist/index.js +588 -2
- package/dist/index.mjs +576 -1
- package/package.json +1 -1
package/dist/index.mjs
CHANGED
|
@@ -475,6 +475,570 @@ var NetworkLSTM = class {
|
|
|
475
475
|
}
|
|
476
476
|
};
|
|
477
477
|
|
|
478
|
+
// src/MatMul.ts
|
|
479
|
+
function matMul(A, B) {
|
|
480
|
+
const rows = A.length;
|
|
481
|
+
const inner = B.length;
|
|
482
|
+
const cols = B[0].length;
|
|
483
|
+
const C = Array.from({ length: rows }, () => new Array(cols).fill(0));
|
|
484
|
+
for (let i = 0; i < rows; i++)
|
|
485
|
+
for (let k = 0; k < inner; k++) {
|
|
486
|
+
const aik = A[i][k];
|
|
487
|
+
for (let j = 0; j < cols; j++)
|
|
488
|
+
C[i][j] += aik * B[k][j];
|
|
489
|
+
}
|
|
490
|
+
return C;
|
|
491
|
+
}
|
|
492
|
+
function transpose(A) {
|
|
493
|
+
const rows = A.length, cols = A[0].length;
|
|
494
|
+
const T = Array.from({ length: cols }, () => new Array(rows).fill(0));
|
|
495
|
+
for (let i = 0; i < rows; i++)
|
|
496
|
+
for (let j = 0; j < cols; j++)
|
|
497
|
+
T[j][i] = A[i][j];
|
|
498
|
+
return T;
|
|
499
|
+
}
|
|
500
|
+
function softmax(row) {
|
|
501
|
+
const max = Math.max(...row);
|
|
502
|
+
const exps = row.map((v) => Math.exp(v - max));
|
|
503
|
+
const sum = exps.reduce((a, b) => a + b, 0);
|
|
504
|
+
return exps.map((e) => e / sum);
|
|
505
|
+
}
|
|
506
|
+
function softmaxBackward(dS, s) {
|
|
507
|
+
const dot = s.reduce((acc, si, i) => acc + dS[i] * si, 0);
|
|
508
|
+
return s.map((si, i) => si * (dS[i] - dot));
|
|
509
|
+
}
|
|
510
|
+
var WeightMatrix = class {
|
|
511
|
+
constructor(rows, cols) {
|
|
512
|
+
const limit = Math.sqrt(2 / (rows + cols));
|
|
513
|
+
this.W = Array.from(
|
|
514
|
+
{ length: rows },
|
|
515
|
+
() => Array.from({ length: cols }, () => (Math.random() * 2 - 1) * limit)
|
|
516
|
+
);
|
|
517
|
+
this.opts = Array.from(
|
|
518
|
+
{ length: rows },
|
|
519
|
+
() => Array.from({ length: cols }, () => new Adam())
|
|
520
|
+
);
|
|
521
|
+
}
|
|
522
|
+
// Apply pre-computed gradient (same shape as W).
|
|
523
|
+
// clipValue: optional per-element gradient clipping before the Adam step.
|
|
524
|
+
// Prevents gradient explosion in deep networks (e.g. Transformers without
|
|
525
|
+
// global norm clipping). Pass e.g. 1.0 to clip to [-1, 1].
|
|
526
|
+
update(dW, lr, clipValue = Infinity) {
|
|
527
|
+
for (let i = 0; i < this.W.length; i++)
|
|
528
|
+
for (let j = 0; j < this.W[0].length; j++) {
|
|
529
|
+
const g = isFinite(clipValue) ? Math.max(-clipValue, Math.min(clipValue, dW[i][j])) : dW[i][j];
|
|
530
|
+
this.W[i][j] = this.opts[i][j].step(this.W[i][j], g, lr);
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
};
|
|
534
|
+
var EmbeddingMatrix = class {
|
|
535
|
+
constructor(vocabSize, d_model) {
|
|
536
|
+
const limit = Math.sqrt(1 / d_model);
|
|
537
|
+
this.W = Array.from(
|
|
538
|
+
{ length: vocabSize },
|
|
539
|
+
() => Array.from({ length: d_model }, () => (Math.random() * 2 - 1) * limit)
|
|
540
|
+
);
|
|
541
|
+
}
|
|
542
|
+
get(idx) {
|
|
543
|
+
return [...this.W[idx]];
|
|
544
|
+
}
|
|
545
|
+
update(idx, grad, lr) {
|
|
546
|
+
for (let m = 0; m < this.W[idx].length; m++)
|
|
547
|
+
this.W[idx][m] += lr * grad[m];
|
|
548
|
+
}
|
|
549
|
+
};
|
|
550
|
+
|
|
551
|
+
// src/AttentionHead.ts
|
|
552
|
+
var AttentionHead = class {
|
|
553
|
+
constructor(d_model, d_k, d_v) {
|
|
554
|
+
// d_v × d_model
|
|
555
|
+
this.cache = null;
|
|
556
|
+
this.d_k = d_k;
|
|
557
|
+
this.d_v = d_v;
|
|
558
|
+
this.Wq = new WeightMatrix(d_k, d_model);
|
|
559
|
+
this.Wk = new WeightMatrix(d_k, d_model);
|
|
560
|
+
this.Wv = new WeightMatrix(d_v, d_model);
|
|
561
|
+
}
|
|
562
|
+
// ── Forward ───────────────────────────────────────────────────────────────
|
|
563
|
+
// X: seqLen × d_model → out: seqLen × d_v
|
|
564
|
+
predict(X) {
|
|
565
|
+
const seqLen = X.length;
|
|
566
|
+
const scale = 1 / Math.sqrt(this.d_k);
|
|
567
|
+
const Q = X.map(
|
|
568
|
+
(x) => this.Wq.W.map((wq) => wq.reduce((s, w, m) => s + w * x[m], 0))
|
|
569
|
+
);
|
|
570
|
+
const K = X.map(
|
|
571
|
+
(x) => this.Wk.W.map((wk) => wk.reduce((s, w, m) => s + w * x[m], 0))
|
|
572
|
+
);
|
|
573
|
+
const V = X.map(
|
|
574
|
+
(x) => this.Wv.W.map((wv) => wv.reduce((s, w, m) => s + w * x[m], 0))
|
|
575
|
+
);
|
|
576
|
+
const scores = Array.from(
|
|
577
|
+
{ length: seqLen },
|
|
578
|
+
(_, i) => Array.from(
|
|
579
|
+
{ length: seqLen },
|
|
580
|
+
(_2, j) => Q[i].reduce((s, q, k) => s + q * K[j][k], 0) * scale
|
|
581
|
+
)
|
|
582
|
+
);
|
|
583
|
+
const attn = scores.map((row) => softmax(row));
|
|
584
|
+
const out = Array.from(
|
|
585
|
+
{ length: seqLen },
|
|
586
|
+
(_, i) => Array.from(
|
|
587
|
+
{ length: this.d_v },
|
|
588
|
+
(_2, d) => attn[i].reduce((s, a, j) => s + a * V[j][d], 0)
|
|
589
|
+
)
|
|
590
|
+
);
|
|
591
|
+
this.cache = { X, Q, K, V, scores, attn };
|
|
592
|
+
return out;
|
|
593
|
+
}
|
|
594
|
+
// ── Backward ──────────────────────────────────────────────────────────────
|
|
595
|
+
// dOut: seqLen × d_v → dX: seqLen × d_model
|
|
596
|
+
//
|
|
597
|
+
// Steps:
|
|
598
|
+
// 1. dV = attn^T @ dOut
|
|
599
|
+
// 2. dAttn = dOut @ V^T (attention weight gradients)
|
|
600
|
+
// 3. dScores = softmaxBwd(dAttn) / √d_k
|
|
601
|
+
// 4. dQ = dScores @ K, dK = dScores^T @ Q
|
|
602
|
+
// 5. dWq = dQ^T @ X, dWk = dK^T @ X, dWv = dV^T @ X
|
|
603
|
+
// 6. dX = dQ @ Wq + dK @ Wk + dV @ Wv
|
|
604
|
+
backward(dOut, lr) {
|
|
605
|
+
const { X, Q, K, V, attn } = this.cache;
|
|
606
|
+
const seqLen = X.length;
|
|
607
|
+
const d_model = X[0].length;
|
|
608
|
+
const scale = 1 / Math.sqrt(this.d_k);
|
|
609
|
+
const dV = Array.from(
|
|
610
|
+
{ length: seqLen },
|
|
611
|
+
(_, j) => Array.from(
|
|
612
|
+
{ length: this.d_v },
|
|
613
|
+
(_2, d) => attn.reduce((s, a, i) => s + a[j] * dOut[i][d], 0)
|
|
614
|
+
)
|
|
615
|
+
);
|
|
616
|
+
const dAttn = Array.from(
|
|
617
|
+
{ length: seqLen },
|
|
618
|
+
(_, i) => Array.from(
|
|
619
|
+
{ length: seqLen },
|
|
620
|
+
(_2, j) => dOut[i].reduce((s, d, k) => s + d * V[j][k], 0)
|
|
621
|
+
)
|
|
622
|
+
);
|
|
623
|
+
const dScores = dAttn.map(
|
|
624
|
+
(da, i) => softmaxBackward(da, attn[i]).map((v) => v * scale)
|
|
625
|
+
);
|
|
626
|
+
const dQ = Array.from(
|
|
627
|
+
{ length: seqLen },
|
|
628
|
+
(_, i) => Array.from(
|
|
629
|
+
{ length: this.d_k },
|
|
630
|
+
(_2, k) => dScores[i].reduce((s, ds, j) => s + ds * K[j][k], 0)
|
|
631
|
+
)
|
|
632
|
+
);
|
|
633
|
+
const dK = Array.from(
|
|
634
|
+
{ length: seqLen },
|
|
635
|
+
(_, j) => Array.from(
|
|
636
|
+
{ length: this.d_k },
|
|
637
|
+
(_2, k) => dScores.reduce((s, ds, i) => s + ds[j] * Q[i][k], 0)
|
|
638
|
+
)
|
|
639
|
+
);
|
|
640
|
+
const dWq = Array.from(
|
|
641
|
+
{ length: this.d_k },
|
|
642
|
+
(_, k) => Array.from(
|
|
643
|
+
{ length: d_model },
|
|
644
|
+
(_2, m) => dQ.reduce((s, dq, i) => s + dq[k] * X[i][m], 0)
|
|
645
|
+
)
|
|
646
|
+
);
|
|
647
|
+
const dWk = Array.from(
|
|
648
|
+
{ length: this.d_k },
|
|
649
|
+
(_, k) => Array.from(
|
|
650
|
+
{ length: d_model },
|
|
651
|
+
(_2, m) => dK.reduce((s, dk, i) => s + dk[k] * X[i][m], 0)
|
|
652
|
+
)
|
|
653
|
+
);
|
|
654
|
+
const dWv = Array.from(
|
|
655
|
+
{ length: this.d_v },
|
|
656
|
+
(_, k) => Array.from(
|
|
657
|
+
{ length: d_model },
|
|
658
|
+
(_2, m) => dV.reduce((s, dv, i) => s + dv[k] * X[i][m], 0)
|
|
659
|
+
)
|
|
660
|
+
);
|
|
661
|
+
this.Wq.update(dWq, lr);
|
|
662
|
+
this.Wk.update(dWk, lr);
|
|
663
|
+
this.Wv.update(dWv, lr);
|
|
664
|
+
const dX = Array.from(
|
|
665
|
+
{ length: seqLen },
|
|
666
|
+
(_, i) => Array.from(
|
|
667
|
+
{ length: d_model },
|
|
668
|
+
(_2, m) => dQ[i].reduce((s, dq, k) => s + dq * this.Wq.W[k][m], 0) + dK[i].reduce((s, dk, k) => s + dk * this.Wk.W[k][m], 0) + dV[i].reduce((s, dv, k) => s + dv * this.Wv.W[k][m], 0)
|
|
669
|
+
)
|
|
670
|
+
);
|
|
671
|
+
return dX;
|
|
672
|
+
}
|
|
673
|
+
// Attention weights from the last predict() call — useful for visualization.
|
|
674
|
+
getAttentionWeights() {
|
|
675
|
+
return this.cache ? this.cache.attn : null;
|
|
676
|
+
}
|
|
677
|
+
};
|
|
678
|
+
|
|
679
|
+
// src/MultiHeadAttention.ts
|
|
680
|
+
var MultiHeadAttention = class {
|
|
681
|
+
// seqLen × (nHeads * d_k)
|
|
682
|
+
constructor(d_model, nHeads) {
|
|
683
|
+
// d_model × (nHeads * d_k)
|
|
684
|
+
// Cached for backward
|
|
685
|
+
this._concat = null;
|
|
686
|
+
this.nHeads = nHeads;
|
|
687
|
+
this.d_model = d_model;
|
|
688
|
+
this.d_k = Math.floor(d_model / nHeads);
|
|
689
|
+
this.heads = Array.from(
|
|
690
|
+
{ length: nHeads },
|
|
691
|
+
() => new AttentionHead(d_model, this.d_k, this.d_k)
|
|
692
|
+
);
|
|
693
|
+
this.Wo = new WeightMatrix(d_model, nHeads * this.d_k);
|
|
694
|
+
}
|
|
695
|
+
// ── Forward ───────────────────────────────────────────────────────────────
|
|
696
|
+
// X: seqLen × d_model → out: seqLen × d_model
|
|
697
|
+
predict(X) {
|
|
698
|
+
const seqLen = X.length;
|
|
699
|
+
const headOuts = this.heads.map((h) => h.predict(X));
|
|
700
|
+
const concat = Array.from(
|
|
701
|
+
{ length: seqLen },
|
|
702
|
+
(_, i) => headOuts.flatMap((ho) => ho[i])
|
|
703
|
+
);
|
|
704
|
+
const out = concat.map(
|
|
705
|
+
(c) => this.Wo.W.map((row) => row.reduce((s, w, j) => s + w * c[j], 0))
|
|
706
|
+
);
|
|
707
|
+
this._concat = concat;
|
|
708
|
+
return out;
|
|
709
|
+
}
|
|
710
|
+
// ── Backward ──────────────────────────────────────────────────────────────
|
|
711
|
+
// dOut: seqLen × d_model → dX: seqLen × d_model
|
|
712
|
+
backward(dOut, lr) {
|
|
713
|
+
const seqLen = dOut.length;
|
|
714
|
+
const concatD = this.nHeads * this.d_k;
|
|
715
|
+
const d_model = this.d_model;
|
|
716
|
+
const concat = this._concat;
|
|
717
|
+
const dConcat = dOut.map(
|
|
718
|
+
(do_) => Array.from(
|
|
719
|
+
{ length: concatD },
|
|
720
|
+
(_, j) => this.Wo.W.reduce((s, row, k) => s + do_[k] * row[j], 0)
|
|
721
|
+
)
|
|
722
|
+
);
|
|
723
|
+
const dWo = Array.from(
|
|
724
|
+
{ length: d_model },
|
|
725
|
+
(_, k) => Array.from(
|
|
726
|
+
{ length: concatD },
|
|
727
|
+
(_2, j) => dOut.reduce((s, row, i) => s + row[k] * concat[i][j], 0)
|
|
728
|
+
)
|
|
729
|
+
);
|
|
730
|
+
this.Wo.update(dWo, lr);
|
|
731
|
+
const dX = Array.from(
|
|
732
|
+
{ length: seqLen },
|
|
733
|
+
() => new Array(d_model).fill(0)
|
|
734
|
+
);
|
|
735
|
+
for (let h = 0; h < this.nHeads; h++) {
|
|
736
|
+
const start = h * this.d_k;
|
|
737
|
+
const dHeadOut = dConcat.map((dc) => dc.slice(start, start + this.d_k));
|
|
738
|
+
const dXh = this.heads[h].backward(dHeadOut, lr);
|
|
739
|
+
for (let i = 0; i < seqLen; i++)
|
|
740
|
+
for (let m = 0; m < d_model; m++)
|
|
741
|
+
dX[i][m] += dXh[i][m];
|
|
742
|
+
}
|
|
743
|
+
return dX;
|
|
744
|
+
}
|
|
745
|
+
// Attention weights per head from the last predict() — for visualization.
|
|
746
|
+
// Returns: nHeads × seqLen × seqLen
|
|
747
|
+
getAttentionWeights() {
|
|
748
|
+
return this.heads.map((h) => h.getAttentionWeights());
|
|
749
|
+
}
|
|
750
|
+
};
|
|
751
|
+
|
|
752
|
+
// src/LayerNorm.ts
|
|
753
|
+
var LayerNorm = class {
|
|
754
|
+
constructor(dim) {
|
|
755
|
+
this.eps = 1e-5;
|
|
756
|
+
// Per-position cache populated during the forward pass.
|
|
757
|
+
// resetCache() must be called before each sequence forward pass.
|
|
758
|
+
this._cache = [];
|
|
759
|
+
this.gamma = new Array(dim).fill(1);
|
|
760
|
+
this.beta = new Array(dim).fill(0);
|
|
761
|
+
}
|
|
762
|
+
// Call once before forward-passing a new sequence.
|
|
763
|
+
resetCache(seqLen) {
|
|
764
|
+
this._cache = new Array(seqLen);
|
|
765
|
+
}
|
|
766
|
+
// Normalize a single position's feature vector.
|
|
767
|
+
// pos must match the position index used in the corresponding backwardOne call.
|
|
768
|
+
predictOne(x, pos) {
|
|
769
|
+
const N = x.length;
|
|
770
|
+
const mean = x.reduce((s, v) => s + v, 0) / N;
|
|
771
|
+
const vari = x.reduce((s, v) => s + (v - mean) ** 2, 0) / N;
|
|
772
|
+
const std = Math.sqrt(vari + this.eps);
|
|
773
|
+
const x_norm = x.map((v) => (v - mean) / std);
|
|
774
|
+
this._cache[pos] = { x_norm, std };
|
|
775
|
+
return x_norm.map((xn, i) => this.gamma[i] * xn + this.beta[i]);
|
|
776
|
+
}
|
|
777
|
+
// Backprop through layer norm for one position.
|
|
778
|
+
//
|
|
779
|
+
// Given dL/dy (dOut), computes dL/dx:
|
|
780
|
+
// Let D = dOut ⊙ γ
|
|
781
|
+
// dL/dx_i = (1/std) * (D_i − mean(D) − x_norm_i * mean(D ⊙ x_norm))
|
|
782
|
+
//
|
|
783
|
+
// Also updates γ and β via SGD:
|
|
784
|
+
// γ_i += lr * dOut_i * x_norm_i
|
|
785
|
+
// β_i += lr * dOut_i
|
|
786
|
+
//
|
|
787
|
+
// SGD (not Adam) for γ/β: they are aggregated across all positions in the
|
|
788
|
+
// sequence (de-facto mini-batch update), so the gradient is already smoothed.
|
|
789
|
+
backwardOne(dOut, pos, lr) {
|
|
790
|
+
const { x_norm, std } = this._cache[pos];
|
|
791
|
+
const N = dOut.length;
|
|
792
|
+
for (let i = 0; i < N; i++) {
|
|
793
|
+
this.gamma[i] += lr * dOut[i] * x_norm[i];
|
|
794
|
+
this.beta[i] += lr * dOut[i];
|
|
795
|
+
}
|
|
796
|
+
const D = dOut.map((d, i) => d * this.gamma[i]);
|
|
797
|
+
const mD = D.reduce((s, v) => s + v, 0) / N;
|
|
798
|
+
const mDxn = D.reduce((s, d, i) => s + d * x_norm[i], 0) / N;
|
|
799
|
+
return D.map((d, i) => (d - mD - x_norm[i] * mDxn) / std);
|
|
800
|
+
}
|
|
801
|
+
};
|
|
802
|
+
|
|
803
|
+
// src/TransformerBlock.ts
|
|
804
|
+
var TransformerBlock = class {
|
|
805
|
+
constructor({ d_model, nHeads, d_ff }) {
|
|
806
|
+
// Forward caches (needed for backprop)
|
|
807
|
+
this._X = null;
|
|
808
|
+
this._attnOut = null;
|
|
809
|
+
this._h1 = null;
|
|
810
|
+
this._ff1Pre = null;
|
|
811
|
+
// pre-ReLU
|
|
812
|
+
this._ff1Out = null;
|
|
813
|
+
// post-ReLU
|
|
814
|
+
this._ff2Out = null;
|
|
815
|
+
this.d_model = d_model;
|
|
816
|
+
this.d_ff = d_ff;
|
|
817
|
+
this.attn = new MultiHeadAttention(d_model, nHeads);
|
|
818
|
+
this.norm1 = new LayerNorm(d_model);
|
|
819
|
+
this.norm2 = new LayerNorm(d_model);
|
|
820
|
+
this.ff1 = new WeightMatrix(d_ff, d_model);
|
|
821
|
+
this.ff2 = new WeightMatrix(d_model, d_ff);
|
|
822
|
+
this.b1 = new Array(d_ff).fill(0);
|
|
823
|
+
this.b2 = new Array(d_model).fill(0);
|
|
824
|
+
this.b1Opts = Array.from({ length: d_ff }, () => new Adam());
|
|
825
|
+
this.b2Opts = Array.from({ length: d_model }, () => new Adam());
|
|
826
|
+
}
|
|
827
|
+
// ── Forward ───────────────────────────────────────────────────────────────
|
|
828
|
+
// X: seqLen × d_model → out: seqLen × d_model
|
|
829
|
+
predict(X) {
|
|
830
|
+
const seqLen = X.length;
|
|
831
|
+
const attnOut = this.attn.predict(X);
|
|
832
|
+
this.norm1.resetCache(seqLen);
|
|
833
|
+
const h1 = X.map((x, i) => {
|
|
834
|
+
const added = x.map((v, k) => v + attnOut[i][k]);
|
|
835
|
+
return this.norm1.predictOne(added, i);
|
|
836
|
+
});
|
|
837
|
+
const ff1Pre = h1.map(
|
|
838
|
+
(h) => this.ff1.W.map((row, k) => row.reduce((s, w, m) => s + w * h[m], this.b1[k]))
|
|
839
|
+
);
|
|
840
|
+
const ff1Out = ff1Pre.map((pre) => pre.map((v) => Math.max(0, v)));
|
|
841
|
+
const ff2Out = ff1Out.map(
|
|
842
|
+
(h) => this.ff2.W.map((row, k) => row.reduce((s, w, m) => s + w * h[m], this.b2[k]))
|
|
843
|
+
);
|
|
844
|
+
this.norm2.resetCache(seqLen);
|
|
845
|
+
const out = h1.map((h, i) => {
|
|
846
|
+
const added = h.map((v, k) => v + ff2Out[i][k]);
|
|
847
|
+
return this.norm2.predictOne(added, i);
|
|
848
|
+
});
|
|
849
|
+
this._X = X;
|
|
850
|
+
this._attnOut = attnOut;
|
|
851
|
+
this._h1 = h1;
|
|
852
|
+
this._ff1Pre = ff1Pre;
|
|
853
|
+
this._ff1Out = ff1Out;
|
|
854
|
+
this._ff2Out = ff2Out;
|
|
855
|
+
return out;
|
|
856
|
+
}
|
|
857
|
+
// ── Backward ──────────────────────────────────────────────────────────────
|
|
858
|
+
// dOut: seqLen × d_model → dX: seqLen × d_model
|
|
859
|
+
backward(dOut, lr) {
|
|
860
|
+
const seqLen = dOut.length;
|
|
861
|
+
const d_model = this.d_model;
|
|
862
|
+
const h1 = this._h1;
|
|
863
|
+
const ff1Out = this._ff1Out;
|
|
864
|
+
const ff1Pre = this._ff1Pre;
|
|
865
|
+
const dAdded2 = dOut.map((do_, i) => this.norm2.backwardOne(do_, i, lr));
|
|
866
|
+
const dFf1Out = dAdded2.map(
|
|
867
|
+
(da) => Array.from(
|
|
868
|
+
{ length: this.d_ff },
|
|
869
|
+
(_, k) => this.ff2.W.reduce((s, row, m) => s + row[k] * da[m], 0)
|
|
870
|
+
)
|
|
871
|
+
);
|
|
872
|
+
const dW2 = Array.from(
|
|
873
|
+
{ length: d_model },
|
|
874
|
+
(_, m) => Array.from(
|
|
875
|
+
{ length: this.d_ff },
|
|
876
|
+
(_2, k) => dAdded2.reduce((s, da, i) => s + da[m] * ff1Out[i][k], 0)
|
|
877
|
+
)
|
|
878
|
+
);
|
|
879
|
+
const db2 = Array.from(
|
|
880
|
+
{ length: d_model },
|
|
881
|
+
(_, m) => dAdded2.reduce((s, da) => s + da[m], 0)
|
|
882
|
+
);
|
|
883
|
+
this.ff2.update(dW2, lr);
|
|
884
|
+
for (let m = 0; m < d_model; m++)
|
|
885
|
+
this.b2[m] = this.b2Opts[m].step(this.b2[m], db2[m], lr);
|
|
886
|
+
const dFf1Pre = dFf1Out.map(
|
|
887
|
+
(d, i) => d.map((v, k) => ff1Pre[i][k] > 0 ? v : 0)
|
|
888
|
+
);
|
|
889
|
+
const dH1_fromFf = dFf1Pre.map(
|
|
890
|
+
(dp) => Array.from(
|
|
891
|
+
{ length: d_model },
|
|
892
|
+
(_, m) => this.ff1.W.reduce((s, row, k) => s + dp[k] * row[m], 0)
|
|
893
|
+
)
|
|
894
|
+
);
|
|
895
|
+
const dW1 = Array.from(
|
|
896
|
+
{ length: this.d_ff },
|
|
897
|
+
(_, k) => Array.from(
|
|
898
|
+
{ length: d_model },
|
|
899
|
+
(_2, m) => dFf1Pre.reduce((s, dp, i) => s + dp[k] * h1[i][m], 0)
|
|
900
|
+
)
|
|
901
|
+
);
|
|
902
|
+
const db1 = Array.from(
|
|
903
|
+
{ length: this.d_ff },
|
|
904
|
+
(_, k) => dFf1Pre.reduce((s, dp) => s + dp[k], 0)
|
|
905
|
+
);
|
|
906
|
+
this.ff1.update(dW1, lr);
|
|
907
|
+
for (let k = 0; k < this.d_ff; k++)
|
|
908
|
+
this.b1[k] = this.b1Opts[k].step(this.b1[k], db1[k], lr);
|
|
909
|
+
const dH1 = Array.from(
|
|
910
|
+
{ length: seqLen },
|
|
911
|
+
(_, i) => dH1_fromFf[i].map((v, m) => v + dAdded2[i][m])
|
|
912
|
+
);
|
|
913
|
+
const dAdded1 = dH1.map((d, i) => this.norm1.backwardOne(d, i, lr));
|
|
914
|
+
const dAttnOut = dAdded1;
|
|
915
|
+
const dX_skip = dAdded1;
|
|
916
|
+
const dX_fromAttn = this.attn.backward(dAttnOut, lr);
|
|
917
|
+
const dX = Array.from(
|
|
918
|
+
{ length: seqLen },
|
|
919
|
+
(_, i) => Array.from(
|
|
920
|
+
{ length: d_model },
|
|
921
|
+
(_2, m) => dX_fromAttn[i][m] + dX_skip[i][m]
|
|
922
|
+
)
|
|
923
|
+
);
|
|
924
|
+
return dX;
|
|
925
|
+
}
|
|
926
|
+
// Attention weights from the last predict() — for visualization.
|
|
927
|
+
getAttentionWeights() {
|
|
928
|
+
return this.attn.getAttentionWeights();
|
|
929
|
+
}
|
|
930
|
+
};
|
|
931
|
+
|
|
932
|
+
// src/NetworkTransformer.ts
|
|
933
|
+
var NetworkTransformer = class {
|
|
934
|
+
constructor(seqLen, options = {}) {
|
|
935
|
+
const {
|
|
936
|
+
vocabSize = 10,
|
|
937
|
+
d_model = 64,
|
|
938
|
+
nHeads = 4,
|
|
939
|
+
d_ff = 128,
|
|
940
|
+
nBlocks = 4,
|
|
941
|
+
nClasses = 9
|
|
942
|
+
} = options;
|
|
943
|
+
this.seqLen = seqLen;
|
|
944
|
+
this.vocabSize = vocabSize;
|
|
945
|
+
this.d_model = d_model;
|
|
946
|
+
this.nClasses = nClasses;
|
|
947
|
+
this.tokenEmb = new EmbeddingMatrix(vocabSize, d_model);
|
|
948
|
+
this.posEmb = new EmbeddingMatrix(seqLen, d_model);
|
|
949
|
+
this.blocks = Array.from(
|
|
950
|
+
{ length: nBlocks },
|
|
951
|
+
() => new TransformerBlock({ d_model, nHeads, d_ff })
|
|
952
|
+
);
|
|
953
|
+
this.outputProj = new WeightMatrix(nClasses, d_model);
|
|
954
|
+
this.outputBias = new Array(nClasses).fill(0);
|
|
955
|
+
this.outBiasOpts = Array.from({ length: nClasses }, () => new Adam());
|
|
956
|
+
}
|
|
957
|
+
// ── Forward pass ──────────────────────────────────────────────────────────
|
|
958
|
+
// tokens: seqLen integer ids → seqLen * nClasses logits (flattened)
|
|
959
|
+
predict(tokens) {
|
|
960
|
+
const h = this._forward(tokens);
|
|
961
|
+
return h.flatMap(
|
|
962
|
+
(hi) => this.outputProj.W.map(
|
|
963
|
+
(row, c) => row.reduce((s, w, m) => s + w * hi[m], this.outputBias[c])
|
|
964
|
+
)
|
|
965
|
+
);
|
|
966
|
+
}
|
|
967
|
+
// ── Training step (online, one sample at a time) ───────────────────────────
|
|
968
|
+
// tokens: seqLen integer ids
|
|
969
|
+
// targets: seqLen * nClasses values (e.g. one-hot per cell)
|
|
970
|
+
// mask: optional boolean[seqLen] — only compute loss/gradients for
|
|
971
|
+
// positions where mask[i] = true (e.g. empty cells in Sudoku)
|
|
972
|
+
// Returns: MSE loss over the masked positions.
|
|
973
|
+
train(tokens, targets, lr, mask) {
|
|
974
|
+
const h = this._forward(tokens);
|
|
975
|
+
const logits = h.map(
|
|
976
|
+
(hi) => this.outputProj.W.map(
|
|
977
|
+
(row, c) => row.reduce((s, w, m) => s + w * hi[m], this.outputBias[c])
|
|
978
|
+
)
|
|
979
|
+
);
|
|
980
|
+
let loss = 0;
|
|
981
|
+
let count = 0;
|
|
982
|
+
const dLogits = Array.from({ length: this.seqLen }, (_, i) => {
|
|
983
|
+
if (mask && !mask[i]) return new Array(this.nClasses).fill(0);
|
|
984
|
+
count++;
|
|
985
|
+
const probs = softmax(logits[i]);
|
|
986
|
+
for (let c = 0; c < this.nClasses; c++) {
|
|
987
|
+
const t = targets[i * this.nClasses + c];
|
|
988
|
+
if (t > 0) loss -= Math.log(Math.max(probs[c], 1e-7));
|
|
989
|
+
}
|
|
990
|
+
return probs.map((p, c) => p - targets[i * this.nClasses + c]);
|
|
991
|
+
});
|
|
992
|
+
if (count > 0) loss /= count;
|
|
993
|
+
const dH = Array.from(
|
|
994
|
+
{ length: this.seqLen },
|
|
995
|
+
(_, i) => Array.from(
|
|
996
|
+
{ length: this.d_model },
|
|
997
|
+
(_2, m) => dLogits[i].reduce((s, dl, c) => s + dl * this.outputProj.W[c][m], 0)
|
|
998
|
+
)
|
|
999
|
+
);
|
|
1000
|
+
const dWout = Array.from(
|
|
1001
|
+
{ length: this.nClasses },
|
|
1002
|
+
(_, c) => Array.from(
|
|
1003
|
+
{ length: this.d_model },
|
|
1004
|
+
(_2, m) => dLogits.reduce((s, dl, i) => s + dl[c] * h[i][m], 0)
|
|
1005
|
+
)
|
|
1006
|
+
);
|
|
1007
|
+
const dBout = Array.from(
|
|
1008
|
+
{ length: this.nClasses },
|
|
1009
|
+
(_, c) => dLogits.reduce((s, dl) => s + dl[c], 0)
|
|
1010
|
+
);
|
|
1011
|
+
this.outputProj.update(dWout, lr);
|
|
1012
|
+
for (let c = 0; c < this.nClasses; c++)
|
|
1013
|
+
this.outputBias[c] = this.outBiasOpts[c].step(this.outputBias[c], dBout[c], lr);
|
|
1014
|
+
let dX = dH;
|
|
1015
|
+
for (let b = this.blocks.length - 1; b >= 0; b--)
|
|
1016
|
+
dX = this.blocks[b].backward(dX, lr);
|
|
1017
|
+
for (let i = 0; i < this.seqLen; i++) {
|
|
1018
|
+
this.tokenEmb.update(tokens[i], dX[i], lr);
|
|
1019
|
+
this.posEmb.update(i, dX[i], lr);
|
|
1020
|
+
}
|
|
1021
|
+
return loss;
|
|
1022
|
+
}
|
|
1023
|
+
// Attention weights from every block for visualization.
|
|
1024
|
+
// Returns: nBlocks × nHeads × seqLen × seqLen (nulls if not yet run)
|
|
1025
|
+
getAttentionWeights() {
|
|
1026
|
+
return this.blocks.map((b) => b.getAttentionWeights());
|
|
1027
|
+
}
|
|
1028
|
+
// ── Internal ──────────────────────────────────────────────────────────────
|
|
1029
|
+
// Shared embedding + block forward pass.
|
|
1030
|
+
_forward(tokens) {
|
|
1031
|
+
let h = tokens.map((id, i) => {
|
|
1032
|
+
const te = this.tokenEmb.get(id);
|
|
1033
|
+
const pe = this.posEmb.get(i);
|
|
1034
|
+
return te.map((v, m) => v + pe[m]);
|
|
1035
|
+
});
|
|
1036
|
+
for (const block of this.blocks)
|
|
1037
|
+
h = block.predict(h);
|
|
1038
|
+
return h;
|
|
1039
|
+
}
|
|
1040
|
+
};
|
|
1041
|
+
|
|
478
1042
|
// src/losses.ts
|
|
479
1043
|
function mse(predicted, actual) {
|
|
480
1044
|
return predicted.reduce((sum, p, i) => sum + (actual[i] - p) ** 2, 0) / predicted.length;
|
|
@@ -499,15 +1063,22 @@ function crossEntropyDeltaRaw(predicted, actual) {
|
|
|
499
1063
|
}
|
|
500
1064
|
export {
|
|
501
1065
|
Adam,
|
|
1066
|
+
AttentionHead,
|
|
1067
|
+
EmbeddingMatrix,
|
|
502
1068
|
LSTMLayer,
|
|
503
1069
|
Layer,
|
|
1070
|
+
LayerNorm,
|
|
504
1071
|
Momentum,
|
|
1072
|
+
MultiHeadAttention,
|
|
505
1073
|
Network,
|
|
506
1074
|
NetworkLSTM,
|
|
507
1075
|
NetworkN,
|
|
1076
|
+
NetworkTransformer,
|
|
508
1077
|
Neuron,
|
|
509
1078
|
NeuronN,
|
|
510
1079
|
SGD,
|
|
1080
|
+
TransformerBlock,
|
|
1081
|
+
WeightMatrix,
|
|
511
1082
|
crossEntropy,
|
|
512
1083
|
crossEntropyDelta,
|
|
513
1084
|
crossEntropyDeltaRaw,
|
|
@@ -516,9 +1087,13 @@ export {
|
|
|
516
1087
|
linear,
|
|
517
1088
|
makeElu,
|
|
518
1089
|
makeLeakyRelu,
|
|
1090
|
+
matMul,
|
|
519
1091
|
mse,
|
|
520
1092
|
mseDelta,
|
|
521
1093
|
relu,
|
|
522
1094
|
sigmoid2 as sigmoid,
|
|
523
|
-
|
|
1095
|
+
softmax,
|
|
1096
|
+
softmaxBackward,
|
|
1097
|
+
tanh,
|
|
1098
|
+
transpose
|
|
524
1099
|
};
|
package/package.json
CHANGED