-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathviz.js
2105 lines (1817 loc) · 62.1 KB
/
viz.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"use strict"
import * as THREE from 'three'
import * as util from './util.js'
//
// shader
//
const TEXTURE = new THREE.TextureLoader().load('./assets/ball.png')
export const MATERIAL = new THREE.ShaderMaterial({
uniforms: {
color: { value: new THREE.Color(0xffffff) },
pointTexture: { value: TEXTURE },
mag: { value: 1.0 },
},
vertexShader: `
uniform float mag;
attribute float pointSize;
attribute vec4 pointColor;
varying vec4 vColor;
void main() {
vColor = pointColor;
vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );
gl_PointSize = mag * pointSize / -mvPosition.z;
gl_Position = projectionMatrix * mvPosition;
}
`,
fragmentShader: `
uniform vec3 color;
uniform sampler2D pointTexture;
varying vec4 vColor;
void main() {
vec4 outColor = texture2D( pointTexture, gl_PointCoord );
if ( outColor.a < 0.5 ) discard;
gl_FragColor = outColor * vec4( color * vColor.xyz, 1.0 );
}`,
})
//
// initialization
//
// https://stackoverflow.com/questions/25582882/javascript-math-random-normal-distribution-gaussian-bell-curve
// Standard Normal variate using Box-Muller transform.
function gaussianRandom(mean = 0, stdev = 1) {
let u = 1 - Math.random() //Converting [0,1) to (0,1)
let v = Math.random()
let z = Math.sqrt(-2.0 * Math.log(u)) * Math.cos(2.0 * Math.PI * v)
// Transform to the desired mean and standard deviation:
return z * stdev + mean
}
// https://github.com/facebookresearch/shumai/blob/main/test/gradient.test.ts#L5
function sampleSphere(args) {
const u = sm.randn(args)
const d = sm.sum(u.mul(u)).sqrt()
return u.div(d)
}
export const INIT_FUNCS = {
rows: (i, j, h) => h > 1 ? i / (h - 1) : 0,
cols: (i, j, h, w) => w > 1 ? j / (w - 1) : 0,
'row major': (i, j, h, w) => h * w > 1 ? (i * w + j) / (h * w - 1) : 0,
'col major': (i, j, h, w) => h * w > 1 ? (j * h + i) / (h * w - 1) : 0,
'pt linear': (i, j, h, w) => (2 * Math.random() - 1) / Math.sqrt(w),
uniform: () => Math.random(),
gaussian: () => gaussianRandom(0.5, 0.5),
// sphere: (i, j, h, w) => sampleSphere([h, w]),
'tril mask': (i, j) => j <= i ? 1 : 0,
'triu mask': (i, j) => j >= i ? 1 : 0,
eye: (i, j) => +(i == j),
diff: (i, j) => i == j ? 1 : i == j + 1 ? -1 : 0,
}
export const INITS = Object.keys(INIT_FUNCS).concat(['url', 'expr'])
const USE_RANGE = ['rows', 'cols', 'row major', 'col major', 'uniform', 'gaussian']
const USE_DROPOUT = USE_RANGE.concat(['pt linear'])
export const useRange = name => USE_RANGE.indexOf(name) >= 0
export const useDropout = name => USE_DROPOUT.indexOf(name) >= 0
const DATA_CACHE = {}
function tryLoadData(data_url) {
if (DATA_CACHE[data_url]) {
return DATA_CACHE[data_url]
}
try {
console.log(`loading data from ${data_url}...`)
const url = new URL(data_url)
const req = new XMLHttpRequest()
req.open("GET", url, false)
req.send(null)
DATA_CACHE[url] = req.responseText.split(/\r?\n|\r/).map(l => l.split(',').map(s => +s))
console.log(`done loading data from ${data_url}`)
return DATA_CACHE[url]
} catch (e) {
console.log(`error loading data from URL '${data_url}' message '${e.message}`)
}
}
function tryURLInit(url) {
const data = tryLoadData(url)
if (data) {
return (i, j, h, w) => {
const row = data[i % data.length]
return row[j % row.length]
}
}
}
function tryEvalInitExpr(expr) {
try {
return eval?.(`(i, j, h, w) => { try { return (${expr}) } catch (e) { return 0 } }`)
} catch ({ name, message }) {
console.log(`error ${name} evaluating init expr '${expr}' message '${message}'`)
return () => 0
}
}
function getInitFunc(init_params) {
const { init, min, max, dropout, url, expr } = init_params
const f = INIT_FUNCS[init] ||
(init == 'url' && tryURLInit(url)) ||
(init == 'expr' && tryEvalInitExpr(expr))
if (!f) {
console.log(init == 'url' ?
`'can't load from URL '${url}'` :
`unrecognized initializer '${init}'`)
return () => 0
}
const scaled = useRange(init) && (min != 0 || max != 1) ?
(i, j, h, w) => min + Math.max(0, max - min) * f(i, j, h, w) :
f
const sparse = useDropout(init) && dropout > 0 ?
(i, j, h, w) => Math.random() > dropout ? scaled(i, j, h, w) : 0 :
scaled
return sparse
}
// pointwise funcs
const ERF_A1 = 0.254829592
const ERF_A2 = -0.284496736
const ERF_A3 = 1.421413741
const ERF_A4 = -1.453152027
const ERF_A5 = 1.061405429
const ERF_P = 0.3275911
function erf(x) {
const absx = Math.abs(x)
const t = 1.0 / (1.0 + ERF_P * absx)
const y = (((((ERF_A5 * t + ERF_A4) * t) + ERF_A3) * t + ERF_A2) * t + ERF_A1) * t
return Math.sign(x) * (1 - y * Math.exp(-absx * absx))
}
const SQRT2 = Math.sqrt(2)
const gelu = x => x * (1 + erf(x / SQRT2)) / 2
const sigmoid = x => 1 / (1 + Math.exp(-x))
const silu = x => x * sigmoid(x)
const relu = x => Math.max(0, x)
const pow2 = x => x ** 2
const POINTWISE = {
'relu': relu,
'gelu': gelu,
'sigmoid': sigmoid,
'silu': silu,
'tanh': Math.tanh,
'x**2': pow2,
}
// epilogs
// TODO the way epis are done is kind of messy rn
export const EPILOGS = [
'none',
'relu',
'gelu',
'sigmoid',
'silu',
'tanh',
'layernorm',
'softmax',
'softmax(x/sqrt(k))',
'softmax(tril(x/sqrt(k)))',
'softmax(tril(x/8))',
'x/k',
'x/sqrt(k)',
'x**2',
]
function softmax_(h, w, data, tril = false) {
const row_max = (ptr, w) => {
let x = 0
for (let j = 0; j < w; j++, ptr++) {
x = Math.max(x, data[ptr])
}
return x
}
const calc_denom = (ptr, w, rmax) => {
let d = 0
for (let j = 0; j < w; j++, ptr++) {
d += Math.exp(data[ptr] - rmax)
if (!isFinite(d)) {
// console.log(`HEY denom at data[${ptr}) = ${data[ptr]} becomes infinite`)
break
}
}
return d
}
for (let i = 0, ptr = 0; i < h; i++) {
const rmax = row_max(ptr, tril ? i + 1 : w)
const denom = calc_denom(ptr, tril ? i + 1 : w, rmax)
for (let j = 0; j < w; j++, ptr++) {
const x = tril && j > i ? 0 : Math.exp(data[ptr] - rmax) / denom
if (isNaN(x)) {
// console.log(`HEY Math.exp(data[${ptr}) = ${data[ptr]}]) / ${denom} is NaN`)
data[ptr] = 0
} else {
data[ptr] = x
}
}
}
}
const softmax_tril_ = (h, w, data) => softmax_(h, w, data, true)
function layernorm_(h, w, data) {
const mean = data.reduce((acc, x) => acc + x) / data.length
const mean2 = data.map(x => x ** 2).reduce((acc, x) => acc + x) / data.length
const variance = mean2 - mean ** 2
const denom = Math.sqrt(variance + 1e-5)
const n = h * w
for (let ptr = 0; ptr < n; ptr++) {
const x = data[ptr]
data[ptr] = (x - mean) / denom
}
}
const IN_PLACE_EPILOGS = {
'softmax': softmax_,
'softmax(x/sqrt(k))': softmax_,
'softmax(tril(x/sqrt(k)))': softmax_tril_,
'softmax(tril(x/8))': softmax_tril_, // TODO remove with epi cleanup
'layernorm': layernorm_,
}
const getInPlaceEpilog = name => IN_PLACE_EPILOGS[name]
function applyInPlaceEpilog_(data, h, w, epi) {
const epi_ = epi && getInPlaceEpilog(epi)
if (epi_) {
epi_(h, w, data)
}
}
//
// Array2D
//
function toRange(x, n) {
return x === undefined ? [0, n] : x.constructor === Array ? x : [x, x + 1]
}
function initArrayData_(data, h, w, init, epi = undefined, r = undefined, c = undefined) {
const [rstart, rend] = toRange(r, h)
const [cstart, cend] = toRange(c, w)
for (let i = rstart; i < rend; i++) {
for (let j = cstart, ptr = i * w + cstart; j < cend; j++, ptr++) {
data[ptr] = init(i, j, h, w)
}
}
applyInPlaceEpilog_(data, h, w, epi)
}
export class Array2D {
static fromInit(h, w, init, epi = undefined) {
const data = new Float32Array(h * w)
initArrayData_(data, h, w, init, epi)
return new Array2D(h, w, data)
}
constructor(h, w, data) {
this.h = h | 0
this.w = w | 0
this.data = data
}
reinit(f, epi = undefined, r = undefined, c = undefined) {
initArrayData_(this.data, this.h, this.w, f, epi, r, c)
}
numel() {
return this.h * this.w
}
get(i, j) {
return this.data[this.addr(i, j)]
}
slice(i = undefined, j = undefined) {
const [istart, iend] = toRange(i, this.h)
const [jstart, jend] = toRange(j, this.w)
const init = (i, j, h, w) => this.get(istart + i, jstart + j)
return Array2D.fromInit(iend - istart, jend - jstart, init)
}
addr(i, j) {
return i * this.w + j
}
absmax() {
const data = this.data
let absmax = 0
for (let i = 0; i < data.length; i++) {
const absx = Math.abs(data[i])
if (absmax < absx) {
absmax = absx
}
}
return absmax
}
absmin() {
const data = this.data
let absmin = Infinity
for (let i = 0; i < data.length; i++) {
const absx = Math.abs(data[i])
if (!isFinite(absmin) || absx < absmin) {
absmin = absx
}
}
return absmin
}
transpose() {
return Array2D.fromInit(this.w, this.h, (i, j) => this.get(j, i))
}
map(f) {
const data = new Float32Array(n)
for (let ptr = 0; ptr < n; ptr++) {
data[ptr] = f(this.data[ptr])
}
return new Array2D(this.h, this.w, data)
}
map2(f, a) {
if (a.h != this.h || a.w != this.w) {
throw Error(`shape error: this ${this.h} ${this.w} a ${a.h} ${a.w}`)
}
const n = this.h * this.w
const data = new Float32Array(n)
for (let ptr = 0; ptr < n; ptr++) {
data[ptr] = f(this.data[ptr], a.data[ptr])
}
return new Array2D(this.h, this.w, data)
}
add(a) {
return this.map2((x, y) => x + y, a)
}
}
//
//
//
function grid(info, dims, f) {
const infos = Array.from(dims).map(d => info[d])
const loop = (args, infos, f) => infos.length == 0 ?
f(...args) :
[...Array(infos[0].n).keys()].map(index => {
const { size, max } = infos[0]
const start = index * size
if (start < max) { // dead final block when size * n - max > size
const end = Math.min(start + size, max)
const extent = end - start
loop([...args, { index, start, end, extent }], infos.slice(1), f)
}
})
loop([], infos, f)
}
//
// Mat
//
let elem_scale = 1.25
let elem_size = elem_scale
function setElemScale(s) {
s ||= elem_scale
const old_elem_scale = elem_scale
elem_scale = s
elem_size *= elem_scale / old_elem_scale
}
export function setElemSize(scale, pixel_ratio) {
elem_size = elem_scale * Math.min(scale.x, scale.y) * pixel_ratio
}
const ZERO_COLOR = new THREE.Color(0, 0, 0)
const COLOR_TEMP = new THREE.Color()
function emptyPoints(h, w, info) {
const { i: { size: si }, j: { size: sj }, gap } = info
const n = h * w
const points = new Float32Array(n * 3)
for (let i = 0, ptr = 0; i < h; i++) {
const ioff = Math.floor(i / si)
for (let j = 0; j < w; j++) {
const joff = Math.floor(j / sj)
points[ptr++] = j + joff * gap
points[ptr++] = i + ioff * gap
points[ptr++] = 0
}
}
const geom = new THREE.BufferGeometry()
geom.setAttribute('position', new THREE.BufferAttribute(points, 3))
geom.setAttribute('pointSize', new THREE.Float32BufferAttribute(new Float32Array(n), 1))
geom.setAttribute('pointColor', new THREE.Float32BufferAttribute(new Float32Array(n * 3), 3))
return new THREE.Points(geom, MATERIAL)
}
export class Mat {
constructor(data, params, context, init_viz) {
this.params = params
this.context = context
this.data = data
this.H = data.h
this.W = data.w
this.absmax = this.data.absmax()
this.absmin = this.data.absmin()
if (init_viz) {
this.initViz()
}
}
getBlockInfo() {
const ni = Math.min(this.params.block['i blocks'], this.H)
const nj = Math.min(this.params.block['j blocks'], this.W)
return {
i: { n: ni, size: Math.ceil(this.H / ni), max: this.H },
j: { n: nj, size: Math.ceil(this.W / nj), max: this.W },
}
}
grid(dims, f) {
grid(this.getBlockInfo(), dims, f)
}
getDispH() {
const { i: { n, size } } = this.getBlockInfo()
return this.H + this.params.layout.gap * (Math.min(n, Math.ceil(this.H / size)) - 1)
}
getDispW() {
const { j: { n, size } } = this.getBlockInfo()
return this.W + this.params.layout.gap * (Math.min(n, Math.ceil(this.W / size)) - 1)
}
initViz() {
const gap = this.params.layout.gap
const info = { ...this.getBlockInfo(), gap }
this.points = emptyPoints(this.H, this.W, info)
this.points.name = `${this.params.name}.points`
this.setColorsAndSizes()
this.inner_group = new THREE.Group()
this.inner_group.name = `${this.params.name}.inner_group`
this.inner_group.add(this.points)
util.updateProps(this.inner_group.position, { x: gap, y: gap })
this.group = new THREE.Group()
this.group.name = `${this.params.name}.group`
this.group.add(this.inner_group)
this.setLegends()
}
setColorsAndSizes(r = undefined, c = undefined, get_size = undefined, get_color = undefined) {
const [rstart, rend] = toRange(r, this.H)
const [cstart, cend] = toRange(c, this.W)
get_size = get_size || this.sizeFromData.bind(this)
get_color = get_color || this.colorFromData.bind(this)
for (let i = rstart; i < rend; i++) {
for (let j = cstart; j < cend; j++) {
const x = this.getData(i, j)
this.setSize(i, j, get_size(x))
this.setColor(i, j, get_color(x))
this.checkLabel(i, j, x)
}
}
}
getExtent() {
const gap = this.params.layout.gap
return this._extents || (this._extents = {
x: this.getDispW() + 2 * gap - 1,
y: this.getDispH() + 2 * gap - 1,
z: 0,
})
}
getRangeInfo() {
const viz = this.params.viz
const use_absmin = viz.sensitivity == 'superlocal'
const local_absmax = this.absmax
const global_absmax = this.getGlobalAbsmax()
const absmax = (use_absmin || viz.sensitivity == 'local') ? local_absmax :
viz.sensitivity == 'global' ? global_absmax :
Math.sqrt(local_absmax * global_absmax) // semilocal
const absmin = use_absmin ? this.absmin : 0
const absdiff = absmax - absmin
if (absmin > absmax) {
console.log(`HEY absmin ${absmin} > absmax ${absmax}`)
}
return { viz, absmin, absmax, absdiff }
}
sizeFromData(x) {
if (x === undefined || isNaN(x)) {
console.log(`HEY sizeFromData(${x})`)
return 0
}
if (x === 0) {
return 0
}
const absx = Math.abs(x)
if (absx === Infinity) {
return elem_size
}
const { viz, absmin, absmax, absdiff } = this.getRangeInfo()
const vol = absmax <= absmin ? 0 : (absx - absmin) / absdiff
const zsize = viz['min size'] * elem_size
const size = zsize + (elem_size - zsize) * Math.sqrt(vol)
if (isNaN(size)) {
this.n_size_from_data_errors = (this.n_size_from_data_errors || 0) + 1
if (this.n_size_from_data_errors <= 100) {
console.log(`HEY x ${x} size ${size} absx ${absx} absmax ${absmax} absmin ${absmin} zsize ${zsize}`)
if (this.n_size_from_data_errors == 100) {
console.log(`HEY stopping logging after 100 errors`)
}
}
}
// boundary violations can happen in intermediates
return Math.min(size, elem_size)
}
colorFromData(x) {
if (x === undefined || isNaN(x)) {
console.log(`HEY colorFromData(${x})`)
return COLOR_TEMP.setHSL(0.0, 1.0, 1.0)
}
if (x === 0) {
return COLOR_TEMP.setHSL(0.0, 1.0, 0.0)
}
const { viz, absmin, absmax, absdiff } = this.getRangeInfo()
// boundary violations can happen in intermediates
const absx = Math.min(absmax, Math.max(absmin, Math.abs(x)))
if (absx === Infinity) {
return COLOR_TEMP.setHSL(1.0, 1.0, 1.0)
}
const hue_vol = absdiff <= 0 ? 0 : (x - Math.sign(x) * absmin) / absdiff
const gap = viz['hue gap'] * Math.sign(x)
const hue = (viz['zero hue'] + gap + (hue_vol * viz['hue spread'])) % 1
const min_light = Math.max(viz['min light'], 0.00001)
const max_light = Math.max(viz['max light'], min_light)
const range = max_light - min_light
const light_vol = absdiff <= 0 ? 0 : (absx - absmin)
const light = min_light + range * Math.sqrt(light_vol) / Math.sqrt(absdiff)
return COLOR_TEMP.setHSL(hue, 1.0, light)
}
getAbsmax() {
return this.absmax
}
getGlobalAbsmax() {
return this.params.getGlobalAbsmax ? this.params.getGlobalAbsmax() : this.absmax
}
reinit(init, epi = undefined, r = undefined, c = undefined) {
this.data.reinit(init, epi, r, c)
this.setColorsAndSizes(r, c)
}
getDataArray() {
return this.data.data
}
getData(i, j) {
if (i >= this.H || j >= this.W) {
console.log(`HEY i ${i} >= this.H ${this.H} || j ${j} >= this.W ${this.W}`)
return 0
}
return this.data.get(i, j)
}
getColor(i, j) {
const colors = this.points.geometry.attributes.pointColor.array
return COLOR_TEMP.fromArray(colors, this.data.addr(i, j) * 3)
}
setColor(i, j, c) {
const colors = this.points.geometry.attributes.pointColor.array
c.toArray(colors, this.data.addr(i, j) * 3)
this.points.geometry.attributes.pointColor.needsUpdate = true
}
getSize(i, j) {
return this.points.geometry.attributes.pointSize.array[this.data.addr(i, j)]
}
setSize(i, j, x) {
this.points.geometry.attributes.pointSize.array[this.data.addr(i, j)] = x
this.points.geometry.attributes.pointSize.needsUpdate = true
}
show(r = undefined, c = undefined) {
this.setColorsAndSizes(r, c)
}
hide(r = undefined, c = undefined) {
this.setColorsAndSizes(r, c, _ => 0, _ => ZERO_COLOR)
}
isHidden(i, j) {
return this.getColor(i, j).equals(ZERO_COLOR)
}
bumpColor(r = undefined, c = undefined) {
COLOR_TEMP.set(0x808080)
this.setColorsAndSizes(r, c, undefined, x => this.colorFromData(x).add(COLOR_TEMP))
}
isFacing() {
const c = this.group.localToWorld(new THREE.Vector3()).sub(this.context.camera.position).normalize()
const m = this.group.getWorldDirection(new THREE.Vector3())
return m.angleTo(c) < Math.PI / 2
}
isRightSideUp() {
const q = new THREE.Quaternion()
const p = new THREE.Vector3(0, -1, 0).applyQuaternion(this.group.getWorldQuaternion(q))
const c = new THREE.Vector3(0, 1, 0).applyQuaternion(this.context.camera.quaternion)
return p.angleTo(c) < Math.PI / 2
}
setRowGuides(light = undefined) {
const prev = this.params.deco['row guides']
light = util.syncProp(this.params.deco, 'row guides', light)
if (this.row_guide_groups && prev == light) {
return
}
if (this.row_guide_groups) {
this.row_guide_groups.forEach(g => {
this.inner_group.remove(g)
util.disposeAndClear(g)
})
}
this.row_guide_groups = []
if (light > 0.0) {
const gap = this.params.layout.gap
this.grid('ij', (
{ start: i, extent: ix, index: ii },
{ start: j, extent: jx, index: ji }
) => {
const g = util.rowGuide(ix, jx, light)
util.updateProps(g.position, { x: j + ji * gap, y: i + ii * gap })
this.inner_group.add(g)
this.row_guide_groups.push(g)
})
}
}
setFlowGuide(light) { }
setName(name) {
util.syncProp(this.params, 'name', name)
this.setLegends()
}
setLegends(size = undefined, shape = undefined) {
shape = util.syncProp(this.params.deco, 'shape', shape)
const facing = this.isFacing()
const rsu = this.isRightSideUp()
const [H, W] = [this.H, this.W]
const name = this.params.name // && this.params.name + (shape ? ` [${H}, ${W}]` : '')
if ((size === undefined || size == this.params.deco.legends) &&
this.legend_state &&
this.legend_state.facing == facing &&
this.legend_state.rsu == rsu &&
this.legend_state.name == name &&
this.legend_state.shape == shape &&
this.legend_state.H == H && this.legend_state.W == W) {
return
}
size = util.syncProp(this.params.deco, 'legends', size)
this.legend_state = { facing, rsu, name, shape, H, W }
const rmv = x => {
if (x) {
this.inner_group.remove(x)
util.disposeAndClear(x)
}
}
rmv(this.name_text)
rmv(this.hdim_text)
rmv(this.wdim_text)
if (size > 0) {
const color = 0xCCCCFF
const adjsiz = size * Math.cbrt(H * W) / 10
const xdir = facing ? 1 : -1
const ydir = rsu ? 1 : 0
const zdir = facing ? 1 : -1
if (name) {
const adjsiz2 = adjsiz * Math.min(1, 8 / name.length)
this.name_text = util.getText(name, color, adjsiz2)
this.name_text.name = `${name}.name`
this.name_text.geometry.rotateZ(Math.PI)
this.name_text.geometry.rotateY(facing ? Math.PI : 0)
const { h, w } = util.gbbhwd(this.name_text.geometry)
this.name_text.geometry.translate(
util.center(this.getDispW() - 1, xdir * w),
h + util.center(this.getDispH() - 1, h),
-zdir
)
this.inner_group.add(this.name_text)
}
if (shape && this.params.deco.shape_info) {
const htext = util.getText("X", color, adjsiz / 2.5)
const { h } = util.gbbhwd(htext.geometry)
util.disposeAndClear(htext)
const { i: { n: ni }, j: { n: nj } } = this.getBlockInfo()
{
const { h: { name, place } } = this.params.deco.shape_info
const hdim_str = `${name} = ${H}` + (ni == 1 ? '' : ` / ${ni}`)
this.hdim_text = util.getText(hdim_str, color, adjsiz / 2.5)
const { w } = util.gbbhwd(this.hdim_text.geometry)
this.hdim_text.geometry.rotateZ((place == facing ? 1 : -1) * Math.PI / 2)
this.hdim_text.geometry.rotateY(facing ? Math.PI : 0)
const xgap = 2 * h
this.hdim_text.geometry.translate(
place ? this.getDispW() - 1 + xgap : -xgap,
(place == facing ? 0 : w) + util.center(this.getDispH() - 1, w),
0
)
this.inner_group.add(this.hdim_text)
}
{
const { w: { name, place } } = this.params.deco.shape_info
const wdim_str = `${name} = ${W}` + (nj == 1 ? '' : ` / ${nj}`)
this.wdim_text = util.getText(wdim_str, color, adjsiz / 2.5)
const { w } = util.gbbhwd(this.wdim_text.geometry)
this.wdim_text.name = `${name}.wdim`
this.wdim_text.geometry.rotateZ(Math.PI)
this.wdim_text.geometry.rotateY(facing ? Math.PI : 0)
this.wdim_text.geometry.translate(
util.center(this.getDispW() - 1, (facing ? 1 : -1) * w),
place ? this.getDispH() - 1 + 3 * h : -2 * h,
0
)
this.inner_group.add(this.wdim_text)
}
}
}
}
checkLabel(i, j, x) {
if (this.label_cache) {
const addr = this.data.addr(i, j)
const label = this.label_cache[addr]
if (label != undefined && label.value != x) {
util.disposeAndClear(label)
this.label_cache[addr] = undefined
}
}
}
updateLabels(spotlight = undefined) {
spotlight = util.syncProp(this.params.deco, 'spotlight', spotlight)
if (spotlight == 0) {
if (this.label_group) {
this.inner_group.remove(this.label_group)
util.disposeAndClear(this.label_group)
this.label_group = undefined
}
} else {
if (!this.label_group) {
this.label_group = new THREE.Group()
this.label_group.name = `${this.params.name}.label_group`
this.inner_group.add(this.label_group)
this.label_cache = []
} else {
util.disposeAndClear(this.label_group)
}
const gap = this.params.layout.gap
const { i: { size: si }, j: { size: sj } } = this.getBlockInfo()
this.context.raycaster.params.Points.threshold = spotlight
const intersects = this.context.raycaster.intersectObject(this.points)
let count = 0
intersects.forEach(p => {
const index = p.index
const i = Math.floor(index / this.W)
const j = index % this.W
if (!this.isHidden(i, j)) {
const x = this.getData(i, j)
let label = this.label_cache[index]
const facing = this.isFacing()
const rsu = this.isRightSideUp()
if (!label || label.facing != facing || label.rsu != rsu) {
const fsiz = isNaN(x) || !isFinite(x) ? 0.12 :
0.16 - 0.008 * Math.log10(Math.floor(1 + Math.abs(x)))
label = util.getText(x.toFixed(5), 0xffffff, fsiz)
count += 1
// label.name = `${this.params.name}.label[${i}, ${j}]`
label.value = x
label.facing = facing
label.rsu = rsu
const zdir = facing ? 1 : -1
label.geometry.rotateX(zdir * Math.PI)
label.geometry.rotateY(facing ? 0 : Math.PI)
label.geometry.rotateZ(rsu ? 0 : Math.PI)
const { h, w } = util.gbbhwd(label.geometry)
const disp_i = i + Math.floor(i / si) * gap
const disp_j = j + Math.floor(j / sj) * gap
label.geometry.translate(
util.center(disp_j * 2, (rsu ? zdir : -zdir) * w),
h + util.center(disp_i * 2, h),
-zdir * 0.5
)
this.label_cache[index] = label
}
this.label_group.add(label)
}
})
}
}
}
//
// MatMul
//
export const SCHEMES = ['blocks', 'zigzag', 'wheel', 'custom']
export const POLARITIES = ['negative', 'positive']
export const LEFT_PLACEMENTS = ['left', 'right']
export const RIGHT_PLACEMENTS = ['top', 'bottom']
export const RESULT_PLACEMENTS = ['front', 'back']
function layoutDesc(layout) {
const pol = { 'positive': '+', 'negative': '-', }[layout.polarity]
const lfp = { 'left': 'L', 'right': 'R', }[layout['left placement']]
const rtp = { 'top': 'T', 'bottom': 'B', }[layout['right placement']]
const rsp = { 'front': 'F', 'back': 'B', }[layout['result placement']]
return `${pol}${lfp}${rtp}${rsp}`
}
export const SENSITIVITIES = ['global', 'semilocal', 'local', 'superlocal']
export const TOP_LEVEL_ANIM_ALGS = [
'none', 'dotprod (row major)', 'dotprod (col major)', 'axpy', 'vmprod', 'mvprod', 'vvprod',
]
export const ANIM_ALGS = TOP_LEVEL_ANIM_ALGS.concat('inherit')
export const FUSE_MODE = ['none', 'sync', 'async']
const ensureChildCounts = p => {
if (p.count === undefined) {
p.count = p.matmul === false ? 0 :
(1 + ensureChildCounts(p.left).count + ensureChildCounts(p.right).count)
// sloppy - this means root
if (p.matmul === undefined) {
const total = p.count
const setTotal = p => {
p.total = total
p.left && setTotal(p.left)
p.right && setTotal(p.right)
}
setTotal(p)
}
}
return p
}
export class MatMul {
constructor(params, context, init_viz = true) {
this.context = context
this.params = util.copyTree(params)
ensureChildCounts(this.params)
this.group = new THREE.Group()
this.group.name = `${this.params.name}.group`
const height = p => p.matmul ? height(p.left) : p.h
const width = p => p.matmul ? width(p.right) : p.w
this.H = height(params.left)
this.D = width(params.left)
this.W = width(params.right)
if (this.D != height(params.right)) {
console.log(`HEY left width ${this.D} != right height ${height(params.right)}`)
}
this.initLeft()
this.initRight()
this.initResult()
if (init_viz) {
this.initViz()
}
}
getDispH() {
const { i: { n, size } } = this.getBlockInfo()
return this.H + this.params.layout.gap * (Math.min(n, Math.ceil(this.H / size)) - 1)
}
getDispD() {
const { k: { n, size } } = this.getBlockInfo()
return this.D + this.params.layout.gap * (Math.min(n, Math.ceil(this.D / size)) - 1)
}
getDispW() {
const { j: { n, size } } = this.getBlockInfo()
return this.W + this.params.layout.gap * (Math.min(n, Math.ceil(this.W / size)) - 1)
}
disposeAll() {
util.disposeAndClear(this.group)
}
prepChildParams(base = undefined) {
base ||= util.copyTree(this.params)
return {
...base,
...(base != this.params ? {
anim: { ...this.params.anim, ...base.anim || {} },
block: { ...this.params.block, ...base.block || {} },
deco: { ...this.params.deco, ...base.deco || {} },
layout: { ...this.params.layout, ...base.layout || {} },
viz: { ...this.params.viz, ...base.viz || {} },
} : {}),
getGlobalAbsmax: this.getGlobalAbsmax.bind(this),
}
}
initLeft() {
const left_params = this.prepChildParams(this.params.left)
left_params.is_child = 'left'
left_params.block['i blocks'] = this.params.block['i blocks']
left_params.block['j blocks'] = this.params.block['k blocks']
if (left_params.matmul) {
this.left = new MatMul(left_params, this.context, false)
} else {
const { right, result, polarity } = this.getPlacementInfo()
left_params.deco.shape_info = {
h: { name: 'I', place: result == polarity },
w: { name: 'K', place: right },