@mineproness/tensorloop 2.1.68 → 2.1.70

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/index.js CHANGED
@@ -8,6 +8,7 @@ import {SelfAttention as ST} from './src/SelfAttention/index.js'
8
8
  import {TransformerBlock as TT} from './src/TransformerBlock/index.js'
9
9
  import { Model as m } from "./src/Model/index.js";
10
10
  import {PositionEmbedding as PM } from './src/PositionEmbedding/index.js'
11
+ import { RMSNorm as RM } from "./src/RMSNorm/index.js";
11
12
  export const Embedding = E
12
13
  export const Linear = L
13
14
  export const Softmax = S;
@@ -17,4 +18,5 @@ export const Tokenizer = to;
17
18
  export const SelfAttention = ST
18
19
  export const TransformerBlock = TT;
19
20
  export const Model = m;
20
- export const PositionEmbedding = PM;
21
+ export const PositionEmbedding = PM;
22
+ export const RMSNorm = RM
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mineproness/tensorloop",
3
- "version": "2.1.68",
3
+ "version": "2.1.70",
4
4
  "description": "Raw-JAVASCRIPT Based Matirx and AI LLM Package called Tensorloop.",
5
5
  "keywords": [
6
6
  "ai",
@@ -1,4 +1,4 @@
1
- import { Embedding, Linear, Softmax, TransformerBlock, Tokenizer, PositionEmbedding } from '../../index.js'
1
+ import { Embedding, Linear, Softmax, TransformerBlock, Tokenizer, PositionEmbedding, RMSNorm } from '../../index.js'
2
2
  import { join } from 'path'
3
3
  import fs from 'fs'
4
4
  import { OperationManager } from '../OperationManager.js'
@@ -16,6 +16,7 @@ export class Model {
16
16
  tokenizerName;
17
17
  op;
18
18
  tokens;
19
+ rmsnorm
19
20
  constructor(device, embeddingSize = 64, configs) {
20
21
  this.device = device;
21
22
  this.dimSize = embeddingSize;
@@ -0,0 +1,10 @@
1
+ export class RMSNorm{
2
+ constructor(device : GPUAdapter, embeddingSize : number , {
3
+ save:{
4
+ filename: string
5
+ }
6
+ });
7
+ async forward(input : GPUBuffer) : Promise<GPUBuffer>
8
+ async backward(outputGradient : GPUBuffer) : Promise<GPUBuffer>
9
+ async Save() : Promise<void>
10
+ }
@@ -0,0 +1,84 @@
1
+ import { OperationManager } from '../OperationManager.js'
2
+ import fs from 'fs'
3
+ import { SaveVector, getVector } from '../getVec.js'
4
+
5
+ export class RMSNorm {
6
+ embeddingSize;
7
+ reductionShader;
8
+ forwardShader;
9
+ backwardShader;
10
+ op;
11
+ gamma;
12
+ gammabuffer;
13
+ configs;
14
+ constructor(device, embeddingSize, configs) {
15
+ this.configs = configs
16
+ this.op = new OperationManager(device);
17
+ this.embeddingSize = embeddingSize;
18
+ this.reductionShader = this.op.getShaderPipline("./src/shaders/Norm/sumSquare.wgsl", {
19
+ embeddingSize: embeddingSize,
20
+ })
21
+ this.forwardShader = this.op.getShaderPipline("./src/shaders/Norm/rmsForward.wgsl", {
22
+ embeddingSize: embeddingSize
23
+ })
24
+ this.backwardShader = this.op.getShaderPipline("./src/shaders/Norm/rmsBackward.wgsl", {
25
+ embeddingSize: embeddingSize
26
+ })
27
+ this.updateGamma = this.op.getShaderPipline("./src/shaders/Norm/updateGamma.wgsl", {
28
+ embeddingSize: embeddingSize
29
+ })
30
+ if (configs) {
31
+ const ga = getVector(configs.save.filename, embeddingSize);
32
+ if (!ga) {
33
+ this.gamma = new Float32Array(embeddingSize).fill(1);
34
+ SaveVector(configs.save.filename, this.gamma)
35
+ } else {
36
+ this.gamma = ga
37
+ }
38
+ } else {
39
+ this.gamma = new Float32Array(embeddingSize).fill(1)
40
+ }
41
+ }
42
+ async forward(input) {
43
+ if (!this.gammabuffer) {
44
+ this.gammabuffer = await this.op.createBuffer(4 * this.embeddingSize);
45
+ await this.op.WriteBuffer(this.gammabuffer, this.gamma);
46
+ }
47
+ let context = input.size / (this.embeddingSize * 4)
48
+ const outputReduce = await this.op.createBuffer(4 * context);
49
+ const output = await this.op.createBuffer(input.size);
50
+ const bindGroup = await this.op.createBindGroup(this.reductionShader, 0, [input, outputReduce])
51
+ const encoder = await this.op.CreateEncoder()
52
+ await this.op.RunPipline(encoder, this.reductionShader, bindGroup, Math.ceil((input.size / 4) / 64))
53
+ const bindGroup1 = await this.op.createBindGroup(this.forwardShader, 0, [outputReduce, input, output, this.gammabuffer])
54
+ await this.op.RunPipline(encoder, this.forwardShader, bindGroup1, Math.ceil((input.size / 4) / 64));
55
+ await this.op.submitQueue(encoder);
56
+ if (this.rms) this.rms.destroy()
57
+ this.rms = outputReduce
58
+ if (this.input) this.input.destroy()
59
+ this.input = input;
60
+ if (this.outputPre) this.outputPre.destroy()
61
+ this.outputPre = output
62
+ return output
63
+ }
64
+ async backward(outputGradient, lr) {
65
+ const output = await this.op.createBuffer(outputGradient.size);
66
+ let params = await this.op.createBuffer(4 * 2)
67
+ await this.op.WriteBuffer(params, new Float32Array([lr, 0]))
68
+ const bindGroup = await this.op.createBindGroup(this.backwardShader, 0, [this.input, outputGradient, this.rms, this.gammabuffer, output]);
69
+ const bindGroup2 = await this.op.createBindGroup(this.updateGamma, 0, [this.input, outputGradient, this.rms, this.gammabuffer, params]);
70
+ const encoder = await this.op.CreateEncoder()
71
+ await this.op.RunPipline(encoder, this.backwardShader, bindGroup, Math.ceil((this.input.size / 4) / 64))
72
+ await this.op.RunPipline(encoder, this.updateGamma, bindGroup2, this.embeddingSize)
73
+ await this.op.submitQueue(encoder)
74
+ if (this.prevOut) this.prevOut.destroy()
75
+ this.prevOut = outputGradient
76
+ params.destroy()
77
+ return output
78
+ }
79
+ async Save(){
80
+ const read = await this.op.readBuffer(4 * this.embeddingSize, this.gammabuffer);
81
+ SaveVector(this.configs.save.filename, read)
82
+ }
83
+
84
+ }
@@ -1,47 +1,85 @@
1
- import {SelfAttention} from '../SelfAttention/index.js'
2
- import {FFN} from '../FFN/index.js'
3
- import {existsSync, mkdirSync} from 'fs'
4
- import {OperationManager} from '../OperationManager.js'
5
- export class TransformerBlock{
1
+
2
+ import { SelfAttention } from '../SelfAttention/index.js';
3
+ import { FFN } from '../FFN/index.js';
4
+ import { existsSync, mkdirSync } from 'fs';
5
+ import { RMSNorm } from '../../index.js';
6
+ import { OperationManager } from '../OperationManager.js';
7
+ import { join } from 'path';
8
+
9
+ export class TransformerBlock {
6
10
  attention;
7
11
  ffn;
8
12
  gpu;
9
13
  size;
10
- constructor(device, embeddingSize, configs){
14
+ rmsnorm;
15
+ rmsnorm2;
16
+
17
+ constructor(device, embeddingSize, configs) {
11
18
  this.size = embeddingSize;
12
- if(!existsSync(configs.dirname)) mkdirSync(configs.dirname);
13
- this.attention = new SelfAttention(device, embeddingSize, configs)
14
- this.ffn = new FFN(device, embeddingSize, configs)
15
- this.gpu = new OperationManager(device)
19
+
20
+ this.rmsnorm = new RMSNorm(device, embeddingSize, {
21
+ save: {
22
+ filename: join(configs.dirname, "LAYERNORM-1.bin")
23
+ }
24
+ });
25
+ this.rmsnorm2 = new RMSNorm(device, embeddingSize, {
26
+ save: {
27
+ filename: join(configs.dirname, "LAYERNORM-2.bin")
28
+ }
29
+ });
30
+
31
+ if (!existsSync(configs.dirname)) {
32
+ mkdirSync(configs.dirname, { recursive: true });
33
+ }
34
+
35
+ this.attention = new SelfAttention(
36
+ device, embeddingSize, configs
37
+ );
38
+
39
+ this.ffn = new FFN(device, embeddingSize, configs);
40
+ this.gpu = new OperationManager(device);
16
41
  }
17
- async forward(input){
18
- let context = input.size / (this.size * 4)
19
- const xAtt = await this.attention.forward(input);
20
- const re1 = await this.gpu.add(input, xAtt, this.size * context)
21
- const xFF = await this.ffn.forward(re1);
22
- const re2 = await this.gpu.add(re1, xFF, this.size * context)
23
- xAtt.destroy()
24
- xFF.destroy()
25
- return re2
42
+
43
+ async forward(input) {
44
+ const count = input.size / 4;
45
+ const norm1 = await this.rmsnorm.forward(input);
46
+ const att = await this.attention.forward(norm1);
47
+ const h = await this.gpu.add(input, att, count);
48
+ const norm2 = await this.rmsnorm2.forward(h);
49
+ const f = await this.ffn.forward(norm2);
50
+ const y = await this.gpu.add(h, f, count);
51
+ norm1.destroy();
52
+ att.destroy();
53
+ f.destroy();
54
+ return y;
26
55
  }
27
- async backward(outGradient, lr){
28
- const context = outGradient.size / (this.size * 4)
29
- const dAtt = await this.ffn.backward(outGradient, lr);
30
- const re1 = await this.gpu.add(outGradient, dAtt, this.size * context)
31
- const dFF = await this.attention.backward(re1, lr)
32
- const re2 = await this.gpu.add(re1, dFF , context)
33
- outGradient.destroy()
34
- re1.destroy()
35
- dFF.destroy()
36
- dAtt.destroy()
37
- return re2
56
+
57
+ async backward(outGradient, lr) {
58
+ const count = outGradient.size / 4;
59
+ const dNorm2 = await this.ffn.backward(outGradient, lr);
60
+ const dHFromFFN = await this.rmsnorm2.backward(dNorm2 , lr);
61
+ const dH = await this.gpu.add(outGradient, dHFromFFN, count);
62
+ const dNorm1 = await this.attention.backward(dH, lr);
63
+ const dInputFromAttention = await this.rmsnorm.backward(dNorm1, lr);
64
+ const dInput = await this.gpu.add(dH, dInputFromAttention, count);
65
+ dNorm2.destroy();
66
+ dHFromFFN.destroy();
67
+ dH.destroy();
68
+ dNorm1.destroy();
69
+ dInputFromAttention.destroy();
70
+ dInputFromAttention.destroy();
71
+ return dInput;
38
72
  }
39
- async ClearInputCache(){
40
- await this.ffn.ClearInputCache()
41
- await this.attention.ClearInputCache()
73
+
74
+ async ClearInputCache() {
75
+ await this.ffn.ClearInputCache();
76
+ await this.attention.ClearInputCache();
42
77
  }
43
- async Save(){
44
- await this.ffn.Save()
45
- await this.attention.Save()
78
+
79
+ async Save() {
80
+ await this.ffn.Save();
81
+ await this.attention.Save();
82
+ await tthis.rmsnorm.Save()
83
+ await this.rmsnorm2.Save()
46
84
  }
47
85
  }
@@ -42,14 +42,14 @@ fn main(@builtin(global_invocation_id) id: vec3<u32>) {
42
42
  let inputValue = input[token * u32(params.inputSize) + inputIndex];
43
43
  let gradient = outGradient[token * u32(params.vocabSize) + outputIndex];
44
44
  let dW = inputValue * gradient;
45
- dWeights += f32(max(-3.0, min(3.0, dW)));
45
+ dWeights += dW;
46
46
  }
47
47
  let vClap = weight[index] - params.lr * dWeights;
48
48
  weight[index] = vClap;
49
49
  if (inputIndex == 0u) {
50
50
  var dBias = 0.0;
51
51
  for (var token = 0u; token < u32(params.tokenCount); token++) {
52
- dBias += f32(max(-3.0, min(3.0, outGradient[token * u32(params.vocabSize) + outputIndex])));
52
+ dBias += outGradient[token * u32(params.vocabSize) + outputIndex];
53
53
  }
54
54
  bias[outputIndex] = bias[outputIndex] - params.lr * dBias;
55
55
 
@@ -0,0 +1,42 @@
1
+ @group(0) @binding(0)
2
+ var<storage, read> input: array<f32>;
3
+
4
+ @group(0) @binding(1)
5
+ var<storage, read> gradOutput: array<f32>;
6
+
7
+ @group(0) @binding(2)
8
+ var<storage, read> rms: array<f32>;
9
+
10
+ @group(0) @binding(3)
11
+ var<storage, read> gamma: array<f32>;
12
+
13
+ @group(0) @binding(4)
14
+ var<storage, read_write> gradInput: array<f32>;
15
+
16
+ var<workgroup> partial: array<f32, %embeddingSize%>;
17
+
18
+ @compute @workgroup_size(%embeddingSize%)
19
+ fn main(@builtin(local_invocation_index) lid: u32, @builtin(workgroup_id) wid: vec3<u32>) {
20
+ let D = %embeddingSize%u;
21
+ let token = wid.x;
22
+ let idx = token * D + lid;
23
+ let x = input[idx];
24
+ let dy = gradOutput[idx];
25
+ let g = gamma[lid];
26
+ let r = rms[token];
27
+ partial[lid] = dy * g * x;
28
+ workgroupBarrier();
29
+ var stride = D / 2u;
30
+ loop {
31
+ if (stride == 0u) {
32
+ break;
33
+ }
34
+ if (lid < stride) {
35
+ partial[lid] += partial[lid + stride];
36
+ }
37
+ workgroupBarrier();
38
+ stride /= 2u;
39
+ }
40
+ let dot = partial[0];
41
+ gradInput[idx] = (dy * g) / r - x * dot / (f32(D) * r * r * r);
42
+ }
@@ -0,0 +1,30 @@
1
+ @group(0) @binding(0)
2
+ var<storage, read> reduce: array<f32>;
3
+
4
+ @group(0) @binding(1)
5
+ var<storage, read> vector: array<f32>;
6
+
7
+ @group(0) @binding(2)
8
+ var<storage, read_write> output: array<f32>;
9
+
10
+ @group(0) @binding(3)
11
+ var<storage, read> gamma: array<f32>;
12
+
13
+ @compute @workgroup_size(64)
14
+ fn main(@builtin(global_invocation_id) id: vec3<u32>) {
15
+ let x = id.x;
16
+
17
+ if (x >= arrayLength(&vector)) {
18
+ return;
19
+ }
20
+
21
+ let dim = %embeddingSize%u;
22
+ let token = x / dim;
23
+ let d = x % dim;
24
+
25
+ let rms = sqrt(
26
+ reduce[token] / f32(dim) + 1e-6
27
+ );
28
+
29
+ output[x] = (vector[x] / rms) * gamma[d];
30
+ }
@@ -0,0 +1,35 @@
1
+ @group(0) @binding(0)
2
+ var<storage, read> input: array<f32>;
3
+
4
+ @group(0) @binding(1)
5
+ var<storage, read_write> out: array<f32>;
6
+
7
+
8
+ var<workgroup> partial: array<f32, %embeddingSize%>;
9
+
10
+ const embeddingSize : u32 = %embeddingSize%u;
11
+ @compute @workgroup_size(64)
12
+ fn main(@builtin(local_invocation_index) lid: u32, @builtin(workgroup_id) wid: vec3<u32>) {
13
+ let dim = embeddingSize;
14
+ let index = wid.x * dim + lid;
15
+ var sum = 0.0;
16
+ if (lid < dim && index < arrayLength(&input)) {
17
+ sum = input[index] * input[index];
18
+ }
19
+ partial[lid] = sum;
20
+ workgroupBarrier();
21
+ var stride = 32u;
22
+ loop {
23
+ if (stride == 0u) {
24
+ break;
25
+ }
26
+ if (lid < stride) {
27
+ partial[lid] += partial[lid + stride];
28
+ }
29
+ workgroupBarrier();
30
+ stride /= 2u;
31
+ }
32
+ if (lid == 0u) {
33
+ out[wid.x] = partial[0];
34
+ }
35
+ }
@@ -0,0 +1,61 @@
1
+ @group(0) @binding(0)
2
+ var<storage, read> input: array<f32>;
3
+
4
+ @group(0) @binding(1)
5
+ var<storage, read> gradOutput: array<f32>;
6
+
7
+ @group(0) @binding(2)
8
+ var<storage, read> rms: array<f32>;
9
+
10
+ @group(0) @binding(3)
11
+ var<storage, read_write> gamma: array<f32>;
12
+
13
+ @group(0) @binding(4)
14
+ var<storage, read> params: array<f32>;
15
+
16
+ var<workgroup> partial: array<f32, %embeddingSize%>;
17
+
18
+ @compute @workgroup_size(64)
19
+ fn main(@builtin(local_invocation_index) lid: u32, @builtin(workgroup_id) wid: vec3<u32>) {
20
+ let D = %embeddingSize%u;
21
+ let dim = wid.x;
22
+
23
+ if (dim >= D) {
24
+ return;
25
+ }
26
+
27
+ let T = arrayLength(&rms);
28
+ let lr = params[0];
29
+
30
+ var sum = 0.0;
31
+ var token = lid;
32
+
33
+ while (token < T) {
34
+ let idx = token * D + dim;
35
+
36
+ sum += gradOutput[idx] * input[idx] / rms[token];
37
+
38
+ token += 64u;
39
+ }
40
+
41
+ partial[lid] = sum;
42
+ workgroupBarrier();
43
+
44
+ var stride = 32u;
45
+ loop {
46
+ if (stride == 0u) {
47
+ break;
48
+ }
49
+
50
+ if (lid < stride) {
51
+ partial[lid] += partial[lid + stride];
52
+ }
53
+
54
+ workgroupBarrier();
55
+ stride /= 2u;
56
+ }
57
+ if (lid == 0u) {
58
+ let gradGamma = partial[0];
59
+ gamma[dim] -= lr * gradGamma;
60
+ }
61
+ }