@genai-fi/nanogpt 1.4.1 → 1.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 (75) hide show
  1. package/dist/api/beamer.d.ts +1 -0
  2. package/dist/api/beamer.js +15 -5
  3. package/dist/inference/Beamer.d.ts +14 -2
  4. package/dist/inference/Beamer.js +147 -89
  5. package/dist/inference/Generator.js +36 -22
  6. package/dist/inference/tokenisePrompt.d.ts +2 -1
  7. package/dist/inference/tokenisePrompt.js +10 -7
  8. package/dist/inference/types.d.ts +1 -0
  9. package/dist/layers/GQA.d.ts +44 -0
  10. package/dist/layers/{CausalSelfAttention.js → GQA.js} +21 -19
  11. package/dist/layers/HeadLayer.d.ts +12 -0
  12. package/dist/layers/HeadLayer.js +28 -0
  13. package/dist/layers/{CausalSelfAttention.d.ts → MHA.d.ts} +7 -3
  14. package/dist/layers/MHA.js +101 -0
  15. package/dist/layers/MLP.d.ts +5 -1
  16. package/dist/layers/MLP.js +25 -13
  17. package/dist/layers/RMSNorm.d.ts +2 -0
  18. package/dist/layers/RMSNorm.js +12 -8
  19. package/dist/layers/RoPECache.js +4 -3
  20. package/dist/layers/TransformerBlock.d.ts +2 -2
  21. package/dist/layers/TransformerBlock.js +4 -4
  22. package/dist/layers.d.ts +1 -1
  23. package/dist/layers.js +1 -1
  24. package/dist/loader/loadTransformers.js +17 -1
  25. package/dist/loader/save.js +18 -3
  26. package/dist/loader/types.d.ts +8 -2
  27. package/dist/main.js +2 -2
  28. package/dist/matMul16-CO1QhsRt.js +85 -0
  29. package/dist/models/Llama.d.ts +16 -0
  30. package/dist/models/Llama.js +89 -0
  31. package/dist/models/Qwen3.d.ts +16 -0
  32. package/dist/models/Qwen3.js +89 -0
  33. package/dist/models/config.d.ts +18 -1
  34. package/dist/models/config.js +1 -1
  35. package/dist/models/factory.js +11 -7
  36. package/dist/models/model.d.ts +1 -1
  37. package/dist/ops/dot16.js +1 -1
  38. package/dist/ops/globalNorm.js +12 -12
  39. package/dist/ops/grads/attentionMask.js +1 -1
  40. package/dist/ops/grads/matMul16.js +1 -1
  41. package/dist/ops/grads/qkv.js +1 -1
  42. package/dist/ops/grads/rope.js +1 -1
  43. package/dist/ops/grads/silu.d.ts +2 -0
  44. package/dist/ops/grads/silu.js +2 -0
  45. package/dist/ops/matMul16.d.ts +1 -1
  46. package/dist/ops/matMul16.js +1 -1
  47. package/dist/ops/normRMS.d.ts +1 -1
  48. package/dist/ops/normRMS.js +8 -8
  49. package/dist/ops/rope.d.ts +1 -1
  50. package/dist/ops/rope.js +1 -1
  51. package/dist/ops/silu.d.ts +3 -0
  52. package/dist/ops/silu.js +2 -0
  53. package/dist/ops/webgl/rope.js +6 -4
  54. package/dist/ops/webgpu/attentionMask.js +1 -1
  55. package/dist/ops/webgpu/index.js +1 -0
  56. package/dist/ops/webgpu/matMul16.js +50 -44
  57. package/dist/ops/webgpu/matMul16_program.d.ts +2 -2
  58. package/dist/ops/webgpu/matMul16_program.js +1 -1
  59. package/dist/ops/webgpu/normRMS.js +6 -6
  60. package/dist/ops/webgpu/normRMS16_program.d.ts +2 -1
  61. package/dist/ops/webgpu/normRMS16_program.js +4 -3
  62. package/dist/ops/webgpu/normRMS32_program.d.ts +2 -1
  63. package/dist/ops/webgpu/normRMS32_program.js +4 -3
  64. package/dist/ops/webgpu/qkv.js +1 -1
  65. package/dist/ops/webgpu/rope.js +99 -34
  66. package/dist/ops/webgpu/silu.d.ts +14 -0
  67. package/dist/ops/webgpu/silu.js +118 -0
  68. package/dist/{rope-C8EAiSGY.js → rope-BPu_uooz.js} +5 -4
  69. package/dist/silu-B6bvCgJ7.js +25 -0
  70. package/dist/training/Evaluator.js +4 -1
  71. package/dist/utilities/maxHeap.d.ts +16 -0
  72. package/dist/utilities/maxHeap.js +55 -0
  73. package/dist/utilities/parameters.js +33 -17
  74. package/package.json +1 -1
  75. package/dist/matMul16-DGtlziMn.js +0 -81
@@ -0,0 +1,89 @@
1
+ import { di as e, oi as t } from "../dist-Da20xy8E.js";
2
+ import { packingSupported as n } from "../utilities/packed.js";
3
+ import { r, t as i } from "../pack16-BhuXNUS7.js";
4
+ import a from "../layers/RMSNorm.js";
5
+ import o from "../layers/TransformerBlock.js";
6
+ import s from "../layers/TiedEmbedding.js";
7
+ import c from "../layers/RoPECache.js";
8
+ import l from "./model.js";
9
+ import u from "../layers/HeadLayer.js";
10
+ //#region lib/models/Llama.ts
11
+ var d = {
12
+ modelType: "llama",
13
+ vocabSize: 2e3,
14
+ blockSize: 128,
15
+ nLayer: 6,
16
+ nHead: 4,
17
+ nEmbed: 256,
18
+ mlpFactor: 4
19
+ }, f = class extends l {
20
+ wte;
21
+ head;
22
+ blocks;
23
+ lnF;
24
+ ropeCache;
25
+ constructor(e = {}) {
26
+ super({
27
+ ...d,
28
+ ...e
29
+ });
30
+ let t = {
31
+ activation: "swiglu",
32
+ hiddenSize: Math.max(256, Math.ceil(this.config.nEmbed * (8 / 3) / 256) * 256),
33
+ useGamma: !0,
34
+ useQKNorm: !1,
35
+ ropeInterleaved: !1
36
+ };
37
+ this.wte = new s(this.config, "token_embedding", this), this.ropeCache = new c(this.config), this.blocks = [];
38
+ for (let e = 0; e < this.config.nLayer; e++) this.blocks.push(new o(e, this.config, t, this));
39
+ this.lnF = new a(this.config, t, "final_rms_norm", this), this.head = new u(this.config, "lm_head", this);
40
+ }
41
+ getClassName() {
42
+ return "llama";
43
+ }
44
+ inputPhase(t) {
45
+ return e(() => this.wte.embed(t));
46
+ }
47
+ forward(a, o) {
48
+ return this.validateInput(o), a.ropeCache = this.ropeCache, a.outputEmbeddings && (a.embeddings = []), e(() => {
49
+ this.startMemory();
50
+ let e = this.inputPhase(o);
51
+ if (a.cache && a.cache.length !== this.blocks.length) throw console.error("Cache", a.cache), Error(`Cache length ${a.cache.length} does not match number of blocks ${this.blocks.length}`);
52
+ let s = a.mixedPrecision === !0 && n(), c = s ? i(e) : e;
53
+ s && e !== c && e.dispose();
54
+ for (let e = 0; e < this.blocks.length; e++) {
55
+ if (a.layerDrop && Math.random() < a.layerDrop * (e / this.blocks.length)) continue;
56
+ let n = this.blocks[e], r = Math.random() * 1e9, i = {
57
+ ...a,
58
+ seed: r,
59
+ pastKV: a.cache ? a.cache[e] : void 0,
60
+ mixedPrecision: s,
61
+ epsilon: 1e-6
62
+ }, o = a.checkpointing && a.training ? n.callCheckpoint(i, c) : n.call(i, c);
63
+ a.outputEmbeddings ? (t(c), a.embeddings.push({
64
+ name: `block_output_${e}`,
65
+ tensor: c
66
+ })) : c.dispose(), c = o;
67
+ }
68
+ if (e = this.lnF.call({
69
+ ...a,
70
+ mixedPrecision: s
71
+ }, c), c.dispose(), a.skipLogits) return this.endMemory("Forward"), e;
72
+ let l = this.head.project(e);
73
+ a.outputEmbeddings ? (t(e), a.embeddings.push({
74
+ name: "final_norm_output",
75
+ tensor: e
76
+ })) : e.dispose();
77
+ let u = s ? r(l) : l;
78
+ return s && l !== u && l.dispose(), u;
79
+ });
80
+ }
81
+ project(t) {
82
+ return e(() => this.head.project(t));
83
+ }
84
+ dispose() {
85
+ this.weightStore.dispose(), this.wte.dispose(), this.head.dispose(), this.blocks.forEach((e) => e.dispose()), this.lnF.dispose();
86
+ }
87
+ };
88
+ //#endregion
89
+ export { f as default };
@@ -0,0 +1,16 @@
1
+ import { GPTConfigQwen3 } from './config';
2
+ import { Tensor } from '@tensorflow/tfjs-core';
3
+ import { default as Model, ModelForwardAttributes } from './model';
4
+ export default class Qwen3 extends Model<ModelForwardAttributes, GPTConfigQwen3> {
5
+ private wte;
6
+ private head;
7
+ private blocks;
8
+ private lnF;
9
+ private ropeCache?;
10
+ constructor(config?: Partial<GPTConfigQwen3>);
11
+ getClassName(): string;
12
+ private inputPhase;
13
+ forward(attrs: ModelForwardAttributes, idx: Tensor): Tensor;
14
+ project(embeddings: Tensor): Tensor;
15
+ dispose(): void;
16
+ }
@@ -0,0 +1,89 @@
1
+ import { di as e, oi as t } from "../dist-Da20xy8E.js";
2
+ import { packingSupported as n } from "../utilities/packed.js";
3
+ import { r, t as i } from "../pack16-BhuXNUS7.js";
4
+ import a from "../layers/RMSNorm.js";
5
+ import o from "../layers/TransformerBlock.js";
6
+ import s from "../layers/TiedEmbedding.js";
7
+ import c from "../layers/RoPECache.js";
8
+ import l from "./model.js";
9
+ import u from "../layers/HeadLayer.js";
10
+ //#region lib/models/Qwen3.ts
11
+ var d = {
12
+ modelType: "qwen3",
13
+ vocabSize: 2e3,
14
+ blockSize: 128,
15
+ nLayer: 6,
16
+ nHead: 4,
17
+ nEmbed: 256,
18
+ mlpFactor: 4
19
+ }, f = class extends l {
20
+ wte;
21
+ head;
22
+ blocks;
23
+ lnF;
24
+ ropeCache;
25
+ constructor(e = {}) {
26
+ super({
27
+ ...d,
28
+ ...e
29
+ });
30
+ let t = {
31
+ activation: "swiglu",
32
+ hiddenSize: this.config.mlpSize ?? Math.max(256, Math.ceil(this.config.nEmbed * (8 / 3) / 256) * 256),
33
+ useGamma: !0,
34
+ useQKNorm: !0,
35
+ ropeInterleaved: !1,
36
+ epsilon: this.config.rmsNormEpsilon ?? 1e-6
37
+ };
38
+ this.wte = new s(this.config, "token_embedding", this), this.ropeCache = new c(this.config), this.blocks = [];
39
+ for (let e = 0; e < this.config.nLayer; e++) this.blocks.push(new o(e, this.config, t, this));
40
+ this.lnF = new a(this.config, t, "final_rms_norm", this), this.config.tieEmbeddings ?? !0 ? this.head = new u(this.config, "lm_head", this) : this.head = null;
41
+ }
42
+ getClassName() {
43
+ return "qwen3";
44
+ }
45
+ inputPhase(t) {
46
+ return e(() => this.wte.embed(t));
47
+ }
48
+ forward(a, o) {
49
+ return this.validateInput(o), a.ropeCache = this.ropeCache, a.outputEmbeddings && (a.embeddings = []), e(() => {
50
+ this.startMemory();
51
+ let e = this.inputPhase(o);
52
+ if (a.cache && a.cache.length !== this.blocks.length) throw console.error("Cache", a.cache), Error(`Cache length ${a.cache.length} does not match number of blocks ${this.blocks.length}`);
53
+ let s = a.mixedPrecision === !0 && n(), c = s ? i(e) : e;
54
+ s && e !== c && e.dispose();
55
+ for (let e = 0; e < this.blocks.length; e++) {
56
+ if (a.layerDrop && Math.random() < a.layerDrop * (e / this.blocks.length)) continue;
57
+ let n = this.blocks[e], r = Math.random() * 1e9, i = {
58
+ ...a,
59
+ seed: r,
60
+ pastKV: a.cache ? a.cache[e] : void 0,
61
+ mixedPrecision: s
62
+ }, o = a.checkpointing && a.training ? n.callCheckpoint(i, c) : n.call(i, c);
63
+ a.outputEmbeddings ? (t(c), a.embeddings.push({
64
+ name: `block_output_${e}`,
65
+ tensor: c
66
+ })) : c.dispose(), c = o;
67
+ }
68
+ if (e = this.lnF.call({
69
+ ...a,
70
+ mixedPrecision: s
71
+ }, c), c.dispose(), a.skipLogits) return this.endMemory("Forward"), e;
72
+ let l = this.head ? this.head.project(e) : this.wte.project(e);
73
+ a.outputEmbeddings ? (t(e), a.embeddings.push({
74
+ name: "final_norm_output",
75
+ tensor: e
76
+ })) : e.dispose();
77
+ let u = s ? r(l) : l;
78
+ return s && l !== u && l.dispose(), u;
79
+ });
80
+ }
81
+ project(t) {
82
+ return e(() => this.wte.project(t));
83
+ }
84
+ dispose() {
85
+ this.weightStore.dispose(), this.wte.dispose(), this.head && this.head.dispose(), this.blocks.forEach((e) => e.dispose()), this.lnF.dispose();
86
+ }
87
+ };
88
+ //#endregion
89
+ export { f as default };
@@ -13,6 +13,7 @@ export interface GPTConfigBase {
13
13
  mlpFactor: number;
14
14
  loraConfig?: Map<string, LoRAConfig>;
15
15
  loraName?: string;
16
+ ropeTheta?: number;
16
17
  }
17
18
  export interface GPTConfigV1 extends GPTConfigBase {
18
19
  modelType: 'GenAI_NanoGPT_v1';
@@ -22,6 +23,22 @@ export interface GPTConfigV2 extends GPTConfigBase {
22
23
  modelType: 'GenAI_NanoGPT_v2';
23
24
  windowSize?: string;
24
25
  }
25
- export type GPTConfig = GPTConfigV1 | GPTConfigV2;
26
+ export interface GPTConfigQwen3 extends GPTConfigBase {
27
+ modelType: 'qwen3';
28
+ tieEmbeddings?: boolean;
29
+ rmsNormEpsilon?: number;
30
+ kvHeads?: number;
31
+ headDim?: number;
32
+ mlpSize?: number;
33
+ }
34
+ export interface GPTConfigLlama extends GPTConfigBase {
35
+ modelType: 'llama';
36
+ tieEmbeddings?: boolean;
37
+ rmsNormEpsilon?: number;
38
+ kvHeads?: number;
39
+ headDim?: number;
40
+ mlpSize?: number;
41
+ }
42
+ export type GPTConfig = GPTConfigV1 | GPTConfigV2 | GPTConfigQwen3 | GPTConfigLlama;
26
43
  export declare const defaultConfig: GPTConfig;
27
44
  export declare function validateConfig(config: unknown): asserts config is GPTConfig;
@@ -31,7 +31,7 @@ function n(e) {
31
31
  if (e.windowSize !== void 0 && typeof e.windowSize != "string") throw Error("Invalid config: \"windowSize\" must be a string for GenAI_NanoGPT_v2.");
32
32
  return;
33
33
  }
34
- throw Error("invalid_model_type");
34
+ if (e.modelType !== "qwen3" && e.modelType !== "llama") throw Error("invalid_model_type");
35
35
  }
36
36
  //#endregion
37
37
  export { e as defaultConfig, n as validateConfig };
@@ -1,13 +1,17 @@
1
1
  import e from "./NanoGPTV1.js";
2
2
  import t from "./NanoGPTV2.js";
3
+ import n from "./Llama.js";
4
+ import r from "./Qwen3.js";
3
5
  //#region lib/models/factory.ts
4
- function n(n) {
5
- let r = n.modelType || "GenAI_NanoGPT_v1";
6
- switch (r) {
7
- case "GenAI_NanoGPT_v1": return new e(n);
8
- case "GenAI_NanoGPT_v2": return new t(n);
9
- default: throw Error(`Unsupported model type: ${r}`);
6
+ function i(i) {
7
+ let a = i.modelType || "GenAI_NanoGPT_v1";
8
+ switch (a) {
9
+ case "GenAI_NanoGPT_v1": return new e(i);
10
+ case "GenAI_NanoGPT_v2": return new t(i);
11
+ case "qwen3": return new r(i);
12
+ case "llama": return new n(i);
13
+ default: throw Error(`Unsupported model type: ${a}`);
10
14
  }
11
15
  }
12
16
  //#endregion
13
- export { n as default };
17
+ export { i as default };
@@ -1,6 +1,6 @@
1
1
  import { Tensor } from '@tensorflow/tfjs-core';
2
2
  import { ForwardAttributes, default as BaseLayer } from '../layers/BaseLayer';
3
- import { AttentionScores, KVCache } from '../layers/CausalSelfAttention';
3
+ import { AttentionScores, KVCache } from '../layers/MHA';
4
4
  import { TransformersMetadata } from '../../loader/types';
5
5
  import { GPTConfig, LoRAConfig } from './config';
6
6
  import { default as LoRA } from '../../layers/LoRA';
package/dist/ops/dot16.js CHANGED
@@ -2,7 +2,7 @@ import { o as e } from "../tfjs_backend-h5weiy1O.js";
2
2
  import { isPackedTensor as t } from "../utilities/packed.js";
3
3
  import { transpose16 as n } from "./transpose16.js";
4
4
  import { reshape16 as r } from "./reshape16.js";
5
- import { t as i } from "../matMul16-DGtlziMn.js";
5
+ import { t as i } from "../matMul16-CO1QhsRt.js";
6
6
  //#region lib/ops/dot16.ts
7
7
  function a(a, o, s = !1, c = !1) {
8
8
  if (!t(a) && !t(o)) return e(a, o);
@@ -1,19 +1,19 @@
1
- import { di as e, ii as t, kt as n } from "../dist-Da20xy8E.js";
1
+ import { _n as e, di as t, ii as n, kt as r } from "../dist-Da20xy8E.js";
2
2
  //#region lib/ops/globalNorm.ts
3
- function r(r, i, a = 1) {
4
- return e(() => {
5
- let e = n([r.length], "int32");
6
- return r.map((n, r) => t().runKernel("Norm2", {
7
- x: n,
3
+ function i(i, a, o = 1) {
4
+ return n().backendName === "webgpu" ? t(() => {
5
+ let e = r([i.length], "int32");
6
+ return i.map((t, r) => n().runKernel("Norm2", {
7
+ x: t,
8
8
  output: e
9
9
  }, {
10
- invLossScaling: i,
10
+ invLossScaling: a,
11
11
  index: r
12
- })), t().runKernel("ClipScale", { x: e }, {
13
- invLossScaling: i,
14
- clipNorm: a
12
+ })), n().runKernel("ClipScale", { x: e }, {
13
+ invLossScaling: a,
14
+ clipNorm: o
15
15
  });
16
- });
16
+ }) : e(a);
17
17
  }
18
18
  //#endregion
19
- export { r as clipScale };
19
+ export { i as clipScale };
@@ -1,6 +1,6 @@
1
1
  import { Fi as e } from "../../dist-Da20xy8E.js";
2
2
  import { transpose16 as t } from "../transpose16.js";
3
- import { a as n } from "../../matMul16-DGtlziMn.js";
3
+ import { a as n } from "../../matMul16-CO1QhsRt.js";
4
4
  //#region lib/ops/grads/attentionMask.ts
5
5
  e({
6
6
  kernelName: "AttentionMask",
@@ -1,2 +1,2 @@
1
- import { o as e } from "../../matMul16-DGtlziMn.js";
1
+ import { o as e } from "../../matMul16-CO1QhsRt.js";
2
2
  export { e as matMul16GradConfig };
@@ -1,6 +1,6 @@
1
1
  import { Fi as e, H as t } from "../../dist-Da20xy8E.js";
2
2
  import { sum16 as n } from "../sum16.js";
3
- import { o as r } from "../../matMul16-DGtlziMn.js";
3
+ import { o as r } from "../../matMul16-CO1QhsRt.js";
4
4
  import { concat16 as i } from "../concat16.js";
5
5
  //#region lib/ops/grads/qkv.ts
6
6
  var a = {
@@ -1,2 +1,2 @@
1
- import { n as e } from "../../rope-C8EAiSGY.js";
1
+ import { n as e } from "../../rope-BPu_uooz.js";
2
2
  export { e as ropeGradConfig };
@@ -0,0 +1,2 @@
1
+ import { GradConfig } from '@tensorflow/tfjs-core';
2
+ export declare const siluGradConfig: GradConfig;
@@ -0,0 +1,2 @@
1
+ import { r as e } from "../../silu-B6bvCgJ7.js";
2
+ export { e as siluGradConfig };
@@ -3,7 +3,7 @@ export declare function matMul16(A: Tensor, B: Tensor, transposeA?: boolean, tra
3
3
  scale?: number;
4
4
  scaleA?: number;
5
5
  scaleB?: number;
6
- activation?: 'gelu' | 'relu2' | 'relu';
6
+ activation?: 'gelu' | 'relu2' | 'relu' | 'silu';
7
7
  forceOutputShape?: number[];
8
8
  perm?: number[];
9
9
  causalMask?: boolean;
@@ -1,2 +1,2 @@
1
- import { a as e, i as t, n, r, t as i } from "../matMul16-DGtlziMn.js";
1
+ import { a as e, i as t, n, r, t as i } from "../matMul16-CO1QhsRt.js";
2
2
  export { i as matMul16, n as matMul16Gelu, r as matMul16ScaleA, t as matMul16ScaleB, e as matMul16Scaled };
@@ -1,2 +1,2 @@
1
1
  import { Tensor } from '@tensorflow/tfjs-core';
2
- export declare function normRMS(x: Tensor, gamma?: Tensor): Tensor;
2
+ export declare function normRMS(x: Tensor, gamma?: Tensor, epsilon?: number): Tensor;
@@ -3,20 +3,20 @@ import "./cpu/normRMS.js";
3
3
  import "./webgl/normRMS.js";
4
4
  import "./grads/normRMS.js";
5
5
  //#region lib/ops/normRMS.ts
6
- function t(t, n) {
6
+ function t(t, n, r = 1e-8) {
7
7
  if (t.rank === 4) {
8
- let [r, i, ...a] = t.shape, o = [r * i, ...a], s = t.reshape(o), c = e().runKernel(n ? "RMSNorm" : "RMSNormNoGamma", n ? {
9
- x: s,
8
+ let [i, a, ...o] = t.shape, s = [i * a, ...o], c = t.reshape(s), l = e().runKernel(n ? "RMSNorm" : "RMSNormNoGamma", n ? {
9
+ x: c,
10
10
  gamma: n
11
- } : { x: s });
12
- s.dispose();
13
- let l = c.reshape(t.shape);
14
- return c.dispose(), l;
11
+ } : { x: c }, { epsilon: r });
12
+ c.dispose();
13
+ let u = l.reshape(t.shape);
14
+ return l.dispose(), u;
15
15
  }
16
16
  return e().runKernel(n ? "RMSNorm" : "RMSNormNoGamma", n ? {
17
17
  x: t,
18
18
  gamma: n
19
- } : { x: t });
19
+ } : { x: t }, { epsilon: r });
20
20
  }
21
21
  //#endregion
22
22
  export { t as normRMS };
@@ -1,3 +1,3 @@
1
1
  import { default as RoPECache } from '../../layers/RoPECache';
2
2
  import { Tensor } from '@tensorflow/tfjs-core';
3
- export declare function rope(x: Tensor, cache: RoPECache, pastLength: number, negSin?: boolean): Tensor;
3
+ export declare function rope(x: Tensor, cache: RoPECache, pastLength: number, negSin?: boolean, interleaved?: boolean): Tensor;
package/dist/ops/rope.js CHANGED
@@ -1,2 +1,2 @@
1
- import { t as e } from "../rope-C8EAiSGY.js";
1
+ import { t as e } from "../rope-BPu_uooz.js";
2
2
  export { e as rope };
@@ -0,0 +1,3 @@
1
+ import { Tensor } from '@tensorflow/tfjs-core';
2
+ export declare function silu(x: Tensor): Tensor;
3
+ export declare function dSilu(dy: Tensor, x: Tensor): Tensor;
@@ -0,0 +1,2 @@
1
+ import { n as e, t } from "../silu-B6bvCgJ7.js";
2
+ export { t as dSilu, e as silu };
@@ -57,11 +57,13 @@ var t = class {
57
57
  }
58
58
  };
59
59
  function n(e) {
60
- let { x: n } = e.inputs, { pastLen: r, ropeCache: i, negSin: a } = e.attrs, o = a ? i.getNegSin() : i.getSin(), s = i.getCos(), c = e.backend, l = n.shape[0], u = n.shape[1], d = n.shape[2], f = n.shape[3], p = new t(l, u, d, f);
61
- return c.runWebGLProgram(p, [
60
+ let { x: n } = e.inputs, { pastLen: r, ropeCache: i, negSin: a, interleaved: o } = e.attrs, s = a ? i.getNegSin() : i.getSin(), c = i.getCos(), l = e.backend;
61
+ if (!o) throw Error("Non-interleaved mode is not supported in this WebGL implementation.");
62
+ let u = n.shape[0], d = n.shape[1], f = n.shape[2], p = n.shape[3], m = new t(u, d, f, p);
63
+ return l.runWebGLProgram(m, [
62
64
  n,
63
- o,
64
- s
65
+ s,
66
+ c
65
67
  ], "float32", [[r]]);
66
68
  }
67
69
  e({
@@ -1,6 +1,6 @@
1
1
  import { Fs as e, Ii as t } from "../../dist-Da20xy8E.js";
2
2
  import { isPackedTensor as n } from "../../utilities/packed.js";
3
- import { t as r } from "../../matMul16-DGtlziMn.js";
3
+ import { t as r } from "../../matMul16-CO1QhsRt.js";
4
4
  import i from "./attentionMask32_program.js";
5
5
  //#region lib/ops/webgpu/attentionMask.ts
6
6
  function a(t) {
@@ -5,6 +5,7 @@ import "./sub16.js";
5
5
  import "./softmax16grad.js";
6
6
  import "./softmax16.js";
7
7
  import "./slice16.js";
8
+ import "./silu.js";
8
9
  import "./scatterSub.js";
9
10
  import "./rope.js";
10
11
  import "./qkv.js";
@@ -1,74 +1,80 @@
1
1
  import { Ii as e, In as t, Wr as n, _n as r, br as i, gr as a, hn as o, lt as s, oc as c, w as l } from "../../dist-Da20xy8E.js";
2
2
  import { isPackedTensor as u } from "../../utilities/packed.js";
3
3
  import { reshape16 as d } from "../reshape16.js";
4
- import { matMulMul as f } from "../matMulMul.js";
5
- import { matMulGelu as p } from "../matMulGelu.js";
6
- import m from "./matMul16_program.js";
4
+ import { n as f } from "../../silu-B6bvCgJ7.js";
5
+ import { matMulMul as p } from "../matMulMul.js";
6
+ import { matMulGelu as m } from "../matMulGelu.js";
7
+ import h from "./matMul16_program.js";
7
8
  //#region lib/ops/webgpu/matMul16.ts
8
- function h(e) {
9
- let { A: h, B: g } = e.inputs, { transposeA: _, transposeB: v, scale: y, activation: b, scaleA: x, scaleB: S, forceOutputShape: C, perm: w, causalMask: T, pastLen: E } = e.attrs, D = e.backend, O = !u(h), k = !u(g);
10
- if (O && k) {
11
- let e = x === void 0 ? h : n(h, r(x)), t = S === void 0 ? g : n(g, r(S));
12
- if (T) throw Error("Causal mask is not supported for unpacked MatMul16.");
9
+ function g(e) {
10
+ let { A: g, B: _ } = e.inputs, { transposeA: v, transposeB: y, scale: b, activation: x, scaleA: S, scaleB: C, forceOutputShape: w, perm: T, causalMask: E, pastLen: D } = e.attrs, O = e.backend, k = !u(g), A = !u(_);
11
+ if (k && A) {
12
+ let e = S === void 0 ? g : n(g, r(S)), t = C === void 0 ? _ : n(_, r(C));
13
+ if (E) throw Error("Causal mask is not supported for unpacked MatMul16.");
13
14
  let c;
14
- if (b === "gelu") c = p(e, t);
15
- else if (b === "relu2") {
16
- let n = a(e, t, _, v), r = s(n);
15
+ if (x === "gelu") c = m(e, t);
16
+ else if (x === "relu2") {
17
+ let n = a(e, t, v, y), r = s(n);
17
18
  n.dispose(), c = o(r), r.dispose();
18
- } else if (b === "relu") {
19
- if (c = s(a(e, t, _, v)), y !== void 0) {
20
- let e = n(c, r(y));
19
+ } else if (x === "relu") {
20
+ if (c = s(a(e, t, v, y)), b !== void 0) {
21
+ let e = n(c, r(b));
21
22
  c.dispose(), c = e;
22
23
  }
23
- } else c = y === void 0 ? a(e, t, _, v) : f(e, t, r(y), _, v);
24
- if (w) if (C) {
25
- let e = i(c, C);
24
+ } else if (x === "silu") {
25
+ if (c = f(a(e, t, v, y)), b !== void 0) {
26
+ let e = n(c, r(b));
27
+ c.dispose(), c = e;
28
+ }
29
+ } else c = b === void 0 ? a(e, t, v, y) : p(e, t, r(b), v, y);
30
+ if (T) if (w) {
31
+ let e = i(c, w);
26
32
  c.dispose();
27
- let t = l(e, w);
33
+ let t = l(e, T);
28
34
  return e.dispose(), t;
29
35
  } else {
30
- let e = l(c, w);
36
+ let e = l(c, T);
31
37
  return c.dispose(), e;
32
38
  }
33
- else if (C) {
34
- let e = i(c, C);
39
+ else if (w) {
40
+ let e = i(c, w);
35
41
  return c.dispose(), e;
36
42
  } else return c;
37
43
  }
38
- if (O && !k) throw Error("When using mixed precision, A must be packed if B is packed.");
39
- if (!O && k) throw Error("When using mixed precision, B must be packed if A is packed.");
40
- let A = h.shape.length, j = g.shape.length, M = h.shape.slice(0, -2), N = g.shape.slice(0, -2), P = c(M), F = c(N), I = t(h.shape.slice(0, -2), g.shape.slice(0, -2)), L = Math.max(P, F), R = h.shape[A - 2], z = g.shape[j - 2], B = h.shape[A - 1] * 2, V = g.shape[j - 1] * 2, H = d(h, [
41
- P,
42
- h.shape[A - 2],
43
- h.shape[A - 1]
44
- ]), U = d(g, [
44
+ if (k && !A) throw Error("When using mixed precision, A must be packed if B is packed.");
45
+ if (!k && A) throw Error("When using mixed precision, B must be packed if A is packed.");
46
+ let j = g.shape.length, M = _.shape.length, N = g.shape.slice(0, -2), P = _.shape.slice(0, -2), F = c(N), I = c(P), L = t(g.shape.slice(0, -2), _.shape.slice(0, -2)), R = Math.max(F, I), z = g.shape[j - 2], B = _.shape[M - 2], V = g.shape[j - 1] * 2, H = _.shape[M - 1] * 2, U = d(g, [
45
47
  F,
46
48
  g.shape[j - 2],
47
49
  g.shape[j - 1]
48
- ]), W = new m(L, R, z, B, V, _, v), G = [];
49
- y !== void 0 && (W.useScale(), G.push({
50
+ ]), W = d(_, [
51
+ I,
52
+ _.shape[M - 2],
53
+ _.shape[M - 1]
54
+ ]), G = new h(R, z, B, V, H, v, y), K = [];
55
+ b !== void 0 && (G.useScale(), K.push({
50
56
  type: "float32",
51
- data: [y]
52
- })), x !== void 0 && (W.useScaleA(), G.push({
53
- type: "float32",
54
- data: [x]
55
- })), S !== void 0 && (W.useScaleB(), G.push({
57
+ data: [b]
58
+ })), S !== void 0 && (G.useScaleA(), K.push({
56
59
  type: "float32",
57
60
  data: [S]
58
- })), b !== void 0 && W.useActivation(b), T && (W.useCausalMask(), G.push({
61
+ })), C !== void 0 && (G.useScaleB(), K.push({
62
+ type: "float32",
63
+ data: [C]
64
+ })), x !== void 0 && G.useActivation(x), E && (G.useCausalMask(), K.push({
59
65
  type: "int32",
60
- data: [E || 0]
66
+ data: [D || 0]
61
67
  }));
62
- let K = W.outputShape.length;
63
- C && (e.attrs.originalShape = W.outputShape);
64
- let q = C ?? I.concat([W.outputShape[K - 2], W.outputShape[K - 1]]);
65
- W.setOutputShape(q, w);
66
- let J = D.runWebGPUProgram(W, [H, U], "packedF16", G.length > 0 ? G : void 0);
67
- return H.dispose(), U.dispose(), J;
68
+ let q = G.outputShape.length;
69
+ w && (e.attrs.originalShape = G.outputShape);
70
+ let J = w ?? L.concat([G.outputShape[q - 2], G.outputShape[q - 1]]);
71
+ G.setOutputShape(J, T);
72
+ let Y = O.runWebGPUProgram(G, [U, W], "packedF16", K.length > 0 ? K : void 0);
73
+ return U.dispose(), W.dispose(), Y;
68
74
  }
69
75
  e({
70
76
  kernelName: "MatMul16",
71
77
  backendName: "webgpu",
72
- kernelFunc: h
78
+ kernelFunc: g
73
79
  });
74
80
  //#endregion
@@ -19,7 +19,7 @@ export default class MatMul16ProgramGeneric implements WebGPUProgram {
19
19
  scale: boolean;
20
20
  scaleA: boolean;
21
21
  scaleB: boolean;
22
- activation?: 'gelu' | 'relu2' | 'relu';
22
+ activation?: 'gelu' | 'relu2' | 'relu' | 'silu';
23
23
  causalMask: boolean;
24
24
  outputComponent?: number | undefined;
25
25
  variableComponents?: number[];
@@ -31,7 +31,7 @@ export default class MatMul16ProgramGeneric implements WebGPUProgram {
31
31
  useScale(): void;
32
32
  useScaleA(): void;
33
33
  useScaleB(): void;
34
- useActivation(activation: 'gelu' | 'relu2' | 'relu'): void;
34
+ useActivation(activation: 'gelu' | 'relu2' | 'relu' | 'silu'): void;
35
35
  useCausalMask(): void;
36
36
  private activationSnippet;
37
37
  private readASnippet;
@@ -110,7 +110,7 @@ var n = class {
110
110
  this.causalMask = !0, this.addUniform("pastLen: i32"), this.shaderKey += "_causalMask";
111
111
  }
112
112
  activationSnippet() {
113
- return this.activation === "gelu" ? "\n // TODO: revisit after https://github.com/gpuweb/gpuweb/issues/4458 is resolved\n fn tanhComplete(x: vec4<f32>) -> vec4<f32> {\n return vec4<f32>(\n select(tanh(x.x), sign(x.x), abs(x.x) > 15.0f),\n select(tanh(x.y), sign(x.y), abs(x.y) > 15.0f),\n select(tanh(x.z), sign(x.z), abs(x.z) > 15.0f),\n select(tanh(x.w), sign(x.w), abs(x.w) > 15.0f),\n );\n }\n fn activation(x : vec4<f32>) -> vec4<f32> {\n let x3 = x * x * x;\n var inner = fma(vec4<f32>(0.044715f), x3, x);\n inner = 0.7978845608028654f * inner;\n inner = tanhComplete(inner);\n inner = 0.5f * (1.0f + inner);\n return x * inner;\n }\n " : this.activation === "relu2" ? "\n fn activation(x : vec4<f32>) -> vec4<f32> {\n let y = max(x, vec4<f32>(0.0));\n return y * y;\n }\n " : this.activation === "relu" ? "\n fn activation(x : vec4<f32>) -> vec4<f32> {\n return max(x, vec4<f32>(0.0));\n }\n " : "";
113
+ return this.activation === "gelu" ? "\n // TODO: revisit after https://github.com/gpuweb/gpuweb/issues/4458 is resolved\n fn tanhComplete(x: vec4<f32>) -> vec4<f32> {\n return vec4<f32>(\n select(tanh(x.x), sign(x.x), abs(x.x) > 15.0f),\n select(tanh(x.y), sign(x.y), abs(x.y) > 15.0f),\n select(tanh(x.z), sign(x.z), abs(x.z) > 15.0f),\n select(tanh(x.w), sign(x.w), abs(x.w) > 15.0f),\n );\n }\n fn activation(x : vec4<f32>) -> vec4<f32> {\n let x3 = x * x * x;\n var inner = fma(vec4<f32>(0.044715f), x3, x);\n inner = 0.7978845608028654f * inner;\n inner = tanhComplete(inner);\n inner = 0.5f * (1.0f + inner);\n return x * inner;\n }\n " : this.activation === "relu2" ? "\n fn activation(x : vec4<f32>) -> vec4<f32> {\n let y = max(x, vec4<f32>(0.0));\n return y * y;\n }\n " : this.activation === "relu" ? "\n fn activation(x : vec4<f32>) -> vec4<f32> {\n return max(x, vec4<f32>(0.0));\n }\n " : this.activation === "silu" ? "\n fn activation(x : vec4<f32>) -> vec4<f32> {\n return x * (1.0 / (1.0 + exp(-x)));\n }\n " : "";
114
114
  }
115
115
  readASnippet() {
116
116
  let e = `