@genai-fi/nanogpt 0.2.12 → 0.3.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 (115) hide show
  1. package/dist/Generator.js +30 -25
  2. package/dist/NanoGPTModel.d.ts +13 -14
  3. package/dist/NanoGPTModel.js +167 -85
  4. package/dist/TeachableLLM.d.ts +3 -5
  5. package/dist/TeachableLLM.js +47 -35
  6. package/dist/Trainer.js +8 -8
  7. package/dist/concat-BIZS_td9.js +33 -0
  8. package/dist/data/parquet.js +1 -1
  9. package/dist/exports_layers-7idKoYqh.js +25 -0
  10. package/dist/{sum-D7fu15XL.js → gather-BPGW8RsB.js} +6 -8
  11. package/dist/index-C4L8Cm77.js +349 -0
  12. package/dist/{index-YPKosni4.js → index-pWA4_lUh.js} +1020 -782
  13. package/dist/layers/CausalSelfAttention.d.ts +11 -11
  14. package/dist/layers/CausalSelfAttention.js +71 -63
  15. package/dist/layers/MLP.d.ts +6 -7
  16. package/dist/layers/MLP.js +18 -16
  17. package/dist/layers/RMSNorm.d.ts +6 -7
  18. package/dist/layers/RMSNorm.js +15 -13
  19. package/dist/layers/RoPECache.d.ts +4 -5
  20. package/dist/layers/RoPECache.js +36 -12
  21. package/dist/layers/TiedEmbedding.d.ts +7 -8
  22. package/dist/layers/TiedEmbedding.js +16 -418
  23. package/dist/layers/TransformerBlock.d.ts +8 -9
  24. package/dist/layers/TransformerBlock.js +12 -12
  25. package/dist/main.d.ts +1 -0
  26. package/dist/main.js +35 -21
  27. package/dist/{mat_mul-Bu7bhLms.js → mat_mul-D7_a4KJn.js} +5 -5
  28. package/dist/moments-DfcpfwKi.js +132 -0
  29. package/dist/ones-Cog-G2ag.js +29 -0
  30. package/dist/ops/appendCache.d.ts +2 -0
  31. package/dist/ops/appendCache.js +9 -0
  32. package/dist/ops/attentionMask.d.ts +1 -1
  33. package/dist/ops/attentionMask.js +7 -85
  34. package/dist/ops/cpu/appendCache.d.ts +2 -0
  35. package/dist/ops/cpu/appendCache.js +28 -0
  36. package/dist/ops/cpu/attentionMask.js +18 -0
  37. package/dist/ops/cpu/gatherSub.d.ts +1 -0
  38. package/dist/ops/cpu/gatherSub.js +34 -0
  39. package/dist/ops/cpu/qkv.d.ts +5 -0
  40. package/dist/ops/cpu/qkv.js +38 -0
  41. package/dist/ops/cpu/rope.d.ts +6 -0
  42. package/dist/ops/cpu/rope.js +38 -0
  43. package/dist/ops/cpu/scatterSub.d.ts +1 -0
  44. package/dist/ops/cpu/scatterSub.js +70 -0
  45. package/dist/ops/gatherSub.d.ts +1 -1
  46. package/dist/ops/gatherSub.js +6 -63
  47. package/dist/ops/grads/attentionMask.d.ts +1 -0
  48. package/dist/ops/grads/attentionMask.js +21 -0
  49. package/dist/ops/grads/qkv.d.ts +1 -0
  50. package/dist/ops/grads/qkv.js +20 -0
  51. package/dist/ops/grads/rope.d.ts +1 -0
  52. package/dist/ops/grads/rope.js +14 -0
  53. package/dist/ops/node/sparseCrossEntropy.js +1 -1
  54. package/dist/ops/qkv.d.ts +1 -6
  55. package/dist/ops/qkv.js +7 -124
  56. package/dist/ops/rope.d.ts +0 -5
  57. package/dist/ops/rope.js +7 -151
  58. package/dist/ops/scatterSub.d.ts +1 -1
  59. package/dist/ops/scatterSub.js +6 -147
  60. package/dist/ops/webgl/appendCache.d.ts +1 -0
  61. package/dist/ops/webgl/appendCache.js +43 -0
  62. package/dist/ops/webgl/attentionMask.d.ts +1 -0
  63. package/dist/ops/webgl/attentionMask.js +43 -0
  64. package/dist/ops/webgl/gatherSub.d.ts +1 -0
  65. package/dist/ops/webgl/gatherSub.js +27 -0
  66. package/dist/ops/webgl/qkv.d.ts +1 -0
  67. package/dist/ops/webgl/qkv.js +46 -0
  68. package/dist/ops/webgl/rope.d.ts +1 -0
  69. package/dist/ops/webgl/rope.js +56 -0
  70. package/dist/ops/webgl/scatterSub.d.ts +1 -0
  71. package/dist/ops/webgl/scatterSub.js +27 -0
  72. package/dist/{parquet-BRl5lE_I.js → parquet-C0Tlmv9c.js} +3045 -3048
  73. package/dist/random_width-PbCt7RXv.js +15489 -0
  74. package/dist/range-CcDl05lo.js +26 -0
  75. package/dist/{reshape-DmnmKT6r.js → reshape-C8CR_Bad.js} +3 -3
  76. package/dist/sin-BJIrfnj7.js +47 -0
  77. package/dist/softmax-Be_lsqUc.js +105 -0
  78. package/dist/{complex-CJ-qCcLB.js → split-DZbvruEP.js} +6 -8
  79. package/dist/stack-BMm-efee.js +27 -0
  80. package/dist/sum-C7Mgy9Bw.js +104 -0
  81. package/dist/tensor-DJVbYhh1.js +24 -0
  82. package/dist/tensor2d-ZuQSh2D-.js +30 -0
  83. package/dist/tokeniser/bpe.d.ts +17 -6
  84. package/dist/tokeniser/bpe.js +88 -60
  85. package/dist/training/AdamExt.js +1 -1
  86. package/dist/training/DatasetBuilder.d.ts +6 -6
  87. package/dist/training/DatasetBuilder.js +1262 -17
  88. package/dist/training/Evaluator.d.ts +3 -2
  89. package/dist/training/FullTrainer.d.ts +9 -8
  90. package/dist/training/FullTrainer.js +26 -25
  91. package/dist/training/LayerTrainer.d.ts +9 -8
  92. package/dist/training/LayerTrainer.js +34 -33
  93. package/dist/training/Trainer.d.ts +22 -21
  94. package/dist/training/Trainer.js +21 -18
  95. package/dist/training/sparseCrossEntropy.js +22 -166
  96. package/dist/utilities/dummy.js +10 -8
  97. package/dist/utilities/generate.js +14 -11
  98. package/dist/utilities/load.d.ts +1 -2
  99. package/dist/utilities/load.js +37 -35
  100. package/dist/utilities/profile.js +1 -1
  101. package/dist/utilities/save.js +14 -9
  102. package/dist/utilities/tokenParse.d.ts +1 -1
  103. package/dist/utilities/tokenParse.js +7 -61
  104. package/dist/utilities/weights.d.ts +3 -3
  105. package/dist/utilities/weights.js +21 -19
  106. package/dist/variable-Dl_ub3pk.js +23 -0
  107. package/dist/{stack-BtKpB0Ry.js → zeros-CCy9C3uU.js} +18 -16
  108. package/package.json +2 -1
  109. package/dist/assets/worker-BYeSPNkq.js +0 -1
  110. package/dist/tokeniser/NodeTokeniser.d.ts +0 -20
  111. package/dist/tokeniser/NodeTokeniser.js +0 -46
  112. package/dist/tokeniser/WebTokeniser.d.ts +0 -18
  113. package/dist/tokeniser/WebTokeniser.js +0 -96
  114. package/dist/tokeniser/worker.js +0 -53
  115. /package/dist/{tokeniser/worker.d.ts → ops/cpu/attentionMask.d.ts} +0 -0
@@ -1,8 +1,9 @@
1
1
  import { default as NanoGPT } from '../NanoGPTModel';
2
- import { default as TF } from '@tensorflow/tfjs';
2
+ import { Dataset } from '@tensorflow/tfjs-data';
3
+ import { TensorContainer } from '@tensorflow/tfjs-core';
3
4
  export default class Evaluator {
4
5
  private model;
5
6
  private iterator;
6
- constructor(model: NanoGPT, dataset: TF.data.Dataset<TF.TensorContainer>);
7
+ constructor(model: NanoGPT, dataset: Dataset<TensorContainer>);
7
8
  evaluate(maxBatches?: number): Promise<number>;
8
9
  }
@@ -1,15 +1,16 @@
1
1
  import { ITokeniser } from '../tokeniser/type';
2
2
  import { default as NanoGPT } from '../NanoGPTModel';
3
- import { default as TF } from '@tensorflow/tfjs';
4
3
  import { default as GPTTrainer, TrainingOptions } from './Trainer';
4
+ import { Tensor } from '@tensorflow/tfjs-core';
5
+ import { Dataset } from '@tensorflow/tfjs-data';
5
6
  export default class FullTrainer extends GPTTrainer {
6
- constructor(tf: typeof TF, model: NanoGPT, tokenizer: ITokeniser, learningRate?: number);
7
- trainOnDataset(dataset: TF.data.Dataset<{
8
- xs: TF.Tensor;
9
- ys: TF.Tensor;
10
- }>, options: Partial<TrainingOptions>, validationDataset?: TF.data.Dataset<{
11
- xs: TF.Tensor;
12
- ys: TF.Tensor;
7
+ constructor(model: NanoGPT, tokenizer: ITokeniser, learningRate?: number);
8
+ trainOnDataset(dataset: Dataset<{
9
+ xs: Tensor;
10
+ ys: Tensor;
11
+ }>, options: Partial<TrainingOptions>, validationDataset?: Dataset<{
12
+ xs: Tensor;
13
+ ys: Tensor;
13
14
  }>): Promise<{
14
15
  losses: number[];
15
16
  validationLosses: number[];
@@ -1,19 +1,20 @@
1
- import { generateText as L } from "../utilities/generate.js";
2
- import w from "./Trainer.js";
3
- import x from "./Evaluator.js";
4
- const g = {
1
+ import { generateText as w } from "../utilities/generate.js";
2
+ import x from "./Trainer.js";
3
+ import g from "./Evaluator.js";
4
+ import { a as h } from "../index-pWA4_lUh.js";
5
+ const S = {
5
6
  desiredLoss: 0.01,
6
7
  logInterval: 1,
7
8
  maxSteps: 1e3
8
9
  };
9
- class P extends w {
10
- constructor(r, i, o, n = 3e-4) {
11
- super(r, i, o, n);
10
+ class D extends x {
11
+ constructor(r, i, o = 3e-4) {
12
+ super(r, i, o);
12
13
  }
13
14
  // Train for multiple epochs using Dataset API - FIXED memory leaks
14
15
  async trainOnDataset(r, i, o) {
15
- const { desiredLoss: n, logInterval: m, onStep: l, prompt: c, maxSteps: d } = {
16
- ...g,
16
+ const { desiredLoss: m, logInterval: u, onStep: n, prompt: l, maxSteps: d } = {
17
+ ...S,
17
18
  ...i
18
19
  }, t = {
19
20
  step: 0,
@@ -24,45 +25,45 @@ class P extends w {
24
25
  ...this.lastState || {}
25
26
  };
26
27
  this.lastState = t, this.dummyPass(), this.model.trainable = !0;
27
- const u = Date.now();
28
+ const f = Date.now();
28
29
  this.running = !0;
29
- const h = o ? new x(this.model, o) : void 0, f = await r.iterator();
30
+ const c = o ? new g(this.model, o) : void 0, v = await r.iterator();
30
31
  try {
31
- for (; this.running && !(t.lastLoss < n); ) {
32
- const e = await f.next();
32
+ for (; this.running && !(t.lastLoss < m); ) {
33
+ const e = await v.next();
33
34
  if (e.done) break;
34
- const p = e.value, v = this.trainBatch(t, p), a = {
35
+ const p = e.value, L = this.trainBatch(t, p), a = {
35
36
  loss: t.lastLoss,
36
37
  step: t.step,
37
- time: Date.now() - u,
38
+ time: Date.now() - f,
38
39
  batchSize: p.xs.shape[0]
39
40
  };
40
- if (this.model.log.push(a), t.step % m === 0) {
41
- if (await v, h)
41
+ if (this.model.log.push(a), t.step % u === 0) {
42
+ if (await L, c)
42
43
  try {
43
- const s = await h.evaluate(5);
44
+ const s = await c.evaluate(5);
44
45
  t.validationLosses.push(s), a.valLoss = s;
45
46
  } catch (s) {
46
47
  console.error("Validation error:", s);
47
48
  }
48
- if (l) {
49
- if (c) {
50
- const s = await L(this.tokenizer, this.model, c, 100, {
49
+ if (n) {
50
+ if (l) {
51
+ const s = await w(this.tokenizer, this.model, l, 100, {
51
52
  temperature: 0.8
52
53
  });
53
54
  a.example = s;
54
55
  }
55
- await l(a);
56
+ await n(a);
56
57
  }
57
58
  }
58
59
  t.step >= d && this.stop();
59
60
  }
60
61
  } catch (e) {
61
- throw console.error("Training error:", e), this.tf.dispose(), e;
62
+ throw console.error("Training error:", e), h(), e;
62
63
  }
63
- return this.tf.dispose(), this.running = !1, { losses: t.losses, validationLosses: t.validationLosses };
64
+ return h(), this.running = !1, { losses: t.losses, validationLosses: t.validationLosses };
64
65
  }
65
66
  }
66
67
  export {
67
- P as default
68
+ D as default
68
69
  };
@@ -1,7 +1,8 @@
1
1
  import { ITokeniser } from '../tokeniser/type';
2
2
  import { default as NanoGPT } from '../NanoGPTModel';
3
- import { default as TF } from '@tensorflow/tfjs';
4
3
  import { default as GPTTrainer, TrainingOptions } from './Trainer';
4
+ import { Tensor } from '@tensorflow/tfjs-core';
5
+ import { Dataset } from '@tensorflow/tfjs-data';
5
6
  interface LayerTrainingOptions extends TrainingOptions {
6
7
  stepsPerLayer: number;
7
8
  maxPasses: number;
@@ -12,14 +13,14 @@ export default class LayerTrainer extends GPTTrainer {
12
13
  private trainingPattern;
13
14
  private startPass;
14
15
  private startLayer;
15
- constructor(tf: typeof TF, model: NanoGPT, tokenizer: ITokeniser, learningRate?: number);
16
+ constructor(model: NanoGPT, tokenizer: ITokeniser, learningRate?: number);
16
17
  private applyTrainingPattern;
17
- trainOnDataset(dataset: TF.data.Dataset<{
18
- xs: TF.Tensor;
19
- ys: TF.Tensor;
20
- }>, options: Partial<LayerTrainingOptions>, validationDataset?: TF.data.Dataset<{
21
- xs: TF.Tensor;
22
- ys: TF.Tensor;
18
+ trainOnDataset(dataset: Dataset<{
19
+ xs: Tensor;
20
+ ys: Tensor;
21
+ }>, options: Partial<LayerTrainingOptions>, validationDataset?: Dataset<{
22
+ xs: Tensor;
23
+ ys: Tensor;
23
24
  }>): Promise<{
24
25
  losses: number[];
25
26
  validationLosses: number[];
@@ -1,33 +1,34 @@
1
- import { generateText as S } from "../utilities/generate.js";
2
- import u from "./Trainer.js";
3
- import { schedule as v } from "./lwSchedule.js";
4
- import w from "./Evaluator.js";
5
- const T = {
1
+ import { generateText as u } from "../utilities/generate.js";
2
+ import v from "./Trainer.js";
3
+ import { schedule as w } from "./lwSchedule.js";
4
+ import T from "./Evaluator.js";
5
+ import { a as m } from "../index-pWA4_lUh.js";
6
+ const x = {
6
7
  desiredLoss: 0.01,
7
8
  logInterval: 1,
8
9
  stepsPerLayer: 400,
9
10
  maxPasses: 3,
10
11
  maxSteps: 1e3
11
12
  };
12
- class z extends u {
13
+ class E extends v {
13
14
  trainingPattern = [];
14
15
  startPass = 0;
15
16
  startLayer = 0;
16
- constructor(r, s, e, p = 3e-4) {
17
- if (super(r, s, e, p), this.trainingPattern = v[s.config.nLayer - 1] || [], s.log.length > 0) {
17
+ constructor(s, r, e = 3e-4) {
18
+ if (super(s, r, e), this.trainingPattern = w[s.config.nLayer - 1] || [], s.log.length > 0) {
18
19
  const i = s.log[s.log.length - 1];
19
20
  i.pass !== void 0 && i.layer !== void 0 && (this.startPass = i.pass, this.startLayer = i.layer, console.log(`Resuming training from pass ${this.startPass}, layer ${this.startLayer}`));
20
21
  }
21
22
  }
22
- applyTrainingPattern(r) {
23
- const s = r < this.trainingPattern.length ? r : this.trainingPattern.length - 1, e = this.trainingPattern[s];
24
- this.model.setSkipMask(e.skip), this.model.setTrainableMask(e.trainable), this.resetOptimizer(e.adam), console.log("Applied training pattern:", s, e);
23
+ applyTrainingPattern(s) {
24
+ const r = s < this.trainingPattern.length ? s : this.trainingPattern.length - 1, e = this.trainingPattern[r];
25
+ this.model.setSkipMask(e.skip), this.model.setTrainableMask(e.trainable), this.resetOptimizer(e.adam), console.log("Applied training pattern:", r, e);
25
26
  }
26
27
  // Train for multiple epochs using Dataset API - FIXED memory leaks
27
- async trainOnDataset(r, s, e) {
28
- const { desiredLoss: p, logInterval: i, stepsPerLayer: L, onLayerChange: o, onPassComplete: h, onStep: c, prompt: g } = {
29
- ...T,
30
- ...s
28
+ async trainOnDataset(s, r, e) {
29
+ const { desiredLoss: i, logInterval: L, stepsPerLayer: f, onLayerChange: o, onPassComplete: p, onStep: h, prompt: c } = {
30
+ ...x,
31
+ ...r
31
32
  }, t = {
32
33
  pass: 0,
33
34
  layerStep: 0,
@@ -39,51 +40,51 @@ class z extends u {
39
40
  validationLosses: []
40
41
  };
41
42
  this.dummyPass();
42
- const f = Date.now();
43
+ const d = Date.now();
43
44
  this.startPass = 0, this.startLayer = 0;
44
- const y = e ? new w(this.model, e) : void 0, d = await r.iterator();
45
+ const g = e ? new T(this.model, e) : void 0, P = await s.iterator();
45
46
  this.applyTrainingPattern(t.layerStep % this.trainingPattern.length);
46
47
  try {
47
- for (; !(t.lastLoss < p); ) {
48
- const n = await d.next();
48
+ for (; !(t.lastLoss < i); ) {
49
+ const n = await P.next();
49
50
  if (n.done) break;
50
- const m = n.value, P = this.trainBatch(t, m);
51
+ const y = n.value, S = this.trainBatch(t, y);
51
52
  t.stepSinceLayerChange++;
52
53
  const l = {
53
54
  loss: t.lastLoss,
54
55
  step: t.step,
55
- time: Date.now() - f,
56
- batchSize: m.xs.shape[0],
56
+ time: Date.now() - d,
57
+ batchSize: y.xs.shape[0],
57
58
  pass: t.pass,
58
59
  layer: t.layerStep % this.model.config.nLayer
59
60
  };
60
- if (this.model.log.push(l), t.step % i === 0) {
61
- if (await P, y)
61
+ if (this.model.log.push(l), t.step % L === 0) {
62
+ if (await S, g)
62
63
  try {
63
- const a = await y.evaluate(5);
64
+ const a = await g.evaluate(5);
64
65
  t.validationLosses.push(a), l.valLoss = a;
65
66
  } catch (a) {
66
67
  console.error("Validation error:", a);
67
68
  }
68
- if (c) {
69
- if (g) {
70
- const a = await S(this.tokenizer, this.model, g, 100, {
69
+ if (h) {
70
+ if (c) {
71
+ const a = await u(this.tokenizer, this.model, c, 100, {
71
72
  temperature: 0.8,
72
73
  topK: 10
73
74
  });
74
75
  l.example = a;
75
76
  }
76
- await c(l);
77
+ await h(l);
77
78
  }
78
79
  }
79
- t.stepSinceLayerChange >= L && (t.layerStep++, t.layerStep % this.model.config.nLayer === 0 ? (o && await o(t.layerStep, t.pass), h && await h(t.pass), t.pass++) : o && await o(t.layerStep, t.pass), t.stepSinceLayerChange = 0, this.applyTrainingPattern(t.layerStep % this.trainingPattern.length));
80
+ t.stepSinceLayerChange >= f && (t.layerStep++, t.layerStep % this.model.config.nLayer === 0 ? (o && await o(t.layerStep, t.pass), p && await p(t.pass), t.pass++) : o && await o(t.layerStep, t.pass), t.stepSinceLayerChange = 0, this.applyTrainingPattern(t.layerStep % this.trainingPattern.length));
80
81
  }
81
82
  } catch (n) {
82
- throw console.error("Training error:", n), this.tf.dispose(), n;
83
+ throw console.error("Training error:", n), m(), n;
83
84
  }
84
- return this.tf.dispose(), { losses: t.losses, validationLosses: t.validationLosses };
85
+ return m(), { losses: t.losses, validationLosses: t.validationLosses };
85
86
  }
86
87
  }
87
88
  export {
88
- z as default
89
+ E as default
89
90
  };
@@ -1,8 +1,10 @@
1
1
  import { ITokeniser } from '../tokeniser/type';
2
2
  import { DatasetBuilder } from './DatasetBuilder';
3
3
  import { default as NanoGPT, TrainingLogEntry } from '../NanoGPTModel';
4
- import { default as TF } from '@tensorflow/tfjs';
5
4
  import { default as AdamExt } from './AdamExt';
5
+ import { TensorContainer } from '@tensorflow/tfjs-core/dist/tensor_types';
6
+ import { Scalar, Tensor } from '@tensorflow/tfjs-core';
7
+ import { Dataset } from '@tensorflow/tfjs-data';
6
8
  export interface TrainingState {
7
9
  step: number;
8
10
  lastLoss: number;
@@ -28,11 +30,10 @@ export default abstract class GPTTrainer {
28
30
  protected model: NanoGPT;
29
31
  protected optimizer: AdamExt;
30
32
  protected datasetBuilder: DatasetBuilder;
31
- protected tf: typeof TF;
32
33
  protected learningRate: number;
33
34
  protected running: boolean;
34
35
  protected lastState?: TrainingState;
35
- constructor(tf: typeof TF, model: NanoGPT, tokenizer: ITokeniser, learningRate?: number);
36
+ constructor(model: NanoGPT, tokenizer: ITokeniser, learningRate?: number);
36
37
  setLearningRate(learningRate: number): void;
37
38
  reset(): void;
38
39
  stop(): void;
@@ -40,34 +41,34 @@ export default abstract class GPTTrainer {
40
41
  resetOptimizer(config?: AdamConfig): void;
41
42
  private printGradients;
42
43
  protected trainStep(batch: {
43
- xs: TF.Tensor;
44
- ys: TF.Tensor;
45
- }, dummy?: boolean, print?: boolean): TF.Scalar;
44
+ xs: Tensor;
45
+ ys: Tensor;
46
+ }, dummy?: boolean, print?: boolean): Scalar;
46
47
  protected dummyPass(): void;
47
48
  protected trainBatch(state: TrainingState, batch: {
48
- xs: TF.Tensor;
49
- ys: TF.Tensor;
49
+ xs: Tensor;
50
+ ys: Tensor;
50
51
  }): Promise<number>;
51
- abstract trainOnDataset(dataset: TF.data.Dataset<{
52
- xs: TF.Tensor;
53
- ys: TF.Tensor;
54
- }>, options: Partial<TrainingOptions>, validationDataset?: TF.data.Dataset<{
55
- xs: TF.Tensor;
56
- ys: TF.Tensor;
52
+ abstract trainOnDataset(dataset: Dataset<{
53
+ xs: Tensor;
54
+ ys: Tensor;
55
+ }>, options: Partial<TrainingOptions>, validationDataset?: Dataset<{
56
+ xs: Tensor;
57
+ ys: Tensor;
57
58
  }>): Promise<{
58
59
  losses: number[];
59
60
  validationLosses: number[];
60
61
  }>;
61
62
  createTrainValidationSplit(textData: string[], batchSize?: number, validationSplit?: number): Promise<{
62
- trainDataset: TF.data.Dataset<{
63
- xs: TF.Tensor;
64
- ys: TF.Tensor;
63
+ trainDataset: Dataset<{
64
+ xs: Tensor;
65
+ ys: Tensor;
65
66
  }>;
66
- validationDataset: TF.data.Dataset<{
67
- xs: TF.Tensor;
68
- ys: TF.Tensor;
67
+ validationDataset: Dataset<{
68
+ xs: Tensor;
69
+ ys: Tensor;
69
70
  }>;
70
71
  }>;
71
- createDataset(textData: string[], batchSize?: number): Promise<TF.data.Dataset<TF.TensorContainer>>;
72
+ createDataset(textData: string[], batchSize?: number): Promise<Dataset<TensorContainer>>;
72
73
  dispose(): void;
73
74
  }
@@ -1,13 +1,16 @@
1
- import { DatasetBuilder as d } from "./DatasetBuilder.js";
1
+ import { DatasetBuilder as p } from "./DatasetBuilder.js";
2
2
  import h from "./AdamExt.js";
3
- class g {
4
- constructor(t, s, e, i = 1e-3) {
5
- this.tokenizer = e, this.tf = t, this.model = s, this.learningRate = i, this.resetOptimizer(), this.datasetBuilder = new d(this.tf, e, s.config.blockSize);
3
+ import { t as g, v as u, a as o } from "../index-pWA4_lUh.js";
4
+ import { m as y, a as f, b as S, n as z } from "../moments-DfcpfwKi.js";
5
+ import { m as b } from "../sum-C7Mgy9Bw.js";
6
+ import { z as n } from "../zeros-CCy9C3uU.js";
7
+ class M {
8
+ constructor(t, s, e = 1e-3) {
9
+ this.tokenizer = s, this.model = t, this.learningRate = e, this.resetOptimizer(), this.datasetBuilder = new p(s, t.config.blockSize);
6
10
  }
7
11
  model;
8
12
  optimizer;
9
13
  datasetBuilder;
10
- tf;
11
14
  learningRate;
12
15
  running = !1;
13
16
  lastState;
@@ -42,21 +45,21 @@ class g {
42
45
  printGradients(t) {
43
46
  Object.keys(t).forEach((s) => {
44
47
  const e = t[s];
45
- console.log(`${s}:`), console.log(` Shape: ${e.shape}`), console.log(` Mean: ${this.tf.mean(e).dataSync()[0]}`), console.log(` Std: ${this.tf.moments(e).variance.sqrt().dataSync()[0]}`), console.log(` Min: ${this.tf.min(e).dataSync()[0]}`), console.log(` Max: ${this.tf.max(e).dataSync()[0]}`), console.log(` Norm: ${this.tf.norm(e).dataSync()[0]}`);
48
+ console.log(`${s}:`), console.log(` Shape: ${e.shape}`), console.log(` Mean: ${y(e).dataSync()[0]}`), console.log(` Std: ${f(e).variance.sqrt().dataSync()[0]}`), console.log(` Min: ${S(e).dataSync()[0]}`), console.log(` Max: ${b(e).dataSync()[0]}`), console.log(` Norm: ${z(e).dataSync()[0]}`);
46
49
  });
47
50
  }
48
51
  trainStep(t, s = !1, e = !1) {
49
- return this.tf.tidy(() => {
52
+ return g(() => {
50
53
  this.model.getProfiler()?.startMemory();
51
- const { xs: i, ys: a } = t, o = () => {
52
- const { loss: l, logits: c } = this.model.forward(i, a, !0);
53
- return c.dispose(), l;
54
- }, { value: n, grads: r } = this.tf.variableGrads(o);
55
- return s ? this.model.getProfiler()?.endMemory("Training") : (e && (console.log("-------"), this.printGradients(r), console.log("-------")), this.optimizer.applyGradients(r), this.model.getProfiler()?.endMemory("Training"), this.tf.dispose(r)), n;
54
+ const { xs: a, ys: r } = t, l = () => {
55
+ const { loss: d, logits: m } = this.model.forward(a, r, !0);
56
+ return m.dispose(), d;
57
+ }, { value: c, grads: i } = u(l);
58
+ return s ? this.model.getProfiler()?.endMemory("Training") : (e && (console.log("-------"), this.printGradients(i), console.log("-------")), this.optimizer.applyGradients(i), this.model.getProfiler()?.endMemory("Training"), o(i)), c;
56
59
  });
57
60
  }
58
61
  dummyPass() {
59
- const t = this.tf.zeros([1, this.model.config.blockSize], "int32"), s = this.tf.zeros([1, this.model.config.blockSize], "int32");
62
+ const t = n([1, this.model.config.blockSize], "int32"), s = n([1, this.model.config.blockSize], "int32");
60
63
  try {
61
64
  const e = this.trainStep({ xs: t, ys: s }, !0);
62
65
  e.dataSync(), e.dispose();
@@ -69,19 +72,19 @@ class g {
69
72
  async trainBatch(t, s) {
70
73
  try {
71
74
  const e = this.trainStep(s, !1, !1);
72
- return s.xs.dispose(), s.ys.dispose(), t.step++, t.totalSteps++, e.array().then((i) => (t.lastLoss = i, t.losses.push(t.lastLoss), e.dispose(), t.lastLoss));
75
+ return s.xs.dispose(), s.ys.dispose(), t.step++, t.totalSteps++, e.array().then((a) => (t.lastLoss = a, t.losses.push(t.lastLoss), e.dispose(), t.lastLoss));
73
76
  } catch (e) {
74
- throw console.error(`Error processing batch at step ${t.step}:`, e), this.tf.dispose(), e;
77
+ throw console.error(`Error processing batch at step ${t.step}:`, e), o(), e;
75
78
  }
76
79
  }
77
80
  async createTrainValidationSplit(t, s = 32, e = 0.1) {
78
- const i = await this.datasetBuilder.createTextDataset(t, s, 0, 1 - e), a = await this.datasetBuilder.createTextDataset(
81
+ const a = await this.datasetBuilder.createTextDataset(t, s, 0, 1 - e), r = await this.datasetBuilder.createTextDataset(
79
82
  t,
80
83
  s,
81
84
  1 - e,
82
85
  1
83
86
  );
84
- return { trainDataset: i, validationDataset: a };
87
+ return { trainDataset: a, validationDataset: r };
85
88
  }
86
89
  async createDataset(t, s = 32) {
87
90
  return await this.datasetBuilder.createTextDataset(t, s);
@@ -91,5 +94,5 @@ class g {
91
94
  }
92
95
  }
93
96
  export {
94
- g as default
97
+ M as default
95
98
  };
@@ -1,178 +1,34 @@
1
- import { gatherSub as _ } from "../ops/gatherSub.js";
2
- import { scatterSub as v } from "../ops/scatterSub.js";
3
- import { o as l, d, E as f, M as w, y as I, L as z, z as N, b as E, D as F, F as M, e as m, H as g, I as $, J as S } from "../index-YPKosni4.js";
4
- import { r as b } from "../reshape-DmnmKT6r.js";
5
- import { s as T } from "../sum-D7fu15XL.js";
6
- /**
7
- * @license
8
- * Copyright 2017 Google LLC. All Rights Reserved.
9
- * Licensed under the Apache License, Version 2.0 (the "License");
10
- * you may not use this file except in compliance with the License.
11
- * You may obtain a copy of the License at
12
- *
13
- * http://www.apache.org/licenses/LICENSE-2.0
14
- *
15
- * Unless required by applicable law or agreed to in writing, software
16
- * distributed under the License is distributed on an "AS IS" BASIS,
17
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
- * See the License for the specific language governing permissions and
19
- * limitations under the License.
20
- * =============================================================================
21
- */
22
- function D(n, s, t) {
23
- const a = n.length + s.length, e = [];
24
- let r = 0, c = 0;
25
- for (let o = 0; o < a; o++)
26
- t.indexOf(o) === -1 ? e.push(n[r++]) : e.push(s[c++]);
27
- return e;
28
- }
29
- function P(n, s) {
30
- const t = s.map((a) => 1);
31
- return D(n, t, s);
32
- }
33
- /**
34
- * @license
35
- * Copyright 2020 Google LLC. All Rights Reserved.
36
- * Licensed under the Apache License, Version 2.0 (the "License");
37
- * you may not use this file except in compliance with the License.
38
- * You may obtain a copy of the License at
39
- *
40
- * http://www.apache.org/licenses/LICENSE-2.0
41
- *
42
- * Unless required by applicable law or agreed to in writing, software
43
- * distributed under the License is distributed on an "AS IS" BASIS,
44
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
45
- * See the License for the specific language governing permissions and
46
- * limitations under the License.
47
- * =============================================================================
48
- */
49
- function A(n, s = null, t = !1) {
50
- const e = { x: d(n, "x", "max") }, r = { reductionIndices: s, keepDims: t };
51
- return f.runKernel(w, e, r);
52
- }
53
- const L = /* @__PURE__ */ l({ max_: A });
54
- /**
55
- * @license
56
- * Copyright 2018 Google LLC. All Rights Reserved.
57
- * Licensed under the Apache License, Version 2.0 (the "License");
58
- * you may not use this file except in compliance with the License.
59
- * You may obtain a copy of the License at
60
- *
61
- * http://www.apache.org/licenses/LICENSE-2.0
62
- *
63
- * Unless required by applicable law or agreed to in writing, software
64
- * distributed under the License is distributed on an "AS IS" BASIS,
65
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
66
- * See the License for the specific language governing permissions and
67
- * limitations under the License.
68
- * =============================================================================
69
- */
70
- function H(n) {
71
- const t = { x: d(n, "x", "exp") };
72
- return f.runKernel(I, t);
73
- }
74
- const J = /* @__PURE__ */ l({ exp_: H });
75
- /**
76
- * @license
77
- * Copyright 2018 Google LLC. All Rights Reserved.
78
- * Licensed under the Apache License, Version 2.0 (the "License");
79
- * you may not use this file except in compliance with the License.
80
- * You may obtain a copy of the License at
81
- *
82
- * http://www.apache.org/licenses/LICENSE-2.0
83
- *
84
- * Unless required by applicable law or agreed to in writing, software
85
- * distributed under the License is distributed on an "AS IS" BASIS,
86
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
87
- * See the License for the specific language governing permissions and
88
- * limitations under the License.
89
- * =============================================================================
90
- */
91
- function O(n) {
92
- const t = { x: d(n, "x", "log", "float32") };
93
- return f.runKernel(z, t);
94
- }
95
- const W = /* @__PURE__ */ l({ log_: O });
96
- /**
97
- * @license
98
- * Copyright 2020 Google LLC. All Rights Reserved.
99
- * Licensed under the Apache License, Version 2.0 (the "License");
100
- * you may not use this file except in compliance with the License.
101
- * You may obtain a copy of the License at
102
- *
103
- * http://www.apache.org/licenses/LICENSE-2.0
104
- *
105
- * Unless required by applicable law or agreed to in writing, software
106
- * distributed under the License is distributed on an "AS IS" BASIS,
107
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
108
- * See the License for the specific language governing permissions and
109
- * limitations under the License.
110
- * =============================================================================
111
- */
112
- function j(n, s = null, t = !1) {
113
- const a = d(n, "x", "logSumExp"), e = N(s, a.shape), r = L(
114
- a,
115
- e,
116
- !0
117
- /* keepDims */
118
- ), c = E(a, r), o = J(c), p = T(o, e), u = W(p), x = F(b(r, u.shape), u);
119
- if (t) {
120
- const h = P(x.shape, e);
121
- return b(x, h);
122
- }
123
- return x;
124
- }
125
- const q = /* @__PURE__ */ l({ logSumExp_: j });
126
- /**
127
- * @license
128
- * Copyright 2018 Google LLC. All Rights Reserved.
129
- * Licensed under the Apache License, Version 2.0 (the "License");
130
- * you may not use this file except in compliance with the License.
131
- * You may obtain a copy of the License at
132
- *
133
- * http://www.apache.org/licenses/LICENSE-2.0
134
- *
135
- * Unless required by applicable law or agreed to in writing, software
136
- * distributed under the License is distributed on an "AS IS" BASIS,
137
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
138
- * See the License for the specific language governing permissions and
139
- * limitations under the License.
140
- * =============================================================================
141
- */
142
- function B(n, s = -1) {
143
- const t = d(n, "logits", "softmax", "float32");
144
- if (s === -1 && (s = t.rank - 1), s !== t.rank - 1)
145
- throw Error(`Softmax along a non-last dimension is not yet supported. Logits was rank ${t.rank} and dim was ${s}`);
146
- const a = { logits: t }, e = { dim: s };
147
- return f.runKernel(M, a, e);
148
- }
149
- const Q = /* @__PURE__ */ l({ softmax_: B });
150
- function R(n, s) {
151
- return $(() => {
152
- const t = n.shape[n.shape.length - 1], e = n.shape.slice(0, -1).reduce((h, i) => h * i, 1), r = n.shape.length > 2 ? n.reshape([e, t]) : n, c = s.shape.length > 1 ? s.reshape([e]).cast("int32") : s.cast("int32"), o = L(r, -1, !0), p = E(r, o), u = q(p, -1);
153
- return _(u, c, p);
1
+ import { gatherSub as L } from "../ops/gatherSub.js";
2
+ import { scatterSub as y } from "../ops/scatterSub.js";
3
+ import { e as u, c as i, z as S, t as f, s as G } from "../index-pWA4_lUh.js";
4
+ import { s as v, l as z } from "../softmax-Be_lsqUc.js";
5
+ import { m as k } from "../sum-C7Mgy9Bw.js";
6
+ function F(a, s) {
7
+ return f(() => {
8
+ const e = a.shape[a.shape.length - 1], n = a.shape.slice(0, -1).reduce((d, c) => d * c, 1), p = a.shape.length > 2 ? a.reshape([n, e]) : a, o = s.shape.length > 1 ? s.reshape([n]).cast("int32") : s.cast("int32"), t = k(p, -1, !0), r = G(p, t), h = z(r, -1);
9
+ return L(h, o, r);
154
10
  });
155
11
  }
156
- function ts() {
157
- return m().backendName === "tensorflow" ? g((s, t, a) => {
158
- const e = s.shape.length > 2 ? s.reshape([-1, s.shape[s.shape.length - 1]]) : s, r = t.shape.length > 1 ? t.reshape([-1]).cast("int32") : t.cast("int32"), [c, o] = m().runKernel(
12
+ function $() {
13
+ return u().backendName === "tensorflow" ? i((s, e, m) => {
14
+ const n = s.shape.length > 2 ? s.reshape([-1, s.shape[s.shape.length - 1]]) : s, p = e.shape.length > 1 ? e.reshape([-1]).cast("int32") : e.cast("int32"), [o, t] = u().runKernel(
159
15
  "NativeSparseSoftmaxCrossEntropy",
160
- { logits: e, labels: r },
16
+ { logits: n, labels: p },
161
17
  {}
162
18
  );
163
- return a([o.reshape(s.shape)]), { value: c, gradFunc: (p, u) => [u[0], S(t)] };
164
- }) : g(
19
+ return m([t.reshape(s.shape)]), { value: o, gradFunc: (r, h) => [h[0], S(e)] };
20
+ }) : i(
165
21
  // @ts-expect-error Invalid params
166
- (s, t, a) => {
167
- const e = s.shape[s.shape.length - 1], c = s.shape.slice(0, -1).reduce((h, i) => h * i, 1), o = s.reshape([c, e]), p = t.reshape([c]).cast("int32"), u = R(o, p);
168
- return a([o, p]), o.dispose(), p.dispose(), { value: u, gradFunc: (h, i) => $(() => {
169
- const y = i[0], k = i[1], C = Q(y), G = v(C, k, h), K = S(t);
170
- return [G.reshape(s.shape), K];
22
+ (s, e, m) => {
23
+ const n = s.shape[s.shape.length - 1], o = s.shape.slice(0, -1).reduce((d, c) => d * c, 1), t = s.reshape([o, n]), r = e.reshape([o]).cast("int32"), h = F(t, r);
24
+ return m([t, r]), t.dispose(), r.dispose(), { value: h, gradFunc: (d, c) => f(() => {
25
+ const l = c[0], b = c[1], x = v(l), C = y(x, b, d), E = S(e);
26
+ return [C.reshape(s.shape), E];
171
27
  }) };
172
28
  }
173
29
  );
174
30
  }
175
31
  export {
176
- ts as createSoftmaxCrossEntropyWithGrad,
177
- R as sparseSoftmaxCrossEntropy
32
+ $ as createSoftmaxCrossEntropyWithGrad,
33
+ F as sparseSoftmaxCrossEntropy
178
34
  };