@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.
- package/dist/Generator.js +30 -25
- package/dist/NanoGPTModel.d.ts +13 -14
- package/dist/NanoGPTModel.js +167 -85
- package/dist/TeachableLLM.d.ts +3 -5
- package/dist/TeachableLLM.js +47 -35
- package/dist/Trainer.js +8 -8
- package/dist/concat-BIZS_td9.js +33 -0
- package/dist/data/parquet.js +1 -1
- package/dist/exports_layers-7idKoYqh.js +25 -0
- package/dist/{sum-D7fu15XL.js → gather-BPGW8RsB.js} +6 -8
- package/dist/index-C4L8Cm77.js +349 -0
- package/dist/{index-YPKosni4.js → index-pWA4_lUh.js} +1020 -782
- package/dist/layers/CausalSelfAttention.d.ts +11 -11
- package/dist/layers/CausalSelfAttention.js +71 -63
- package/dist/layers/MLP.d.ts +6 -7
- package/dist/layers/MLP.js +18 -16
- package/dist/layers/RMSNorm.d.ts +6 -7
- package/dist/layers/RMSNorm.js +15 -13
- package/dist/layers/RoPECache.d.ts +4 -5
- package/dist/layers/RoPECache.js +36 -12
- package/dist/layers/TiedEmbedding.d.ts +7 -8
- package/dist/layers/TiedEmbedding.js +16 -418
- package/dist/layers/TransformerBlock.d.ts +8 -9
- package/dist/layers/TransformerBlock.js +12 -12
- package/dist/main.d.ts +1 -0
- package/dist/main.js +35 -21
- package/dist/{mat_mul-Bu7bhLms.js → mat_mul-D7_a4KJn.js} +5 -5
- package/dist/moments-DfcpfwKi.js +132 -0
- package/dist/ones-Cog-G2ag.js +29 -0
- package/dist/ops/appendCache.d.ts +2 -0
- package/dist/ops/appendCache.js +9 -0
- package/dist/ops/attentionMask.d.ts +1 -1
- package/dist/ops/attentionMask.js +7 -85
- package/dist/ops/cpu/appendCache.d.ts +2 -0
- package/dist/ops/cpu/appendCache.js +28 -0
- package/dist/ops/cpu/attentionMask.js +18 -0
- package/dist/ops/cpu/gatherSub.d.ts +1 -0
- package/dist/ops/cpu/gatherSub.js +34 -0
- package/dist/ops/cpu/qkv.d.ts +5 -0
- package/dist/ops/cpu/qkv.js +38 -0
- package/dist/ops/cpu/rope.d.ts +6 -0
- package/dist/ops/cpu/rope.js +38 -0
- package/dist/ops/cpu/scatterSub.d.ts +1 -0
- package/dist/ops/cpu/scatterSub.js +70 -0
- package/dist/ops/gatherSub.d.ts +1 -1
- package/dist/ops/gatherSub.js +6 -63
- package/dist/ops/grads/attentionMask.d.ts +1 -0
- package/dist/ops/grads/attentionMask.js +21 -0
- package/dist/ops/grads/qkv.d.ts +1 -0
- package/dist/ops/grads/qkv.js +20 -0
- package/dist/ops/grads/rope.d.ts +1 -0
- package/dist/ops/grads/rope.js +14 -0
- package/dist/ops/node/sparseCrossEntropy.js +1 -1
- package/dist/ops/qkv.d.ts +1 -6
- package/dist/ops/qkv.js +7 -124
- package/dist/ops/rope.d.ts +0 -5
- package/dist/ops/rope.js +7 -151
- package/dist/ops/scatterSub.d.ts +1 -1
- package/dist/ops/scatterSub.js +6 -147
- package/dist/ops/webgl/appendCache.d.ts +1 -0
- package/dist/ops/webgl/appendCache.js +43 -0
- package/dist/ops/webgl/attentionMask.d.ts +1 -0
- package/dist/ops/webgl/attentionMask.js +43 -0
- package/dist/ops/webgl/gatherSub.d.ts +1 -0
- package/dist/ops/webgl/gatherSub.js +27 -0
- package/dist/ops/webgl/qkv.d.ts +1 -0
- package/dist/ops/webgl/qkv.js +46 -0
- package/dist/ops/webgl/rope.d.ts +1 -0
- package/dist/ops/webgl/rope.js +56 -0
- package/dist/ops/webgl/scatterSub.d.ts +1 -0
- package/dist/ops/webgl/scatterSub.js +27 -0
- package/dist/{parquet-BRl5lE_I.js → parquet-C0Tlmv9c.js} +3045 -3048
- package/dist/random_width-PbCt7RXv.js +15489 -0
- package/dist/range-CcDl05lo.js +26 -0
- package/dist/{reshape-DmnmKT6r.js → reshape-C8CR_Bad.js} +3 -3
- package/dist/sin-BJIrfnj7.js +47 -0
- package/dist/softmax-Be_lsqUc.js +105 -0
- package/dist/{complex-CJ-qCcLB.js → split-DZbvruEP.js} +6 -8
- package/dist/stack-BMm-efee.js +27 -0
- package/dist/sum-C7Mgy9Bw.js +104 -0
- package/dist/tensor-DJVbYhh1.js +24 -0
- package/dist/tensor2d-ZuQSh2D-.js +30 -0
- package/dist/tokeniser/bpe.d.ts +17 -6
- package/dist/tokeniser/bpe.js +88 -60
- package/dist/training/AdamExt.js +1 -1
- package/dist/training/DatasetBuilder.d.ts +6 -6
- package/dist/training/DatasetBuilder.js +1262 -17
- package/dist/training/Evaluator.d.ts +3 -2
- package/dist/training/FullTrainer.d.ts +9 -8
- package/dist/training/FullTrainer.js +26 -25
- package/dist/training/LayerTrainer.d.ts +9 -8
- package/dist/training/LayerTrainer.js +34 -33
- package/dist/training/Trainer.d.ts +22 -21
- package/dist/training/Trainer.js +21 -18
- package/dist/training/sparseCrossEntropy.js +22 -166
- package/dist/utilities/dummy.js +10 -8
- package/dist/utilities/generate.js +14 -11
- package/dist/utilities/load.d.ts +1 -2
- package/dist/utilities/load.js +37 -35
- package/dist/utilities/profile.js +1 -1
- package/dist/utilities/save.js +14 -9
- package/dist/utilities/tokenParse.d.ts +1 -1
- package/dist/utilities/tokenParse.js +7 -61
- package/dist/utilities/weights.d.ts +3 -3
- package/dist/utilities/weights.js +21 -19
- package/dist/variable-Dl_ub3pk.js +23 -0
- package/dist/{stack-BtKpB0Ry.js → zeros-CCy9C3uU.js} +18 -16
- package/package.json +2 -1
- package/dist/assets/worker-BYeSPNkq.js +0 -1
- package/dist/tokeniser/NodeTokeniser.d.ts +0 -20
- package/dist/tokeniser/NodeTokeniser.js +0 -46
- package/dist/tokeniser/WebTokeniser.d.ts +0 -18
- package/dist/tokeniser/WebTokeniser.js +0 -96
- package/dist/tokeniser/worker.js +0 -53
- /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 {
|
|
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:
|
|
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(
|
|
7
|
-
trainOnDataset(dataset:
|
|
8
|
-
xs:
|
|
9
|
-
ys:
|
|
10
|
-
}>, options: Partial<TrainingOptions>, validationDataset?:
|
|
11
|
-
xs:
|
|
12
|
-
ys:
|
|
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
|
|
2
|
-
import
|
|
3
|
-
import
|
|
4
|
-
|
|
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
|
|
10
|
-
constructor(r, i, o
|
|
11
|
-
super(r, i, o
|
|
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:
|
|
16
|
-
...
|
|
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
|
|
28
|
+
const f = Date.now();
|
|
28
29
|
this.running = !0;
|
|
29
|
-
const
|
|
30
|
+
const c = o ? new g(this.model, o) : void 0, v = await r.iterator();
|
|
30
31
|
try {
|
|
31
|
-
for (; this.running && !(t.lastLoss <
|
|
32
|
-
const e = await
|
|
32
|
+
for (; this.running && !(t.lastLoss < m); ) {
|
|
33
|
+
const e = await v.next();
|
|
33
34
|
if (e.done) break;
|
|
34
|
-
const p = e.value,
|
|
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() -
|
|
38
|
+
time: Date.now() - f,
|
|
38
39
|
batchSize: p.xs.shape[0]
|
|
39
40
|
};
|
|
40
|
-
if (this.model.log.push(a), t.step %
|
|
41
|
-
if (await
|
|
41
|
+
if (this.model.log.push(a), t.step % u === 0) {
|
|
42
|
+
if (await L, c)
|
|
42
43
|
try {
|
|
43
|
-
const s = await
|
|
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 (
|
|
49
|
-
if (
|
|
50
|
-
const s = await
|
|
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
|
|
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),
|
|
62
|
+
throw console.error("Training error:", e), h(), e;
|
|
62
63
|
}
|
|
63
|
-
return
|
|
64
|
+
return h(), this.running = !1, { losses: t.losses, validationLosses: t.validationLosses };
|
|
64
65
|
}
|
|
65
66
|
}
|
|
66
67
|
export {
|
|
67
|
-
|
|
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(
|
|
16
|
+
constructor(model: NanoGPT, tokenizer: ITokeniser, learningRate?: number);
|
|
16
17
|
private applyTrainingPattern;
|
|
17
|
-
trainOnDataset(dataset:
|
|
18
|
-
xs:
|
|
19
|
-
ys:
|
|
20
|
-
}>, options: Partial<LayerTrainingOptions>, validationDataset?:
|
|
21
|
-
xs:
|
|
22
|
-
ys:
|
|
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
|
|
2
|
-
import
|
|
3
|
-
import { schedule as
|
|
4
|
-
import
|
|
5
|
-
|
|
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
|
|
13
|
+
class E extends v {
|
|
13
14
|
trainingPattern = [];
|
|
14
15
|
startPass = 0;
|
|
15
16
|
startLayer = 0;
|
|
16
|
-
constructor(
|
|
17
|
-
if (super(
|
|
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(
|
|
23
|
-
const
|
|
24
|
-
this.model.setSkipMask(e.skip), this.model.setTrainableMask(e.trainable), this.resetOptimizer(e.adam), console.log("Applied training pattern:",
|
|
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(
|
|
28
|
-
const { desiredLoss:
|
|
29
|
-
...
|
|
30
|
-
...
|
|
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
|
|
43
|
+
const d = Date.now();
|
|
43
44
|
this.startPass = 0, this.startLayer = 0;
|
|
44
|
-
const
|
|
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 <
|
|
48
|
-
const n = await
|
|
48
|
+
for (; !(t.lastLoss < i); ) {
|
|
49
|
+
const n = await P.next();
|
|
49
50
|
if (n.done) break;
|
|
50
|
-
const
|
|
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() -
|
|
56
|
-
batchSize:
|
|
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 %
|
|
61
|
-
if (await
|
|
61
|
+
if (this.model.log.push(l), t.step % L === 0) {
|
|
62
|
+
if (await S, g)
|
|
62
63
|
try {
|
|
63
|
-
const a = await
|
|
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 (
|
|
69
|
-
if (
|
|
70
|
-
const a = await
|
|
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
|
|
77
|
+
await h(l);
|
|
77
78
|
}
|
|
78
79
|
}
|
|
79
|
-
t.stepSinceLayerChange >=
|
|
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),
|
|
83
|
+
throw console.error("Training error:", n), m(), n;
|
|
83
84
|
}
|
|
84
|
-
return
|
|
85
|
+
return m(), { losses: t.losses, validationLosses: t.validationLosses };
|
|
85
86
|
}
|
|
86
87
|
}
|
|
87
88
|
export {
|
|
88
|
-
|
|
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(
|
|
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:
|
|
44
|
-
ys:
|
|
45
|
-
}, dummy?: boolean, print?: boolean):
|
|
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:
|
|
49
|
-
ys:
|
|
49
|
+
xs: Tensor;
|
|
50
|
+
ys: Tensor;
|
|
50
51
|
}): Promise<number>;
|
|
51
|
-
abstract trainOnDataset(dataset:
|
|
52
|
-
xs:
|
|
53
|
-
ys:
|
|
54
|
-
}>, options: Partial<TrainingOptions>, validationDataset?:
|
|
55
|
-
xs:
|
|
56
|
-
ys:
|
|
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:
|
|
63
|
-
xs:
|
|
64
|
-
ys:
|
|
63
|
+
trainDataset: Dataset<{
|
|
64
|
+
xs: Tensor;
|
|
65
|
+
ys: Tensor;
|
|
65
66
|
}>;
|
|
66
|
-
validationDataset:
|
|
67
|
-
xs:
|
|
68
|
-
ys:
|
|
67
|
+
validationDataset: Dataset<{
|
|
68
|
+
xs: Tensor;
|
|
69
|
+
ys: Tensor;
|
|
69
70
|
}>;
|
|
70
71
|
}>;
|
|
71
|
-
createDataset(textData: string[], batchSize?: number): Promise<
|
|
72
|
+
createDataset(textData: string[], batchSize?: number): Promise<Dataset<TensorContainer>>;
|
|
72
73
|
dispose(): void;
|
|
73
74
|
}
|
package/dist/training/Trainer.js
CHANGED
|
@@ -1,13 +1,16 @@
|
|
|
1
|
-
import { DatasetBuilder as
|
|
1
|
+
import { DatasetBuilder as p } from "./DatasetBuilder.js";
|
|
2
2
|
import h from "./AdamExt.js";
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
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: ${
|
|
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
|
|
52
|
+
return g(() => {
|
|
50
53
|
this.model.getProfiler()?.startMemory();
|
|
51
|
-
const { xs:
|
|
52
|
-
const { loss:
|
|
53
|
-
return
|
|
54
|
-
}, { value:
|
|
55
|
-
return s ? this.model.getProfiler()?.endMemory("Training") : (e && (console.log("-------"), this.printGradients(
|
|
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 =
|
|
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((
|
|
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),
|
|
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
|
|
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:
|
|
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
|
-
|
|
97
|
+
M as default
|
|
95
98
|
};
|
|
@@ -1,178 +1,34 @@
|
|
|
1
|
-
import { gatherSub as
|
|
2
|
-
import { scatterSub as
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
*
|
|
9
|
-
|
|
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
|
|
157
|
-
return
|
|
158
|
-
const
|
|
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:
|
|
16
|
+
{ logits: n, labels: p },
|
|
161
17
|
{}
|
|
162
18
|
);
|
|
163
|
-
return
|
|
164
|
-
}) :
|
|
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,
|
|
167
|
-
const
|
|
168
|
-
return
|
|
169
|
-
const
|
|
170
|
-
return [
|
|
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
|
-
|
|
177
|
-
|
|
32
|
+
$ as createSoftmaxCrossEntropyWithGrad,
|
|
33
|
+
F as sparseSoftmaxCrossEntropy
|
|
178
34
|
};
|