@mineproness/tensorloop 1.3.2 → 1.3.3
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/package.json +1 -1
- package/src/SelfAttention/index.js +13 -5
package/package.json
CHANGED
|
@@ -25,16 +25,23 @@ export class SelfAttention {
|
|
|
25
25
|
this.q = vectors.map((e) => this.query.forward(e))
|
|
26
26
|
this.v = vectors.map((e) => this.value.forward(e))
|
|
27
27
|
this.k = vectors.map((e) => this.key.forward(e))
|
|
28
|
-
// console.log(this.q, this.k, this.v)
|
|
29
28
|
const attentionSocres = []
|
|
30
29
|
for (let i = 0; i < this.q.length; i++) {
|
|
31
|
-
attentionSocres[i] = new Float32Array(this.k.length)
|
|
32
|
-
|
|
30
|
+
attentionSocres[i] = new Float32Array(this.k.length);
|
|
31
|
+
|
|
32
|
+
for (let j = 0; j < this.k.length; j++) {
|
|
33
|
+
if (j > i) {
|
|
34
|
+
attentionSocres[i][j] = -1e9; // mask future
|
|
35
|
+
continue;
|
|
36
|
+
}
|
|
37
|
+
|
|
33
38
|
let dot = 0;
|
|
39
|
+
|
|
34
40
|
for (let d = 0; d < this.q[i].length; d++) {
|
|
35
|
-
dot += this.q[i][d] * this.k[
|
|
41
|
+
dot += this.q[i][d] * this.k[j][d];
|
|
36
42
|
}
|
|
37
|
-
|
|
43
|
+
|
|
44
|
+
attentionSocres[i][j] = dot / this.score;
|
|
38
45
|
}
|
|
39
46
|
}
|
|
40
47
|
const weights = attentionSocres.map((e) => this.softmax.forward(e))
|
|
@@ -93,6 +100,7 @@ export class SelfAttention {
|
|
|
93
100
|
const dK = this.k.map(k => new Float32Array(k.length));
|
|
94
101
|
for (let a = 0; a < this.q.length; a++) {
|
|
95
102
|
for (let j = 0; j < this.k.length; j++) {
|
|
103
|
+
if (j > a) continue;
|
|
96
104
|
for (let r = 0; r < this.q[a].length; r++) {
|
|
97
105
|
dQ[a][r] += dScores[a][j] * this.k[j][r] / this.score;
|
|
98
106
|
dK[j][r] += dScores[a][j] * this.q[a][r] / this.score;
|