@mineproness/tensorloop 1.2.4 → 1.2.6

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
@@ -5,10 +5,14 @@ import { Softmax as softmax2 } from "./src/Softmax/index.js";
5
5
  import { crossEntropy } from "./src/crossEntropy/index.js";
6
6
  import {tools} from './src/tools/index.js'
7
7
  import {ReLU} from './src/ReLU/index.js'
8
+ import {PositionEmbedding as PE} from './src/PositionEmbedding/index.js'
9
+ import {SelfAttention as ST} from './src/SelfAttention/index.js'
8
10
  export const Tokenizer = tokenizer
9
11
  export const Embedding = embeddding2
10
12
  export const Linear = li2
11
13
  export const Softmax = softmax2
12
14
  export const CrossEntropy = crossEntropy
13
15
  export const Tools = tools
14
- export const ReLu = ReLU
16
+ export const ReLu = ReLU
17
+ export const PositionEmbedding = PE
18
+ export const SelfAttention = ST
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mineproness/tensorloop",
3
- "version": "1.2.4",
3
+ "version": "1.2.6",
4
4
  "description": "The most powerfull Machine Learning Library for AI.",
5
5
  "keywords": [
6
6
  "ai",
package/readme.md CHANGED
@@ -10,6 +10,8 @@ A Library that Supply AI Tools and Large Language model Development tools like E
10
10
  - CrossEntroy for Loss Calculation.
11
11
  - Relu for Stable Layer.
12
12
  - Tokenizer for convert into tokens.
13
+ - Self attention
14
+ - Position Embedding
13
15
 
14
16
  ## Configs
15
17
 
@@ -1,5 +1,5 @@
1
1
  import fs, { existsSync } from 'fs'
2
- import { GetEmbeddingVectors, SaveEmbeddingVectors, SaveVectors } from '../GetConfigs.js'
2
+ import { SaveVectors, LoadVectors } from '../GetConfigs.js'
3
3
  // import { config } from 'process'
4
4
 
5
5
  function GenerateVectors(embeddingSize, vocabSize) {
@@ -22,7 +22,7 @@ export class Embedding {
22
22
  this.embeddingSize = embeddingSize
23
23
  if (configs && configs.save) {
24
24
  if (existsSync(configs.save.filename)) {
25
- this.vectors = []
25
+ this.vectors = LoadVectors(configs.save.filename, embeddingSize)
26
26
  } else {
27
27
  this.vectors = GenerateVectors(embeddingSize, vocabSize)
28
28
  this.Save()
@@ -35,15 +35,9 @@ export class Embedding {
35
35
  forward(token) {
36
36
  if (Array.isArray(token)) {
37
37
  return token.map((e) => {
38
- const id = this.vectors[e]
39
- if (id) return id
40
- this.vectors[e] = GetEmbeddingVectors(e, this.embeddingSize, this.configs.save.filename)
41
38
  return this.vectors[e]
42
39
  })
43
40
  } else {
44
- if (!this.vectors[token]) {
45
- this.vectors[token] = GetEmbeddingVectors(token, this.embeddingSize, this.configs.save.filename)
46
- }
47
41
  return this.vectors[token]
48
42
  }
49
43
  }
@@ -53,6 +47,6 @@ export class Embedding {
53
47
  }
54
48
  }
55
49
  Save() {
56
- SaveEmbeddingVectors(this.vectors, this.configs.save.filename)
50
+ SaveVectors(this.vectors, this.configs.save.filename)
57
51
  }
58
52
  }
package/src/GetConfigs.js CHANGED
@@ -1,62 +1,35 @@
1
- import fs from "fs";
2
- import { join } from "path";
3
-
4
- export function SaveVectors(filename, vectors) {
5
- const fd = fs.openSync(filename, "w");
6
-
7
- try {
8
- for (const vector of vectors) {
9
- fs.writeSync(fd, Buffer.from(vector.buffer, vector.byteOffset, vector.byteLength));
10
- }
11
- } finally {
12
- fs.closeSync(fd);
13
- }
14
- }
15
-
16
- export function GetWeights(filename, embeddingSize) {
17
- const fileBuffer = fs.readFileSync(filename)
18
- const ELEMENTS_PER_ARRAY = embeddingSize;
19
- const BYTES_PER_ELEMENT = Float32Array.BYTES_PER_ELEMENT
20
- const BYTES_PER_ARRAY = ELEMENTS_PER_ARRAY * BYTES_PER_ELEMENT
21
- const totalArraySaved = fileBuffer.byteLength / BYTES_PER_ARRAY;
22
- const totalArray = []
23
- for (let i = 0; i < totalArraySaved; i++) {
24
- const currentOffset = fileBuffer.byteOffset + (i * BYTES_PER_ARRAY)
25
- const f32 = new Float32Array(fileBuffer.buffer, currentOffset, ELEMENTS_PER_ARRAY)
26
- totalArray.push(f32)
27
- }
28
- return totalArray
1
+ import fs from 'fs'
2
+ import { join } from 'path'
3
+
4
+ export function SaveVectors(vectors, path){
5
+ const rows = vectors.length;
6
+ const cols = vectors[0].length;
7
+ const flatArray = new Float32Array(rows * cols)
8
+ vectors.forEach((e,i)=>{
9
+ flatArray.set(e, i * cols)
10
+ })
11
+ const bufferArray = Buffer.from(flatArray.buffer, flatArray.byteOffset, flatArray.byteLength)
12
+ fs.writeFileSync(path, bufferArray)
29
13
  }
30
14
 
31
- export function GetVector(filename) {
32
- const buffer = fs.readFileSync(filename)
33
- return new Float32Array(buffer.buffer, buffer.byteOffset, buffer.byteLength / Float32Array.BYTES_PER_ELEMENT)
15
+ export function LoadVectors(path, cols){
16
+ const buffer = fs.readFileSync(path)
17
+ const flatArray = new Float32Array(buffer.buffer, buffer.byteOffset, buffer.byteLength / 4 )
18
+ const vectors = []
19
+ const rows = flatArray.length / cols;
20
+ for(let a = 0; a < rows; a++){
21
+ vectors.push(flatArray.slice(a * cols, (a+1) * cols))
22
+ }
23
+ return vectors
34
24
  }
35
25
 
36
- export function Save(filename, vector) {
37
- return fs.writeFileSync(filename, Buffer.from(vector.buffer))
26
+ export function SaveBias(vectors, path){
27
+ const bufferArray = Buffer.from(vectors.buffer, vectors.byteOffset, vectors.byteLength)
28
+ fs.writeFileSync(path, bufferArray)
38
29
  }
39
30
 
40
- export function GetEmbeddingVectors(token, embeddingSize, filename) {
41
- const fd = fs.openSync(filename, "r")
42
- const PER_BTYES_VECTOR = embeddingSize * Float32Array.BYTES_PER_ELEMENT
43
- const buffer = Buffer.allocUnsafe(PER_BTYES_VECTOR)
44
- fs.readSync(fd, buffer, 0, PER_BTYES_VECTOR, token * PER_BTYES_VECTOR)
45
- fs.closeSync(fd)
46
- return new Float32Array(buffer.buffer, buffer.byteOffset, embeddingSize)
47
- }
48
-
49
- export function SaveEmbeddingVectors(vectors = [new Float32Array([1, 2, 3])], filename) {
50
- const fd = fs.openSync(filename, "w")
51
- try {
52
- for (let a = 0; a < vectors.length; a++) {
53
- const vector = vectors[a]
54
- if (vector == undefined) continue;
55
- const offset = a * vector.length * Float32Array.BYTES_PER_ELEMENT;
56
- fs.writeSync(fd, Buffer.from(vector.buffer, vector.byteOffset, vector.byteLength) , 0 , vector.byteLength, offset)
57
-
58
- }
59
- }finally{
60
- fs.closeSync(fd)
61
- }
31
+ export function LoadBias(path){
32
+ const buffer = fs.readFileSync(path)
33
+ const flatArray = new Float32Array(buffer.buffer, buffer.byteOffset, buffer.byteLength / 4 )
34
+ return vectors
62
35
  }
@@ -7,6 +7,6 @@ export class Linear{
7
7
  }
8
8
  })
9
9
  forward(input : number[]) : Float32Array[]
10
- backward(outGradient : number[] , learingRate: number) : Float32Array[]
10
+ backward(outGradient : number[] , learingRate: number, idx: number) : Float32Array[]
11
11
  Save() : void
12
12
  }
@@ -1,4 +1,4 @@
1
- import { GetWeights, Save,GetVector , SaveVectors } from '../GetConfigs.js'
1
+ import { LoadBias,LoadVectors,SaveBias,SaveVectors } from '../GetConfigs.js'
2
2
  import { existsSync } from 'fs'
3
3
  function GenerateWeightsBias(embeddingSize, vocabSize) {
4
4
  const vectors = []
@@ -22,8 +22,8 @@ export class Linear {
22
22
  if (configs && configs.save) {
23
23
  this.configs = configs
24
24
  if (existsSync(configs.save.filename[0]) && existsSync(configs.save.filename[1])) {
25
- const Vectors = GetWeights(configs.save.filename[0], embeddingSize)
26
- const Bias = GetVector(configs.save.filename[1])
25
+ const Vectors = LoadVectors(configs.save.filename[0], embeddingSize)
26
+ const Bias = LoadBias(configs.save.filename[1])
27
27
  this.Weights = Vectors;
28
28
  this.Bias = Bias
29
29
  } else {
@@ -31,7 +31,7 @@ export class Linear {
31
31
  this.Weights = vectors;
32
32
  this.Bias = Bias;
33
33
  SaveVectors(configs.save.filename[0], this.Weights)
34
- Save(configs.save.filename[1], this.Bias)
34
+ SaveBias(configs.save.filename[1], this.Bias)
35
35
  }
36
36
  } else {
37
37
  const { vectors, Bias } = GenerateWeightsBias(embeddingSize, vocabSize)
@@ -41,10 +41,10 @@ export class Linear {
41
41
  }
42
42
  Save() {
43
43
  SaveVectors(this.configs.save.filename[0], this.Weights)
44
- Save(this.configs.save.filename[1], this.Bias)
44
+ SaveBias(this.configs.save.filename[1], this.Bias)
45
45
  }
46
46
  forward(input) {
47
- this.input = input
47
+ this.input.push(input)
48
48
  const output = new Float32Array(this.Weights.length)
49
49
  for (let a = 0; a < this.Weights.length; a++) {
50
50
  let sum = this.Bias[a]
@@ -55,10 +55,10 @@ export class Linear {
55
55
  }
56
56
  return output
57
57
  }
58
- backward(outputGradient, learningRate) {
59
- const input = this.input;
58
+ backward(outputGradient, learningRate, idx) {
59
+ const input = this.input[idx];
60
60
  const weights = this.Weights
61
- const inputGradient = new Float32Array(this.input.length)
61
+ const inputGradient = new Float32Array(input.length)
62
62
  for (let a = 0; a < weights.length; a++) {
63
63
  const gran = outputGradient[a]
64
64
  const w = weights[a]
@@ -0,0 +1,12 @@
1
+ export class PositionEmbedding{
2
+ vectors: Float32Array[]
3
+ constructor(embeddingSize: number, contextSize: number, configs: {
4
+ save: {
5
+ filename: string
6
+ }
7
+ })
8
+ forward(position: number | number[]) : Float32Array[] | Float32Array[][]
9
+ backward(pos: number , inputGradient: number[] | Float32Array[], learingRate: number) : void
10
+ Save() : void;
11
+ addPos(PSEM, vectors : Float32Array[][]) : Float32Array
12
+ }
@@ -0,0 +1,67 @@
1
+ import fs, { existsSync } from 'fs'
2
+ import { LoadVectors, SaveVectors } from '../GetConfigs.js'
3
+ // import { config } from 'process'
4
+
5
+ function GenerateVectors(embeddingSize, vocabSize) {
6
+ const vector = []
7
+ for (let token = 0; token < vocabSize; token++) {
8
+ vector[token] = new Float32Array(embeddingSize)
9
+ for (let a = 0; a < embeddingSize; a++) {
10
+ vector[token][a] = (Math.random() * 2 - 1) * 0.2
11
+ }
12
+ }
13
+ return vector
14
+ }
15
+
16
+ export class PositionEmbedding {
17
+ vectors = []
18
+ configs;
19
+ embeddingSize = 0
20
+ constructor(embeddingSize, vocabSize, configs) {
21
+ this.configs = configs
22
+ this.embeddingSize = embeddingSize
23
+ if (configs && configs.save) {
24
+ if (existsSync(configs.save.filename)) {
25
+ this.vectors = LoadVectors(onfigs.save.filename, embeddingSize)
26
+ } else {
27
+ this.vectors = GenerateVectors(embeddingSize, vocabSize)
28
+ this.Save()
29
+ }
30
+ } else {
31
+ this.vectors = GenerateVectors(embeddingSize, vocabSize)
32
+
33
+ }
34
+ }
35
+ forward(token) {
36
+ if (Array.isArray(token)) {
37
+ return token.map((e) => {
38
+ return this.vectors[e]
39
+ })
40
+ } else {
41
+
42
+ return this.vectors[token]
43
+ }
44
+ }
45
+ backward(token, inputGradient, learingRate) {
46
+ for (let a = 0; a < this.vectors[token].length; a++) {
47
+ this.vectors[token][a] -= learingRate * inputGradient[a]
48
+ }
49
+ }
50
+ Save() {
51
+ SaveVectors(this.vectors, this.configs.save.filename)
52
+ }
53
+ addPos(xEM) {
54
+ const out = []
55
+
56
+ for (let pos = 0; pos < xEM.length; pos++) {
57
+ const tokenVector = xEM[pos]
58
+ const posVector = this.forward(pos)
59
+ const x = new Float32Array(xEM[0].length)
60
+ for (let a = 0; a < tokenVector.length; a++) {
61
+ x[a] = tokenVector[a] + posVector[a]
62
+ }
63
+ out.push(x)
64
+ }
65
+ return out
66
+ }
67
+ }
@@ -0,0 +1,16 @@
1
+ export class SelfAttention{
2
+ q : Float32Array[]
3
+ v : Float32Array[]
4
+ k : Float32Array[]
5
+ input;
6
+ constructor(embeddingSize : number, configs: {
7
+ save: {
8
+ dirname: string
9
+ }
10
+ })
11
+ weights : Float32Array[]
12
+ score : number
13
+ forward(vectors: Float32Array[][])
14
+ Save() : void
15
+ backward(dOutput, learningRate)
16
+ }
@@ -0,0 +1,118 @@
1
+ import { Softmax } from '../../index.js';
2
+ import { Linear } from '../Linear/index.js'
3
+
4
+ export class SelfAttention {
5
+ query;
6
+ key;
7
+ value;
8
+ v;
9
+ k;
10
+ q;
11
+ input;
12
+ configs;
13
+ score;
14
+ softmax;
15
+ weights;
16
+ constructor(embeddingSize, configs) {
17
+ this.configs = configs
18
+ this.softmax = new Softmax()
19
+ this.score = Math.sqrt(embeddingSize)
20
+ this.query = new Linear(embeddingSize, embeddingSize, { save: { filename: [`./${configs.dirname}/query.bin`, `./${configs.dirname}/queryBias.bin`] } })
21
+ this.key = new Linear(embeddingSize, embeddingSize, { save: { filename: [`./${configs.dirname}/key.bin`, `./${configs.dirname}/keyBias.bin`] } })
22
+ this.value = new Linear(embeddingSize, embeddingSize, { save: { filename: [`./${configs.dirname}/value.bin`, `./${configs.dirname}/valueBias.bin`] } })
23
+ }
24
+ forward(vectors) {
25
+ this.q = vectors.map((e) => this.query.forward(e))
26
+ this.v = vectors.map((e) => this.value.forward(e))
27
+ this.k = vectors.map((e) => this.key.forward(e))
28
+ // console.log(this.q, this.k, this.v)
29
+ const attentionSocres = []
30
+ for (let i = 0; i < this.q.length; i++) {
31
+ attentionSocres[i] = new Float32Array(this.k.length)
32
+ for (let a = 0; a < this.k.length; a++) {
33
+ let dot = 0;
34
+ for (let d = 0; d < this.q[i].length; d++) {
35
+ dot += this.q[i][d] * this.k[a][d]
36
+ }
37
+ attentionSocres[i][a] = dot / this.score
38
+ }
39
+ }
40
+ const weights = attentionSocres.map((e) => this.softmax.forward(e))
41
+ this.weights = weights
42
+ const output = [];
43
+
44
+ for (let i = 0; i < weights.length; i++) {
45
+ output[i] = new Float32Array(this.v[0].length);
46
+
47
+ for (let j = 0; j < this.v.length; j++) {
48
+ for (let d = 0; d < this.v[j].length; d++) {
49
+ output[i][d] += weights[i][j] * this.v[j][d];
50
+ }
51
+ }
52
+ }
53
+
54
+ return output;
55
+ }
56
+ softmaxBack(probs, dOut) {
57
+ const dIn = new Float32Array(probs.length);
58
+
59
+ for (let i = 0; i < probs.length; i++) {
60
+ let sum = 0;
61
+
62
+ for (let j = 0; j < probs.length; j++) {
63
+ const jacobian =
64
+ i === j
65
+ ? probs[i] * (1 - probs[i])
66
+ : -probs[i] * probs[j];
67
+
68
+ sum += jacobian * dOut[j];
69
+ }
70
+
71
+ dIn[i] = sum;
72
+ }
73
+
74
+ return dIn;
75
+ }
76
+ backward(dOutput, learningRate) {
77
+ const dV = this.v.map((e) => new Float32Array(e.length));
78
+ const dWeights = []
79
+ for (let a = 0; a < this.weights.length; a++) {
80
+ dWeights[a] = new Float32Array(this.weights[a].length)
81
+ for (let j = 0; j < this.v.length; j++) {
82
+ for (let r = 0; r < this.v[j].length; r++) {
83
+ dWeights[a][j] += dOutput[a][r] * this.v[j][r]
84
+ dV[j][r] += dOutput[a][r] * this.weights[a][j]
85
+ }
86
+ }
87
+ }
88
+ const dScores = []
89
+ for (let t = 0; t < dWeights.length; t++) {
90
+ dScores[t] = this.softmaxBack(this.weights[t], dWeights[t])
91
+ }
92
+ const dQ = this.q.map(q => new Float32Array(q.length));
93
+ const dK = this.k.map(k => new Float32Array(k.length));
94
+ for (let a = 0; a < this.q.length; a++) {
95
+ for (let j = 0; j < this.k.length; j++) {
96
+ for (let r = 0; r < this.q[a].length; r++) {
97
+ dQ[a][r] += dScores[a][j] * this.k[j][r] / this.score;
98
+ dK[j][r] += dScores[a][j] * this.q[a][r] / this.score;
99
+ }
100
+ }
101
+ }
102
+ const dInput = this.q.map(() => new Float32Array(this.q[0].length))
103
+ for (let a = 0; a < this.q.length; a++) {
104
+ const dq = this.query.backward(dQ[a], learningRate, a)
105
+ const dk = this.key.backward(dK[a], learningRate, a)
106
+ const dv = this.value.backward(dV[a], learningRate, a)
107
+ for (let b = 0; b < dq.length; b++) {
108
+ dInput[a][b] = dq[b] + dk[b] + dv[b]
109
+ }
110
+ }
111
+ return dInput
112
+ }
113
+ Save() {
114
+ this.query.Save()
115
+ this.key.Save()
116
+ this.value.Save()
117
+ }
118
+ }