@mineproness/tensorloop 2.1.55 → 2.1.56

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 (51) hide show
  1. package/index.js +14 -20
  2. package/package.json +5 -2
  3. package/readme.md +907 -72
  4. package/src/Embedding/index.d.ts +5 -5
  5. package/src/Embedding/index.js +118 -33
  6. package/src/FFN/index.d.ts +5 -5
  7. package/src/FFN/index.js +34 -39
  8. package/src/Linear/index.d.ts +7 -8
  9. package/src/Linear/index.js +173 -49
  10. package/src/OperationManager.js +96 -0
  11. package/src/Relu/index.d.ts +5 -0
  12. package/src/Relu/index.js +103 -0
  13. package/src/SelfAttention/index.d.ts +7 -13
  14. package/src/SelfAttention/index.js +108 -55
  15. package/src/Softmax/index.d.ts +4 -3
  16. package/src/Softmax/index.js +192 -12
  17. package/src/Tokenizer/index.d.ts +1 -0
  18. package/src/Tokenizer/index.js +92 -7
  19. package/src/TransformerBlock/index.d.ts +6 -7
  20. package/src/TransformerBlock/index.js +24 -23
  21. package/src/getVec.js +28 -0
  22. package/src/shaders/CalculateAcc.wgsl +50 -0
  23. package/src/shaders/CalculateLoss.wgsl +35 -0
  24. package/src/shaders/ComputeDInput.wgsl +32 -0
  25. package/src/shaders/EB.wgsl +31 -0
  26. package/src/shaders/EF.wgsl +25 -0
  27. package/src/shaders/LB.wgsl +57 -0
  28. package/src/shaders/LF.wgsl +44 -0
  29. package/src/shaders/RB.wgsl +37 -0
  30. package/src/shaders/RF.wgsl +33 -0
  31. package/src/shaders/ReductionFunction.wgsl +28 -0
  32. package/src/shaders/SB.wgsl +36 -0
  33. package/src/shaders/SF.wgsl +65 -0
  34. package/src/shaders/SoftmaxBackward.wgsl +31 -0
  35. package/src/shaders/attentionShader/CompueFinalForwardOutput.wgsl +29 -0
  36. package/src/shaders/attentionShader/ComputeDA.wgsl +30 -0
  37. package/src/shaders/attentionShader/ComputeDV.wgsl +37 -0
  38. package/src/shaders/attentionShader/ComputeK.wgsl +30 -0
  39. package/src/shaders/attentionShader/ComputedQ.wgsl +31 -0
  40. package/src/shaders/attentionShader/attentionSocres.wgsl +40 -0
  41. package/src/shaders/attentionShader/sumGradient.wgsl +24 -0
  42. package/src/GELU/index.d.ts +0 -6
  43. package/src/GELU/index.js +0 -33
  44. package/src/GetConfigs.js +0 -35
  45. package/src/Model/index.d.ts +0 -10
  46. package/src/Model/index.js +0 -88
  47. package/src/PositionEmbedding/index.d.ts +0 -11
  48. package/src/PositionEmbedding/index.js +0 -49
  49. package/src/ReLU/index.d.ts +0 -5
  50. package/src/ReLU/index.js +0 -17
  51. package/src/gpiInit.js +0 -764
package/src/gpiInit.js DELETED
@@ -1,764 +0,0 @@
1
- import { GPU } from 'gpu.js'
2
-
3
- const gpu = new GPU({ mode: "gpu" })
4
- if (gpu.mode == "cpu") {
5
- throw new Error("The tensorloop didn't have working GPU access.")
6
- }
7
-
8
- // ==========================
9
- // Init all Things
10
- // ==========================
11
-
12
- const maxTexture = GetMaxTexture()
13
-
14
- // ===========================
15
- // UTILS FUNCITON
16
- // ===========================
17
- function GetMaxTexture() {
18
- const dummyKernel = gpu.createKernel(function () {
19
- return 1 + 1
20
- }).setOutput([1])
21
- dummyKernel()
22
- const gl = dummyKernel.context;
23
- return gl.getParameter(gl.MAX_TEXTURE_SIZE)
24
- }
25
-
26
- export function spilt2DArray(arr) {
27
- const result = []
28
- for (let a = 0; a < arr.length; a += maxTexture) {
29
- result.push(arr.slice(a, a + maxTexture))
30
- }
31
- return result
32
- }
33
- function split2DByColumns(matrix, chunkSize = maxTexture) {
34
- const chunks = [];
35
- for (let start = 0; start < matrix[0].length; start += chunkSize) {
36
- const end = Math.min(start + chunkSize, matrix[0].length);
37
- const chunk = matrix.map(row =>
38
- row.slice(start, end)
39
- );
40
- chunks.push(chunk);
41
- }
42
- return chunks;
43
- }
44
- // =======================
45
- // Init all Classes
46
- // =======================
47
-
48
-
49
- export class GPULinear {
50
- cacheLF = [];
51
- cacheLInputGra = []
52
- cacheLWeigths = []
53
- cacheLBias = []
54
- Weights = [];
55
- Bias = [];
56
- contextSize;
57
- embeddingSize;
58
- outputSize;
59
- constructor(weights, bias, contextSize) {
60
-
61
- this.contextSize = contextSize;
62
- this.embeddingSize = weights[0].length;
63
- this.outputSize = weights.length
64
- const splitW = spilt2DArray(weights)
65
- const splitB = spilt2DArray(bias)
66
- process.stdout.write(`\r[DEBUG] Saving Weights in VRAM${".".repeat(Math.floor(Math.random() * 4))}`)
67
- for (let i = 0; i < splitW.length; i++) {
68
- const biasVram = gpu.createKernel(function (x) {
69
- return x[this.thread.x]
70
- }, {
71
- output: [splitW[i].length],
72
- immutable: true,
73
- pipeline: true
74
- })
75
- const weightVram = gpu.createKernel(function (x) {
76
- return x[this.thread.y][this.thread.x]
77
- }, {
78
- output: [this.embeddingSize, splitW[i].length],
79
- immutable: true,
80
- pipeline: true
81
- })
82
- this.Weights[i] = weightVram(splitW[i]);
83
- this.Bias[i] = biasVram(splitB[i]);
84
- this.cacheLF[i] = gpu.createKernel(function (weights, bias, x) {
85
- let sum = bias[this.thread.x]
86
- for (let i = 0; i < this.constants.inputSize; i++) {
87
- sum += weights[this.thread.x][i] * x[this.thread.y][i]
88
- }
89
- return sum;
90
- }).setOutput([splitW[i].length, contextSize]).setConstants({ inputSize: this.embeddingSize })
91
- this.cacheLWeigths[i] = gpu.createKernel(function (weights, learningRate, out, input) {
92
- let sum = 0;
93
- for (let a = 0; a < this.constants.contextSize; a++) {
94
- sum += out[a][this.thread.y] * input[a][this.thread.x]
95
- }
96
- let grad = Math.max(-1.0, Math.min(1.0, sum))
97
- return weights[this.thread.y][this.thread.x] - learningRate * grad
98
-
99
- }, {
100
- constants: {
101
- contextSize
102
- },
103
- output: [this.embeddingSize, splitW[i].length],
104
- pipeline: true,
105
- immutable: true
106
- })
107
- this.cacheLBias[i] = gpu.createKernel(function (bias, learningRate, out) {
108
- let sum = 0;
109
- for (let a = 0; a < this.constants.contextSize; a++) {
110
- sum += out[a][this.thread.x]
111
- }
112
- let grad = Math.max(-1.0, Math.min(1.0, sum))
113
- return bias[this.thread.x] - learningRate * grad
114
-
115
- }, {
116
- constants: {
117
- contextSize
118
- },
119
- output: [splitW[i].length],
120
- pipeline: true,
121
- immutable: true
122
- })
123
- this.cacheLInputGra[i] = gpu.createKernel(function (weights, out) {
124
- let sum = 0;
125
- for (let a = 0; a < this.constants.outputSizes; a++) {
126
- sum += out[this.thread.y][a] * weights[a][this.thread.x]
127
- }
128
- return Math.max(-1.0, Math.min(1.0, sum))
129
-
130
- }, {
131
- output: [this.embeddingSize, contextSize],
132
- constants: {
133
- outputSizes: splitW[i].length
134
- }
135
- })
136
- process.stdout.write(
137
- `\r[DEBUG] Weigths are Saved in VRAM!`
138
- );
139
- }
140
- }
141
- forward(input) {
142
- const result = Array.from({ length: this.contextSize }, () => new Float32Array(this.outputSize))
143
- let offset = 0;
144
- for (let i = 0; i < this.cacheLF.length; i++) {
145
- const out = this.cacheLF[i](this.Weights[i], this.Bias[i], input)
146
- for (let a = 0; a < this.contextSize; a++) {
147
- result[a].set(out[a], offset)
148
- }
149
- offset += out[0].length
150
- }
151
- return result
152
- }
153
- Save() {
154
- const weights = []
155
- const bias = []
156
- for (let a = 0; a < this.Weights.length; a++) {
157
- const chunkB = this.Bias[a]
158
- const chunkW = this.Weights[a]
159
- if (chunkB.toArray) {
160
- bias.push(...chunkB.toArray())
161
- weights.push(...chunkW.toArray())
162
- } else {
163
- bias.push(...chunkB)
164
- weights.push(...chunkW)
165
- }
166
- }
167
- return { weights, bias: new Float32Array(bias) }
168
- }
169
- backward(outGradient, input, learningRate) {
170
- const splitOut = split2DByColumns(outGradient)
171
- const result = Array.from({ length: this.contextSize }, () => new Float32Array(this.embeddingSize))
172
- for (let i = 0; i < splitOut.length; i++) {
173
- const oldW = this.Weights[i]
174
- const oldB = this.Bias[i]
175
- const out = this.cacheLInputGra[i](this.Weights[i], splitOut[i])
176
- this.Weights[i] = this.cacheLWeigths[i](this.Weights[i], learningRate, splitOut[i], input)
177
- this.Bias[i] = this.cacheLBias[i](this.Bias[i], learningRate, splitOut[i])
178
- for (let a = 0; a < this.contextSize; a++) {
179
- for (let g = 0; g < this.embeddingSize; g++) {
180
- result[a][g] += out[a][g]
181
- }
182
- }
183
- if (oldW.delete) {
184
- oldW.delete()
185
- oldB.delete()
186
- }
187
- }
188
- return result
189
- }
190
- }
191
-
192
-
193
- export class GPUSoftmax {
194
- cacheSumCalculate;
195
- cacheMaxCache;
196
- cacheSF = [];
197
- cacheSB = []
198
- contextSize;
199
- avgLoss;
200
- constructor(logits, contextSize) {
201
- this.contextSize = contextSize;
202
- this.avgLoss = gpu.createKernel(function (probs, target) {
203
- let sum = 0;
204
- for (let i = 0; i < this.constants.contextSize; i++) {
205
- sum += -Math.log(probs[i][target[i]] + 1e-15)
206
- }
207
- return sum / this.constants.contextSize
208
- }, {
209
- output: [1],
210
- constants: { contextSize }
211
- })
212
- this.cacheSumCalculate = gpu.createKernel(function (maxLogits, logits) {
213
- const maxLogit = maxLogits[this.thread.x]
214
- let sum = 0;
215
- for (let i = 0; i < this.constants.logitSize; i++) {
216
- sum += Math.exp(logits[this.thread.x][i] - maxLogit)
217
- }
218
- return sum
219
- }, {
220
- output: [contextSize],
221
- constants: { logitSize: logits[0].length },
222
- immutable: true,
223
- pipeline: true
224
- })
225
- this.cacheMaxCache = gpu.createKernel(function (logits) {
226
- let maxLogit = logits[this.thread.x][0]
227
- for (let i = 0; i < this.constants.logitSize; i++) {
228
- if (logits[this.thread.x][i] > maxLogit) {
229
- maxLogit = logits[this.thread.x][i]
230
- }
231
- }
232
- return maxLogit
233
- }, {
234
- output: [contextSize],
235
- constants: { logitSize: logits[0].length },
236
- immutable: true,
237
- pipeline: true
238
- })
239
- const splited2d = split2DByColumns(logits)
240
- let offset = 0;
241
- for (let a = 0; a < splited2d.length; a++) {
242
- this.cacheSF[a] = gpu.createKernel(function (logits, sum, maxLogit) {
243
- return Math.exp(logits[this.thread.y][this.thread.x] - maxLogit[this.thread.y]) / sum[this.thread.y]
244
- }, {
245
- output: [splited2d[a][0].length, contextSize]
246
- })
247
- this.cacheSB[a] = gpu.createKernel(function (logits, targets) {
248
- let logit = logits[this.thread.y][this.thread.x]
249
- let globalIndex = this.constants.offset + this.thread.x
250
- return globalIndex == targets[this.thread.y] ? logit - 1.0 : logit
251
- }, {
252
- output: [splited2d[a][0].length, contextSize],
253
- constants: { offset: offset }
254
- })
255
- offset += splited2d[a][0].length
256
- }
257
- }
258
- forward(logits) {
259
- const maxLogits = this.cacheMaxCache(logits)
260
- const sumes = this.cacheSumCalculate(maxLogits, logits)
261
- const splitedLogits = split2DByColumns(logits)
262
- const result = Array.from({ length: this.contextSize }, () => new Float32Array(logits[0].length))
263
- let offset = 0
264
- for (let i = 0; i < splitedLogits.length; i++) {
265
- const out = this.cacheSF[i](splitedLogits[i], sumes, maxLogits)
266
- for (let a = 0; a < this.contextSize; a++) {
267
- result[a].set(out[a], offset)
268
- }
269
- offset += out[0].length
270
- }
271
- maxLogits.delete()
272
- sumes.delete()
273
- return result
274
- }
275
- backward(probs, target) {
276
- const splitedProbs = split2DByColumns(probs)
277
- const result = Array.from({ length: this.contextSize }, () => new Float32Array(probs[0].length))
278
- let offset = 0;
279
- for (let i = 0; i < this.cacheSB.length; i++) {
280
- const out = this.cacheSB[i](splitedProbs[i], target)
281
- for (let a = 0; a < this.contextSize; a++) {
282
- result[a].set(out[a], offset)
283
- }
284
- offset += out[0].length
285
- }
286
- return result
287
- }
288
- crossEntropy(probs, target) {
289
- const loss = this.avgLoss(probs, target)
290
- return loss
291
- }
292
-
293
- }
294
-
295
-
296
- export class GPUHiddenLayer {
297
- cacheHF = [];
298
- cacheHB = []
299
- contextSize = 0;
300
- input = [];
301
- initKernel(probs, contextSize) {
302
- const splitL = split2DByColumns(probs)
303
- this.contextSize = contextSize;
304
- for (let a = 0; a < splitL.length; a++) {
305
- this.cacheHF[a] = gpu.createKernel(function (xs) {
306
- const x = xs[this.thread.y][this.thread.x]
307
- return x > 0 ? x : x * 0.02
308
- }).setOutput([splitL[a].length, contextSize])
309
- this.cacheHB[a] = gpu.createKernel(function (outputGradient, input) {
310
- const grad = outputGradient[this.thread.y][this.thread.x]
311
- const x = input[this.thread.y][this.thread.x]
312
- return x > 0 ? grad : grad * 0.02
313
- }, {
314
- output: [splitL[a].length, contextSize]
315
- })
316
- }
317
- }
318
- forward(logits) {
319
- if (this.cacheHF.length == 0) {
320
- this.initKernel(logits, logits.length)
321
- }
322
- this.input = logits
323
- const split = split2DByColumns(logits)
324
- const result = Array.from({ length: this.contextSize }, () => new Float32Array(logits[0].length))
325
- let offset = 0;
326
- for (let a = 0; a < split.length; a++) {
327
- const out = this.cacheHF[a](split[a])
328
- for (let i = 0; i < this.contextSize; i++) {
329
- result[i].set(out[i], offset)
330
- }
331
- offset += out[0].length
332
- }
333
- return result
334
- }
335
- backward(outputGradient) {
336
- const splitOut = split2DByColumns(outputGradient)
337
- const inputSp = split2DByColumns(this.input)
338
- const result = Array.from({ length: this.contextSize }, () => new Float32Array(outputGradient[0].length))
339
- let offset = 0;
340
- for (let a = 0; a < splitOut.length; a++) {
341
- const out = this.cacheHB[a](splitOut[a], inputSp[a])
342
- for (let i = 0; i < this.contextSize; i++) {
343
- result[i].set(out[i], offset)
344
- }
345
- offset += out[0].length
346
- }
347
- return result
348
- }
349
- ClearInputCache() {
350
- this.input = []
351
- }
352
- }
353
- export class GPUEmbedding {
354
- vocabSize = 0;
355
- embeddingSize = 0;
356
- contextSize = 0;
357
- chunkStarts = [];
358
- chunkEnds = [];
359
- vectors = [];
360
-
361
- lookupKernels = [];
362
- cacheEB = [];
363
-
364
- indexes = [];
365
- positions = [];
366
-
367
- constructor(vectors, vocabSize, embeddingSize, contextSize) {
368
- this.embeddingSize = embeddingSize;
369
- this.contextSize = contextSize;
370
- this.vocabSize = vocabSize;
371
-
372
- const splitedVectors = spilt2DArray(vectors);
373
- let start = 0;
374
- process.stdout.write(
375
- `\r[DEBUG] Saving Vectors in VRAM${".".repeat(Math.floor(Math.random() * 4))}`
376
- );
377
- for (let a = 0; a < splitedVectors.length; a++) {
378
-
379
-
380
- const length = splitedVectors[a].length;
381
-
382
- this.chunkStarts[a] = start;
383
- this.chunkEnds[a] = start + length;
384
-
385
- const vectorsK = gpu.createKernel(function (x) {
386
- return x[this.thread.x][this.thread.y];
387
- }, {
388
- output: [length, embeddingSize],
389
- pipeline: true,
390
- immutable: true
391
- });
392
-
393
- this.vectors[a] = vectorsK(splitedVectors[a]);
394
- vectorsK.destroy();
395
-
396
- this.cacheEB[a] = gpu.createKernel(function (vectors, indexes, positions, outGradient, learningRate) {
397
- const tokenIndex = this.thread.x;
398
- const dim = this.thread.y;
399
- let gradient = 0;
400
-
401
- for (let p = 0; p < this.constants.contextSize; p++) {
402
- const index = indexes[p];
403
- const pos = positions[p];
404
-
405
- if (index >= 0 && index == tokenIndex && pos >= 0) {
406
- gradient += outGradient[pos][dim];
407
- }
408
- }
409
-
410
- return vectors[tokenIndex][dim] - learningRate * gradient;
411
- }, {
412
- output: [length, embeddingSize],
413
- immutable: true,
414
- pipeline: true,
415
- constants: {
416
- contextSize: this.contextSize
417
- }
418
- });
419
-
420
- start += length;
421
-
422
- }
423
- process.stdout.write(
424
- `\n[DEBUG] Vectors are Saved in VRAM!`
425
- );
426
-
427
- process.stdout.write("\n");
428
- }
429
-
430
- getLookupKernel(count) {
431
- if (!this.lookupKernels[count]) {
432
- this.lookupKernels[count] = gpu.createKernel(function (vectors, indexes) {
433
- const dim = this.thread.x;
434
- const pos = this.thread.y;
435
- const index = Math.floor(indexes[pos]);
436
-
437
- return vectors[index][dim];
438
- }, {
439
- output: [
440
- this.embeddingSize,
441
- count
442
- ]
443
- });
444
- }
445
-
446
- return this.lookupKernels[count];
447
- }
448
-
449
- forward(tokens) {
450
- const result = Array.from(
451
- { length: this.contextSize },
452
- () => new Float32Array(this.embeddingSize)
453
- );
454
-
455
- for (let i = 0; i < this.vectors.length; i++) {
456
-
457
- const start = this.chunkStarts[i];
458
- const end = this.chunkEnds[i];
459
-
460
- const indexArray = new Float32Array(this.contextSize);
461
- const positionArray = new Int32Array(this.contextSize);
462
-
463
- for (let p = 0; p < this.contextSize; p++) {
464
- indexArray[p] = -1;
465
- positionArray[p] = -1;
466
- }
467
-
468
- let count = 0;
469
-
470
- for (let pos = 0; pos < tokens.length && count < this.contextSize; pos++) {
471
- const token = tokens[pos];
472
- if (token >= start && token < end) {
473
- indexArray[count] = token - start;
474
- positionArray[count] = pos;
475
- count++;
476
- }
477
- }
478
- this.indexes[i] = indexArray;
479
- this.positions[i] = positionArray;
480
- if (count === 0) {
481
- continue;
482
- }
483
- const compactIndexes = indexArray.subarray(0, count);
484
- const lookup = this.getLookupKernel(count);
485
- const out = lookup(
486
- this.vectors[i],
487
- compactIndexes
488
- );
489
-
490
- for (let j = 0; j < count; j++) {
491
- const originalPosition = positionArray[j];
492
- for (let dim = 0; dim < this.embeddingSize; dim++) {
493
- result[originalPosition][dim] = out[j][dim];
494
- }
495
- }
496
- }
497
- return result;
498
- }
499
-
500
- backward(outGradient, learningRate) {
501
- for (let a = 0; a < this.vectors.length; a++) {
502
- if (!this.indexes[a]) {
503
- continue;
504
- }
505
-
506
- let hasToken = false;
507
-
508
- for (let p = 0; p < this.contextSize; p++) {
509
- if (this.indexes[a][p] >= 0) {
510
- hasToken = true;
511
- break;
512
- }
513
- }
514
-
515
- if (!hasToken) {
516
- continue;
517
- }
518
-
519
- const oldVec = this.vectors[a];
520
-
521
- this.vectors[a] = this.cacheEB[a](
522
- oldVec,
523
- this.indexes[a],
524
- this.positions[a],
525
- outGradient,
526
- learningRate
527
- );
528
-
529
- if (oldVec && oldVec.delete) {
530
- oldVec.delete();
531
- }
532
- }
533
- }
534
-
535
- destroy() {
536
- for (const vector of this.vectors) {
537
- if (vector && vector.delete) {
538
- vector.delete();
539
- }
540
- }
541
-
542
- for (const kernel of this.lookupKernels) {
543
- if (kernel) {
544
- kernel.destroy();
545
- }
546
- }
547
-
548
- for (const kernel of this.cacheEB) {
549
- if (kernel) {
550
- kernel.destroy();
551
- }
552
- }
553
-
554
- this.vectors = [];
555
- this.lookupKernels = [];
556
- this.cacheEB = [];
557
- this.indexes = [];
558
- this.positions = [];
559
- this.chunkStarts = [];
560
- this.chunkEnds = [];
561
- }
562
- }
563
-
564
- export class GELUGPU {
565
- cacheGF;
566
- cacheGB;
567
- constructor(embeddingSize, contextSize) {
568
- this.cacheGF = gpu.createKernel(function (input) {
569
- const k = this.constants.kVal;
570
- const x = input[this.thread.y][this.thread.x]
571
- const u = k * (x + 0.044715 * x * x * x)
572
- return 0.5 * x * (1 + Math.tanh(u))
573
- }, {
574
- output: [embeddingSize, contextSize],
575
- constants: {
576
- kVal: Math.sqrt(2 / Math.PI)
577
- }
578
- })
579
- this.cacheGB = gpu.createKernel(function (input, gradient) {
580
- const x = input[this.thread.y][this.thread.x]
581
- const k = this.constants.kVal;
582
- const x3 = x * x * x;
583
- const u = k * (x + 0.044715 * x3)
584
- const t = Math.tanh(u)
585
- const sech2 = 1 - t * t
586
- const duDx = k * (1 + 3 * 0.044715 * x * x)
587
- const geluGrad =
588
- 0.5 * (1 + t) +
589
- 0.5 * x * sech2 * duDx;
590
- return gradient[this.thread.y][this.thread.x] * geluGrad
591
- }, {
592
- output: [embeddingSize, contextSize],
593
- constants: {
594
- kVal: Math.sqrt(2 / Math.PI)
595
- }
596
- })
597
- }
598
- forward(input) {
599
- return this.cacheGF(input)
600
- }
601
- backward(dOutput, input) {
602
- return this.cacheGB(input, dOutput)
603
- }
604
- }
605
-
606
- export class GPUAttention {
607
- attentionScores;
608
- attentionOutput;
609
- dWeightsKernel;
610
- dVKernel;
611
- softmaxBackKernel;
612
- dQKernel;
613
- dKKernel;
614
- constructor(embeddingSize, contextSize) {
615
- this.attentionScores = gpu.createKernel(function (q, k, scale) {
616
- const i = this.thread.y;
617
- const j = this.thread.x;
618
- if (j > i) {
619
- return -1e9;
620
- }
621
- let sum = 0;
622
- for (let d = 0; d < this.constants.D; d++) {
623
- sum += q[i][d] * k[j][d];
624
- }
625
- return sum / scale;
626
- }, {
627
- output: [contextSize, contextSize],
628
- constants: {
629
- D: embeddingSize
630
- }
631
- });
632
- this.attentionOutput = gpu.createKernel(function (weights, v) {
633
- const i = this.thread.y;
634
- const d = this.thread.x;
635
- let sum = 0;
636
- for (let j = 0; j < this.constants.CONTEXT; j++) {
637
- sum += weights[i][j] * v[j][d];
638
- }
639
- return sum;
640
- }, {
641
- output: [embeddingSize, contextSize],
642
- constants: {
643
- CONTEXT: contextSize
644
- },
645
- });
646
- this.dWeightsKernel = gpu.createKernel(function (dOutput, v) {
647
- const a = this.thread.y;
648
- const j = this.thread.x;
649
- let sum = 0;
650
- for (let r = 0; r < this.constants.D; r++) {
651
- sum += dOutput[a][r] * v[j][r];
652
- }
653
- return sum;
654
- }, {
655
- output: [contextSize, contextSize],
656
- pipeline: true,
657
- immutable: true,
658
- constants: {
659
- D: embeddingSize
660
- }
661
- });
662
- this.dVKernel = gpu.createKernel(function (dOutput, weights) {
663
- const j = this.thread.y;
664
- const r = this.thread.x;
665
- let sum = 0;
666
- for (let a = 0; a < this.constants.C; a++) {
667
- sum += weights[a][j] * dOutput[a][r];
668
- }
669
- return sum;
670
- }, {
671
- output: [embeddingSize, contextSize],
672
-
673
- constants: {
674
- C: contextSize
675
- }
676
- });
677
- this.softmaxBackKernel = gpu.createKernel(function (probs, dOut) {
678
- const a = this.thread.y;
679
- const i = this.thread.x;
680
- let dot = 0;
681
- for (let j = 0; j < this.constants.C; j++) {
682
- dot += probs[a][j] * dOut[a][j];
683
- }
684
- return probs[a][i] * (dOut[a][i] - dot);
685
- }, {
686
- output: [contextSize, contextSize],
687
- pipeline: true,
688
- immutable: true,
689
- constants: {
690
- C: contextSize
691
- }
692
- });
693
- this.dQKernel = gpu.createKernel(function (dScores, k, scale) {
694
- const a = this.thread.y;
695
- const r = this.thread.x;
696
- let sum = 0;
697
- for (let j = 0; j <= a; j++) {
698
- sum += dScores[a][j] * k[j][r];
699
- }
700
- return sum / scale;
701
- }, {
702
- output: [embeddingSize, contextSize],
703
-
704
- });
705
- this.dKKernel = gpu.createKernel(function (dScores, q, scale) {
706
- const j = this.thread.y;
707
- const r = this.thread.x;
708
- let sum = 0;
709
- for (let a = j; a < this.constants.C; a++) {
710
- sum += dScores[a][j] * q[a][r];
711
- }
712
- return sum / scale;
713
- }, {
714
- output: [embeddingSize, contextSize],
715
-
716
- constants: {
717
- C: contextSize
718
- }
719
- });
720
- }
721
- }
722
-
723
-
724
- export class GPUPosition {
725
- cachePF;
726
- cachePB;
727
- posVectors
728
- constructor(posVectors, embeddingSize, contextSize) {
729
- const vramKernel = gpu.createKernel(function (posVec) {
730
- return posVec[this.thread.y][this.thread.x]
731
- }, {
732
- output: [embeddingSize, contextSize],
733
- immutable: true,
734
- pipeline: true
735
- })
736
- this.posVectors = vramKernel(posVectors)
737
- this.cachePF = gpu.createKernel(function (posVectors, vectors) {
738
- return vectors[this.thread.y][this.thread.x] + posVectors[this.thread.y][this.thread.x]
739
- }, {
740
- output: [embeddingSize, contextSize],
741
-
742
- })
743
- this.cachePB = gpu.createKernel(function (outGradient, learingRate, oldVec) {
744
- return oldVec[this.thread.y][this.thread.x] - learingRate * outGradient[this.thread.y][this.thread.x]
745
- }, {
746
- output: [embeddingSize, contextSize],
747
- immutable: true,
748
- pipeline: true,
749
- })
750
- }
751
- forward(vectors) {
752
- return this.cachePF(this.posVectors, vectors)
753
- }
754
- backward(outGradient, learingRate) {
755
- const oldVec = this.posVectors;
756
- this.posVectors = this.cachePB(outGradient, learingRate, oldVec)
757
- oldVec.delete()
758
- }
759
- Save() {
760
- return this.posVectors.toArray()
761
- }
762
- }
763
-
764
-