@genai-fi/nanogpt 0.4.5 → 0.5.0

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.
Files changed (111) hide show
  1. package/dist/BaseLayer-BhrMN8JO.js +135 -0
  2. package/dist/Generator.js +44 -41
  3. package/dist/NanoGPTModel.d.ts +12 -16
  4. package/dist/NanoGPTModel.js +128 -138
  5. package/dist/{Reshape-CiAY8ltP.js → Reshape-BE5rA4rT.js} +8 -8
  6. package/dist/TeachableLLM.js +1 -1
  7. package/dist/{TiedEmbedding-DznFwzcB.js → TiedEmbedding-DsDRvLB0.js} +751 -768
  8. package/dist/{axis_util-QP0LdI1v.js → axis_util-97KkkyRQ.js} +1 -1
  9. package/dist/broadcast_to-CMlkG8NS.js +44 -0
  10. package/dist/{concat-DvWM7HGZ.js → concat-Cxbo2sOz.js} +3 -3
  11. package/dist/{dropout-DFEXTPV0.js → dropout-kbDY39Ci.js} +1 -1
  12. package/dist/{gather-C5D8PxwA.js → gather-Bxe1Qip8.js} +4 -4
  13. package/dist/{gpgpu_math-CUzjlO9A.js → gpgpu_math-C0zyxKFi.js} +1 -1
  14. package/dist/{index--6vO-cOz.js → index-iNhkcAEQ.js} +82 -82
  15. package/dist/{kernel_funcs_utils-C6YBCuOt.js → kernel_funcs_utils-C4eIk4fE.js} +20 -20
  16. package/dist/layers/BaseLayer.d.ts +28 -4
  17. package/dist/layers/BaseLayer.js +3 -16
  18. package/dist/layers/CausalSelfAttention.d.ts +22 -24
  19. package/dist/layers/CausalSelfAttention.js +73 -128
  20. package/dist/layers/MLP.d.ts +8 -15
  21. package/dist/layers/MLP.js +43 -81
  22. package/dist/layers/RMSNorm.d.ts +5 -10
  23. package/dist/layers/RMSNorm.js +13 -29
  24. package/dist/layers/RoPECache.js +14 -12
  25. package/dist/layers/TiedEmbedding.d.ts +6 -16
  26. package/dist/layers/TiedEmbedding.js +5 -5
  27. package/dist/layers/TransformerBlock.d.ts +12 -16
  28. package/dist/layers/TransformerBlock.js +20 -41
  29. package/dist/{log_sum_exp-CiEy1aUe.js → log_sum_exp-CkumwesB.js} +11 -11
  30. package/dist/main.js +1 -1
  31. package/dist/{mat_mul-BEHRPMh0.js → mat_mul-D0SifYfJ.js} +3 -3
  32. package/dist/{max-BUShNgfh.js → max-CYaAjEEp.js} +3 -3
  33. package/dist/{moments-DYOHXoRV.js → moments-B06NlR_V.js} +6 -6
  34. package/dist/{norm-DSva3hI3.js → norm-D3676xIo.js} +7 -7
  35. package/dist/{ones-D6kB8bdY.js → ones-BIeFnPHR.js} +2 -2
  36. package/dist/ops/appendCache.js +4 -4
  37. package/dist/ops/attentionMask.d.ts +1 -1
  38. package/dist/ops/attentionMask.js +4 -4
  39. package/dist/ops/cpu/appendCache.js +2 -2
  40. package/dist/ops/cpu/attentionMask.js +14 -15
  41. package/dist/ops/cpu/fusedSoftmax.js +2 -2
  42. package/dist/ops/cpu/gatherSub.js +5 -5
  43. package/dist/ops/cpu/gelu.js +1 -1
  44. package/dist/ops/cpu/matMulGelu.js +1 -1
  45. package/dist/ops/cpu/matMulMul.d.ts +1 -0
  46. package/dist/ops/cpu/matMulMul.js +17 -0
  47. package/dist/ops/cpu/mulDropout.js +1 -1
  48. package/dist/ops/cpu/normRMS.js +1 -1
  49. package/dist/ops/cpu/qkv.js +3 -3
  50. package/dist/ops/cpu/rope.js +5 -5
  51. package/dist/ops/cpu/scatterSub.js +8 -8
  52. package/dist/ops/fusedSoftmax.js +1 -1
  53. package/dist/ops/gatherSub.js +1 -1
  54. package/dist/ops/gelu.js +1 -1
  55. package/dist/ops/grads/attentionMask.js +13 -9
  56. package/dist/ops/grads/fusedSoftmax.js +12 -9
  57. package/dist/ops/grads/gelu.js +1 -1
  58. package/dist/ops/grads/matMulGelu.js +1 -1
  59. package/dist/ops/grads/normRMS.js +1 -1
  60. package/dist/ops/grads/qkv.js +19 -9
  61. package/dist/ops/grads/rope.js +1 -1
  62. package/dist/ops/matMulGelu.js +1 -1
  63. package/dist/ops/matMulMul.d.ts +2 -0
  64. package/dist/ops/matMulMul.js +9 -0
  65. package/dist/ops/mulDrop.js +1 -1
  66. package/dist/ops/node/sparseCrossEntropy.js +1 -1
  67. package/dist/ops/normRMS.js +1 -1
  68. package/dist/ops/qkv.js +1 -1
  69. package/dist/ops/scatterSub.js +1 -1
  70. package/dist/ops/webgl/appendCache.js +1 -1
  71. package/dist/ops/webgl/attentionMask.js +13 -12
  72. package/dist/ops/webgl/fusedSoftmax.js +43 -40
  73. package/dist/ops/webgl/gatherSub.js +1 -1
  74. package/dist/ops/webgl/gelu.js +2 -2
  75. package/dist/ops/webgl/matMulGelu.js +17 -17
  76. package/dist/ops/webgl/matMulMul.d.ts +14 -0
  77. package/dist/ops/webgl/matMulMul.js +28 -0
  78. package/dist/ops/webgl/mulDropout.js +1 -1
  79. package/dist/ops/webgl/normRMS.js +29 -21
  80. package/dist/ops/webgl/qkv.js +1 -1
  81. package/dist/ops/webgl/rope.js +1 -1
  82. package/dist/ops/webgl/scatterSub.js +1 -1
  83. package/dist/ops-ObfXLHYQ.js +1269 -0
  84. package/dist/{range-C_vpUjBu.js → range-BsFU-SNG.js} +1 -1
  85. package/dist/{reshape-z51Eu-re.js → reshape-DxTPgnwL.js} +3 -3
  86. package/dist/{sin-H567uayl.js → sin-BOX-JVAj.js} +5 -5
  87. package/dist/slice_util-D-kaD4ZV.js +49 -0
  88. package/dist/{softmax-Dsxflvdl.js → softmax-BjsptB07.js} +2 -2
  89. package/dist/{split-B_k_jwud.js → split-BCbrzthj.js} +4 -4
  90. package/dist/{stack-CmqSdsfs.js → stack--cqr9Dgc.js} +2 -2
  91. package/dist/{sum-DdkDf2MG.js → sum-B_92TaHD.js} +5 -5
  92. package/dist/{tensor-BGYi41cj.js → tensor-CfiPXsW4.js} +1 -1
  93. package/dist/{tensor2d-DUr_htjt.js → tensor2d-tSxWdFMH.js} +1 -1
  94. package/dist/tfjs_backend-NucKez4s.js +1010 -0
  95. package/dist/training/AdamExt.js +1 -1
  96. package/dist/training/DatasetBuilder.js +44 -44
  97. package/dist/training/Evaluator.js +6 -6
  98. package/dist/training/FullTrainer.js +1 -1
  99. package/dist/training/Trainer.js +7 -7
  100. package/dist/training/sparseCrossEntropy.js +4 -4
  101. package/dist/utilities/dummy.js +10 -10
  102. package/dist/utilities/generate.js +3 -3
  103. package/dist/utilities/load.js +1 -1
  104. package/dist/utilities/profile.js +1 -1
  105. package/dist/utilities/save.js +10 -8
  106. package/dist/utilities/weights.js +2 -2
  107. package/dist/{zeros-8xl-W2DC.js → zeros-NMYTayy7.js} +3 -3
  108. package/package.json +1 -1
  109. package/dist/slice_util-BdhYwFY_.js +0 -90
  110. package/dist/tfjs_backend-DuKis_xG.js +0 -2271
  111. package/dist/variable-BJTZ3jOy.js +0 -23
@@ -0,0 +1,135 @@
1
+ import { E as p, V as v, c as _, e as o, W as V } from "./index-iNhkcAEQ.js";
2
+ /**
3
+ * @license
4
+ * Copyright 2018 Google LLC. All Rights Reserved.
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ * =============================================================================
17
+ */
18
+ function E(l, t = !0, r, e) {
19
+ return p.makeVariable(l, t, r, e);
20
+ }
21
+ class m {
22
+ parent;
23
+ config;
24
+ _variables = /* @__PURE__ */ new Map();
25
+ _trainable = !0;
26
+ children = [];
27
+ constructor(t, r) {
28
+ this.config = t, this.parent = r, this.parent && this.parent.children.push(this);
29
+ }
30
+ getProfiler() {
31
+ return this.config.layerConfig.profiler;
32
+ }
33
+ startMemory() {
34
+ this.config.layerConfig.profiler?.startMemory();
35
+ }
36
+ endMemory(t) {
37
+ this.config.layerConfig.profiler?.endMemory(t);
38
+ }
39
+ addVariable(t, r) {
40
+ this._variables.set(t, r || null);
41
+ }
42
+ get variables() {
43
+ const t = Array.from(this._variables.values()).filter((e) => e !== null), r = this.children.flatMap((e) => e.variables);
44
+ return [...t, ...r];
45
+ }
46
+ get trainableVariables() {
47
+ const t = Array.from(this._variables.values()).filter(
48
+ (e) => e !== null && e.trainable
49
+ ), r = this.children.flatMap((e) => e.trainableVariables);
50
+ return [...t, ...r];
51
+ }
52
+ get trainable() {
53
+ return this._trainable;
54
+ }
55
+ set trainable(t) {
56
+ this._trainable = t, this._variables.forEach((r) => {
57
+ r && (r.trainable = t);
58
+ }), this.children.forEach((r) => {
59
+ r.trainable = t;
60
+ });
61
+ }
62
+ getVariable(t) {
63
+ const r = this._variables.get(t);
64
+ if (!r)
65
+ throw new Error(`Variable ${t} not found`);
66
+ return r;
67
+ }
68
+ hasVariable(t) {
69
+ return this._variables.get(t) !== null;
70
+ }
71
+ setVariable(t, r) {
72
+ if (!this._variables.has(t))
73
+ throw new Error(`Variable ${t} not found`);
74
+ this._variables.set(t, r);
75
+ }
76
+ saveWeights(t) {
77
+ this._variables.forEach((r, e) => {
78
+ r && t.set(e, [r.clone()]);
79
+ }), this.children.forEach((r) => {
80
+ r.saveWeights(t);
81
+ });
82
+ }
83
+ loadWeights(t) {
84
+ this._variables.forEach((r, e) => {
85
+ const i = t.get(e)?.[0];
86
+ if (!i)
87
+ throw new Error(`Weights for ${e} not found`);
88
+ r ? r.assign(i) : this._variables.set(e, E(i, this._trainable));
89
+ }), this.children.forEach((r) => {
90
+ r.loadWeights(t);
91
+ });
92
+ }
93
+ dispose() {
94
+ this._variables.forEach((t) => {
95
+ t?.dispose();
96
+ }), this._variables.clear();
97
+ }
98
+ build() {
99
+ }
100
+ dropout(t) {
101
+ return t;
102
+ }
103
+ call(t, ...r) {
104
+ this.build();
105
+ const e = this.forward(t, ...r);
106
+ if (t.training && e instanceof v) {
107
+ const i = this.dropout(e);
108
+ return i !== e && e.dispose(), i;
109
+ } else
110
+ return e;
111
+ }
112
+ callCheckpoint(t, ...r) {
113
+ return this.build(), this.checkpointingFn(t, ...r);
114
+ }
115
+ checkpointingFn(t, ...r) {
116
+ const e = this.trainableVariables, s = _((...a) => {
117
+ const h = a[a.length - 1], n = a.slice(0, r.length), c = this.forward(t, ...n);
118
+ return h(n), { value: c, gradFunc: (f, u) => {
119
+ const b = o().state.activeTape;
120
+ o().state.activeTape = [];
121
+ const d = V((...g) => this.forward(t, ...g.slice(0, n.length)))([...u, ...e], f);
122
+ return o().state.activeTape = b, d;
123
+ } };
124
+ })(...r, ...e);
125
+ if (t.training) {
126
+ const a = this.dropout(s);
127
+ return a !== s && s.dispose(), a;
128
+ } else
129
+ return s;
130
+ }
131
+ }
132
+ export {
133
+ m as B,
134
+ E as v
135
+ };
package/dist/Generator.js CHANGED
@@ -1,70 +1,73 @@
1
1
  import { E as u } from "./index-Dwqa6Zy2.js";
2
- import "./index--6vO-cOz.js";
3
- import { t as d } from "./tensor2d-DUr_htjt.js";
4
- import { c as p } from "./concat-DvWM7HGZ.js";
2
+ import "./index-iNhkcAEQ.js";
3
+ import { t as d } from "./tensor2d-tSxWdFMH.js";
4
+ import { c as p } from "./concat-Cxbo2sOz.js";
5
5
  class w extends u {
6
- constructor(s, e) {
7
- super(), this.model = s, this.tokeniser = e;
6
+ constructor(i, t) {
7
+ super(), this.model = i, this.tokeniser = t;
8
8
  }
9
9
  active = !1;
10
- async tokenisePrompt(s) {
11
- const e = s ? await this.tokeniser.tokenise([s], !0) : [[this.tokeniser.eosToken]];
12
- return d(e, [1, e[0].length], "int32");
10
+ async tokenisePrompt(i) {
11
+ const t = i ? await this.tokeniser.tokenise([i], !0) : [[this.tokeniser.eosToken]];
12
+ return d(t, [1, t[0].length], "int32");
13
13
  }
14
- async generateNoCache(s, e) {
15
- let t = await this.tokenisePrompt(s), n = s || "";
16
- const o = e?.maxLength ?? 1e3;
17
- for (let a = 0; a < o && this.active; a++) {
14
+ async generateNoCache(i, t) {
15
+ let s = await this.tokenisePrompt(i), o = i || "";
16
+ const n = t?.maxLength ?? 1e3;
17
+ for (let a = 0; a < n && this.active; a++) {
18
18
  const {
19
- output: i,
19
+ output: e,
20
20
  attention: c,
21
21
  probabilities: l
22
- } = this.model.generate(t, void 0, e), h = t;
23
- t = p([t, i], 1), h.dispose();
24
- const r = await this.processResponse(i, c, l);
25
- if (i.dispose(), r === null)
22
+ } = this.model.generate(s, void 0, t), h = s;
23
+ s = p([s, e], 1), h.dispose();
24
+ const r = await this.processResponse(e, c, l);
25
+ if (e.dispose(), r === null)
26
26
  break;
27
- n += r;
27
+ o += r;
28
28
  }
29
- return t.dispose(), n;
29
+ return s.dispose(), o;
30
30
  }
31
- async processResponse(s, e, t) {
32
- const n = (await s.array())[0][0];
33
- if (n === this.tokeniser.eosToken)
31
+ async processResponse(i, t, s) {
32
+ const o = (await i.array())[0][0];
33
+ if (o === this.tokeniser.eosToken)
34
34
  return null;
35
- const o = await this.tokeniser.decode([n]);
35
+ const n = await this.tokeniser.decode([o]);
36
36
  let a;
37
- e && (a = await e.array(), e.dispose());
38
- let i;
39
- return t && (i = await t.array(), t.dispose()), this.emit("tokens", [n], o, a, i), o;
37
+ t && (a = await t.array(), t.dispose());
38
+ let e;
39
+ return s && (e = await s.array(), s.dispose()), this.emit("tokens", [o], n, a, e), n;
40
40
  }
41
- async generateCache(s, e) {
42
- let t = await this.tokenisePrompt(s), n = s || "";
43
- const o = new Array(this.model.config.gpt.nLayer).fill(void 0), a = e?.maxLength ?? 1e3;
44
- for (let i = 0; i < a && this.active; i++) {
41
+ async generateCache(i, t) {
42
+ let s = await this.tokenisePrompt(i), o = i || "";
43
+ const n = new Array(this.model.config.gpt.nLayer);
44
+ for (let e = 0; e < this.model.config.gpt.nLayer; e++)
45
+ n[e] = { k: void 0, v: void 0, length: 0, cumulativeLength: 0 };
46
+ const a = t?.maxLength ?? 1e3;
47
+ for (let e = 0; e < a && this.active; e++) {
45
48
  const {
46
49
  output: c,
47
50
  attention: l,
48
51
  probabilities: h
49
- } = this.model.generate(t, o, {
50
- ...e,
52
+ } = this.model.generate(s, n, {
53
+ ...t,
51
54
  usePadding: !1
52
55
  });
53
- t.dispose(), t = c;
56
+ s.dispose(), s = c;
54
57
  const r = await this.processResponse(c, l, h);
55
58
  if (r === null)
56
59
  break;
57
- n += r;
60
+ o += r;
58
61
  }
59
- return o.forEach((i) => {
60
- i && (i.k.dispose(), i.v.dispose());
61
- }), t.dispose(), n;
62
+ return n.forEach((e) => {
63
+ e && (e.k && e.k.dispose(), e.v && e.v.dispose());
64
+ }), s.dispose(), o;
62
65
  }
63
- async generate(s, e) {
64
- const t = s && s.length > this.model.config.gpt.blockSize ? s.slice(-this.model.config.gpt.blockSize) : s;
66
+ async generate(i, t) {
67
+ const s = i && i.length > this.model.config.gpt.blockSize ? i.slice(-this.model.config.gpt.blockSize) : i;
65
68
  this.active = !0, this.emit("start");
66
- const o = await (this.model.config.gpt.useRope && !e?.noCache && !e?.includeAttention ? this.generateCache(t, e) : this.generateNoCache(t, e));
67
- return this.active = !1, this.emit("stop"), o;
69
+ const n = await (this.model.config.gpt.useRope && !t?.noCache ? this.generateCache(s, t) : this.generateNoCache(s, t));
70
+ return this.active = !1, this.emit("stop"), n;
68
71
  }
69
72
  stop() {
70
73
  this.active = !1;
@@ -1,7 +1,7 @@
1
1
  import { GPTConfig } from './config';
2
- import { KVCache } from './layers/CausalSelfAttention';
3
- import { default as BaseLayer } from './layers/BaseLayer';
4
- import { Tensor, Variable } from '@tensorflow/tfjs-core';
2
+ import { AttentionScores, KVCache } from './layers/CausalSelfAttention';
3
+ import { default as BaseLayer, ForwardAttributes } from './layers/BaseLayer';
4
+ import { Tensor } from '@tensorflow/tfjs-core';
5
5
  export interface TrainingLogEntry {
6
6
  loss: number;
7
7
  valLoss?: number;
@@ -14,10 +14,15 @@ export interface GenerateOptions {
14
14
  temperature?: number;
15
15
  topK?: number;
16
16
  usePadding?: boolean;
17
- includeAttention?: boolean;
17
+ attentionScores?: AttentionScores;
18
18
  includeProbabilities?: boolean;
19
19
  }
20
- export default class NanoGPT extends BaseLayer {
20
+ export interface ModelForwardAttributes extends ForwardAttributes {
21
+ cache?: KVCache[];
22
+ attentionScores?: AttentionScores;
23
+ seed?: number;
24
+ }
25
+ export default class NanoGPT extends BaseLayer<ModelForwardAttributes> {
21
26
  private wte;
22
27
  private wpe?;
23
28
  private drop;
@@ -28,22 +33,13 @@ export default class NanoGPT extends BaseLayer {
28
33
  constructor(config?: Partial<GPTConfig>);
29
34
  get checkpointing(): boolean;
30
35
  set checkpointing(value: boolean);
31
- get variables(): Variable[];
32
- saveWeights(): Map<string, Tensor[]>;
33
- loadWeights(weights: Map<string, Tensor[]>): void;
34
36
  private inputPhase;
35
37
  setSkipMask(mask: boolean[]): void;
36
38
  setTrainableMask(mask: boolean[]): void;
37
- set trainable(value: boolean);
38
39
  private validateInput;
39
40
  private calculateLoss;
40
- private computeAttentionRollout;
41
- forward(idx: Tensor, targets?: Tensor, training?: boolean, includeAttention?: boolean, cache?: (KVCache | undefined)[]): {
42
- logits: Tensor;
43
- loss?: Tensor;
44
- attention?: Tensor;
45
- };
46
- generate(idx: Tensor, cache?: (KVCache | undefined)[], options?: GenerateOptions): {
41
+ forward(attrs: ModelForwardAttributes, idx: Tensor, targets?: Tensor): Tensor[];
42
+ generate(idx: Tensor, cache?: KVCache[], options?: GenerateOptions): {
47
43
  output: Tensor;
48
44
  attention?: Tensor;
49
45
  probabilities?: Tensor;