Repository navigation
Expand file tree
/
Copy pathtensor-utils.js
More file actions
1531 lines (1373 loc) · 62.3 KB
/
Copy pathtensor-utils.js
File metadata and controls
1531 lines (1373 loc) · 62.3 KB
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
import * as tf from '@tensorflow/tfjs'
import { BWLabeler } from './bwlabels.js'
// DEBUG ONLY: set true to force the post-processing noise guard to trip on any
// run, so you can see the "segmentation produced noise" failure path in the UI
// without an actual garbage segmentation. Leave false for normal use.
const FORCE_SEGMENTATION_NOISE = false;
export async function cropAndGetCorner(tensor3d, mask_3d, userPadding) {
// Find bounding box
const [row_min, row_max, col_min, col_max, depth_min, depth_max] = await firstLastNonZero3D(mask_3d);
// Calculate dimensions
const height = row_max - row_min + 1;
const width = col_max - col_min + 1;
const depth = depth_max - depth_min + 1;
// Adjust starting corner based on padding, ensuring we don't exceed 256 or go negative
const adjustCorner = (min, max, size, pad) => {
const startPad = Math.min(min, pad); // how much we can pad towards start
const endPad = Math.min(255 - max, pad); // how much we can pad towards end
const newStart = Math.max(0, min - startPad);
const newEnd = Math.min(255, max + endPad);
return [newStart, newEnd];
};
const [safeRowStart, safeRowEnd] = adjustCorner(row_min, row_max, height, userPadding);
const [safeColStart, safeColEnd] = adjustCorner(col_min, col_max, width, userPadding);
const [safeDepthStart, safeDepthEnd] = adjustCorner(depth_min, depth_max, depth, userPadding);
// Extract cropped brain with safe bounds
let cropped = tensor3d.slice(
[safeRowStart, safeColStart, safeDepthStart],
[safeRowEnd - safeRowStart + 1, safeColEnd - safeColStart + 1, safeDepthEnd - safeDepthStart + 1]
);
// Ensure dimensions are even for stride-2 alignment (important for SpatialAE models)
// Use zero-padding at the END, matching run_inference.py logic
const shape = cropped.shape;
const padRow = shape[0] % 2;
const padCol = shape[1] % 2;
const padDepth = shape[2] % 2;
if (padRow || padCol || padDepth) {
cropped = cropped.pad([
[0, padRow],
[0, padCol],
[0, padDepth]
]);
console.log(`Padded to even dims: [${shape}] -> [${cropped.shape}]`);
} else {
console.log(`Crop dimensions (already even): [${shape}]`);
}
return { cropped, corner: [safeRowStart, safeColStart, safeDepthStart], padding: [padRow, padCol, padDepth] };
}
export async function restoreToOriginalSize(tensor3d, corner, targetShape, shift = [0, 0, 0]) {
const [row_min, col_min, depth_min] = corner;
const [targetHeight, targetWidth, targetDepth] = targetShape;
const [height, width, depth] = tensor3d.shape;
const [sRow, sCol, sDepth] = shift || [0, 0, 0];
const padRow = Math.max(0, row_min + sRow);
const padCol = Math.max(0, col_min + sCol);
const padDepth = Math.max(0, depth_min + sDepth);
const paddings = [
[padRow, Math.max(0, targetHeight - height - padRow)],
[padCol, Math.max(0, targetWidth - width - padCol)],
[padDepth, Math.max(0, targetDepth - depth - padDepth)]
];
const padded = tensor3d.pad(paddings);
// Ensure we enforce the target shape (truncate if padding exceeded dimensions)
if (padded.shape[0] > targetHeight || padded.shape[1] > targetWidth || padded.shape[2] > targetDepth) {
const sliced = padded.slice([0, 0, 0], [targetHeight, targetWidth, targetDepth]);
padded.dispose();
return sliced;
}
return padded;
}
export async function addZeroPaddingTo3dTensor(tensor3d, rowPadArr = [1, 1], colPadArr = [1, 1], depthPadArr = [1, 1]) {
if (tensor3d.rank !== 3) {
throw new Error('Tensor must be 3D');
}
const [height, width, depth] = tensor3d.shape;
const adjustPadding = (size, padding) => {
const totalPad = padding[0] + padding[1];
if (size + totalPad > 256) {
const scale = (256 - size) / totalPad;
return [Math.floor(padding[0] * scale), Math.floor(padding[1] * scale)];
}
return padding;
};
return tensor3d.pad([
adjustPadding(height, rowPadArr),
adjustPadding(width, colPadArr),
adjustPadding(depth, depthPadArr)
]);
}
// export async function addZeroPaddingTo3dTensor(tensor3d, rowPadArr = [1, 1], colPadArr = [1, 1], depthPadArr = [1, 1]) {
// if (tensor3d.rank !== 3) {
// throw new Error('Tensor must be 3D')
// }
// return tensor3d.pad([rowPadArr, colPadArr, depthPadArr])
// }
export async function applyMriThreshold(tensor, percentage) {
// Perform asynchronous operations outside of tf.tidy
const maxTensor = tensor.max()
const thresholdTensor = maxTensor.mul(percentage)
const threshold = await thresholdTensor.data() // Extracts the threshold value
// Dispose tensors not needed anymore
maxTensor.dispose()
thresholdTensor.dispose()
// Use tf.tidy for synchronous operations
return tf.tidy(() => {
const dataForProcessing = tensor.clone()
// Thresholding (assuming background has very low values compared to the head)
const mask = dataForProcessing.greater(threshold[0])
// -- const denoisedMriData = dataForProcessing.mul(mask)
// No need to manually dispose dataForProcessing and mask, as tf.tidy() will dispose them auto.
return mask
})
// -- return denoisedMriData
}
export async function binarizeVolumeDataTensor(volumeDataTensor) {
const alpha = 0
// element-wise: (x > 0 ? 1 : alpha * x ); e.g. Tenosr [0, 0.9, 0.8, -3] => Tensor [0, 1, 1, 0]
return volumeDataTensor.step(alpha)
}
function linearQuantileFromHistogram(histogram, count, quantile) {
const rank = (count - 1) * quantile
const lowerRank = Math.floor(rank)
const upperRank = Math.ceil(rank)
let cumulative = 0
let lowerValue = 0
let upperValue = 0
let lowerFound = false
for (let value = 0; value < histogram.length; value++) {
cumulative += histogram[value]
if (!lowerFound && cumulative > lowerRank) {
lowerValue = value
lowerFound = true
}
if (cumulative > upperRank) {
upperValue = value
break
}
}
return lowerValue + (upperValue - lowerValue) * (rank - lowerRank)
}
async function calculateQuantiles(tensor, lowerQuantile = 0.02, upperQuantile = 0.98) {
// Download once to CPU. This avoids tf.gather on a 16M-voxel tensor, which
// causes avoidable GPU memory pressure immediately before inference.
const flatTensor = tensor.flatten()
const totalSize = flatTensor.shape[0]
// Download tensor data to CPU (TypedArray, not JS Array - much faster)
const flatData = await flatTensor.data()
flatTensor.dispose()
// Brainchomp's bundled examples are uint8. For uint8-like data an exact
// histogram is both faster and more reproducible than the old random sample,
// and reproduces NumPy's default linearly interpolated quantile.
const histogram = new Uint32Array(256)
let isUint8 = true
for (let i = 0; i < totalSize; i++) {
const value = flatData[i]
if (!Number.isFinite(value)) {
throw new Error('Cannot percentile-normalize a volume containing NaN or Infinity')
}
if (value < 0 || value > 255 || value !== Math.trunc(value)) {
isUint8 = false
} else {
histogram[value]++
}
}
if (isUint8) {
return {
qmin: linearQuantileFromHistogram(histogram, totalSize, lowerQuantile),
qmax: linearQuantileFromHistogram(histogram, totalSize, upperQuantile)
}
}
// Uploaded float volumes can be much larger than is practical to sort in a
// browser. Use a deterministic, evenly spaced sample instead of Math.random
// so repeated runs and both browser backends receive the same scaling.
const sampleSize = Math.min(100000, totalSize)
const sample = new Float32Array(sampleSize)
const scale = sampleSize > 1 ? (totalSize - 1) / (sampleSize - 1) : 0
for (let i = 0; i < sampleSize; i++) {
const value = flatData[Math.round(i * scale)]
if (!Number.isFinite(value)) {
throw new Error('Cannot percentile-normalize a volume containing NaN or Infinity')
}
sample[i] = value
}
sample.sort()
const interpolate = (quantile) => {
const rank = (sampleSize - 1) * quantile
const lower = Math.floor(rank)
const upper = Math.ceil(rank)
return sample[lower] + (sample[upper] - sample[lower]) * (rank - lower)
}
const qminValue = interpolate(lowerQuantile)
const qmaxValue = interpolate(upperQuantile)
return { qmin: qminValue, qmax: qmaxValue }
}
export async function convByOutputChannelAndInputSlicing(input, filter, biases, stride, pad, dilationRate, sliceSize) {
const inChannels = input.shape[4]
const outChannels = filter.shape[4]
// Create an empty array to hold the output channels
let outputChannels = null
// Slice the input tensor and process one output channel at a time
for (let channel = 0; channel < outChannels; channel++) {
const numSlices = Math.ceil(inChannels / sliceSize)
let outputChannel = null
for (let i = 0; i < numSlices; i++) {
const startChannel = i * sliceSize
const endChannel = Math.min((i + 1) * sliceSize, inChannels)
// Only proceed if there are channels to process
if (startChannel < inChannels) {
const resultSlice = tf.tidy(() => {
const inputSlice = input.slice([0, 0, 0, 0, startChannel], [-1, -1, -1, -1, endChannel - startChannel])
const filterSlice = filter.slice([0, 0, 0, startChannel, channel], [-1, -1, -1, endChannel - startChannel, 1])
// Perform the convolution for the current slice and output channel
return tf.conv3d(inputSlice, filterSlice, stride, pad, 'NDHWC', dilationRate)
})
if (outputChannel === null) {
outputChannel = resultSlice
} else {
const updatedOutputChannel = outputChannel.add(resultSlice)
outputChannel.dispose()
resultSlice.dispose()
outputChannel = updatedOutputChannel
}
}
}
// --- Start of Fix ---
// This variable will hold the final result for this channel, after bias is (optionally) added.
let biasedOutputChannel;
// Check if the biases tensor was actually provided for this layer.
if (biases) {
// If biases exist, slice the correct one for this channel and add it.
const biasesSlice = biases.slice([channel], [1]);
biasedOutputChannel = outputChannel.add(biasesSlice);
outputChannel.dispose();
biasesSlice.dispose();
} else {
// If no biases exist, the result is simply the accumulated convolution output.
biasedOutputChannel = outputChannel;
}
// --- End of Fix ---
// Accumulate the channel to the output array
if (outputChannels == null) {
outputChannels = biasedOutputChannel
} else {
const updatedOutputChannels = await tf.concat([outputChannels, biasedOutputChannel], 4)
biasedOutputChannel.dispose()
outputChannels.dispose()
outputChannels = updatedOutputChannels
}
}
return outputChannels
}
/**
* Applies instance normalization to a single-channel 3D tensor.
* Normalizes the tensor over its depth, height, and width.
* @param {tf.Tensor} x A 5D tensor of shape [1, D, H, W, 1].
* @param {number} epsilon A small float added to variance to avoid dividing by zero.
* @returns {tf.Tensor} The normalized tensor.
*/
function instanceNorm(x, epsilon = 1e-5) {
return tf.tidy(() => {
// Axes [1, 2, 3] correspond to Depth, Height, Width.
const { mean, variance } = tf.moments(x, [1, 2, 3], true);
const invStd = tf.rsqrt(variance.add(epsilon));
return x.sub(mean).mul(invStd);
});
}
export async function gn_convByOutputChannelAndInputSlicing(input, filter, biases, stride, pad, dilationRate, sliceSize) {
// const finalResult = tf.tidy(() => {
const inChannels = input.shape[4];
const outChannels = filter.shape[4];
let outputChannels = null;
for (let channel = 0; channel < outChannels; channel++) {
// This section computes a single channel's convolution.
const numSlices = Math.ceil(inChannels / sliceSize);
let outputChannel = null;
for (let i = 0; i < numSlices; i++) {
const startChannel = i * sliceSize;
const endChannel = Math.min((i + 1) * sliceSize, inChannels);
if (startChannel < inChannels) {
const resultSlice = tf.tidy(() => {
const inputSlice = input.slice([0, 0, 0, 0, startChannel], [-1, -1, -1, -1, endChannel - startChannel]);
const filterSlice = filter.slice([0, 0, 0, startChannel, channel], [-1, -1, -1, endChannel - startChannel, 1]);
return tf.conv3d(inputSlice, filterSlice, stride, pad, 'NDHWC', dilationRate);
});
if (outputChannel === null) {
outputChannel = resultSlice;
} else {
const updatedOutputChannel = outputChannel.add(resultSlice);
outputChannel.dispose();
resultSlice.dispose();
outputChannel = updatedOutputChannel;
}
}
}
let biasedOutputChannel;
if (biases) {
const biasesSlice = biases.slice([channel], [1]);
biasedOutputChannel = outputChannel.add(biasesSlice);
outputChannel.dispose();
biasesSlice.dispose();
} else {
biasedOutputChannel = outputChannel;
}
// --- KEY CHANGE ---
// Apply instance normalization to the resulting channel.
// Apply normalization
const normalizedChannel = instanceNorm(biasedOutputChannel);
biasedOutputChannel.dispose();
// Incremental concatenation
if (outputChannels === null) {
outputChannels = normalizedChannel;
} else {
const updatedOutputChannels = await tf.concat([outputChannels, normalizedChannel], 4);
normalizedChannel.dispose();
outputChannels.dispose();
outputChannels = updatedOutputChannels;
}
}
return outputChannels;
}// );
// return finalResult;
// }
// ===========================================================================
// CHANNEL-LIST (sequential) convolution path
// ---------------------------------------------------------------------------
// The functions below carry a layer's activation as a JavaScript ARRAY of
// single-channel tensors ([1, D, H, W, 1] each) instead of one packed
// [1, D, H, W, C] tensor. For the large gridding-free MeshNet models the full
// multi-channel activation (~256x204x204x24) would be materialized by tfjs as
// an unpacked WebGL2 texture larger than the 8192 limit and throw. A single
// channel is only ~3257^2 packed, comfortably under the limit -- so as long as
// no tensor ever holds more than one channel, every texture fits.
//
// These replace the old convByOutputChannelAndInputSlicing / gn_ variants,
// whose final `tf.concat([...], 4)` rebuilt the oversized full tensor.
// ===========================================================================
/**
* Compute ONE output channel of a Conv3D as a single-channel [1, D, H, W, 1]
* tensor, reading inputs from a channel-list (array of single-channel tensors).
* Input channels are gathered in small groups of `sliceSize` so the only
* multi-channel tensor ever built is a tiny [1, D, H, W, sliceSize] temporary.
*
* @param {tf.Tensor[]} inputList Array of [1, D, H, W, 1] input channels.
* @param {tf.Tensor} filter Conv3D kernel [kD, kH, kW, inC, outC].
* @param {tf.Tensor|null} biases Bias vector [outC] or null.
* @param {number} channel Index of the output channel to compute.
* @returns {tf.Tensor} A kept [1, D, H, W, 1] tensor (caller disposes).
*/
function convOneOutputChannel(inputList, filter, biases, channel, stride, pad, dilationRate, sliceSize) {
const inChannels = inputList.length;
return tf.tidy(() => {
let acc = null;
const numSlices = Math.ceil(inChannels / sliceSize);
for (let i = 0; i < numSlices; i++) {
const start = i * sliceSize;
const end = Math.min((i + 1) * sliceSize, inChannels);
const group = end - start;
// Gather this small group of input channels. group===1 avoids a needless
// concat (and never materializes anything wider than `sliceSize`).
const inputSlice = group === 1
? inputList[start]
: tf.concat(inputList.slice(start, end), 4);
const filterSlice = filter.slice([0, 0, 0, start, channel], [-1, -1, -1, group, 1]);
const part = tf.conv3d(inputSlice, filterSlice, stride, pad, 'NDHWC', dilationRate);
acc = acc === null ? part : acc.add(part);
}
if (biases) {
acc = acc.add(biases.slice([channel], [1]));
}
return acc;
});
}
/**
* Channel-list Conv3D: returns an ARRAY of single-channel [1, D, H, W, 1]
* tensors (one per output channel) instead of a concatenated full tensor.
* Optionally applies per-channel normalization (the affine-GroupNorm export
* decomposes GroupNorm into per-channel instance-norm + a diagonal 1x1
* "affine_*" conv, so per-channel normalization here is mathematically exact).
* Uses the CENTERED-variance LayerNormInPlace -- the same normalization the
* dense WebGL path uses, which is required for fp16-texture stability (the
* one-pass E[x^2]-E[x]^2 form cancels catastrophically in fp16 and produces
* pure-noise segmentations).
*
* Caller owns the returned array and must dispose it (tf.dispose(list)).
*
* @param {tf.Tensor[]} inputList Array of [1, D, H, W, 1] input channels.
* @param {tf.Tensor} filter Conv3D kernel [kD, kH, kW, inC, outC].
* @param {tf.Tensor|null} biases Bias vector [outC] or null.
* @param {boolean} applyNorm Apply per-channel GroupNorm (instance norm) to each output channel.
* @returns {tf.Tensor[]} Array of `outC` single-channel tensors.
*/
export function convChannelList(inputList, filter, biases, stride, pad, dilationRate, sliceSize, applyNorm = false) {
const outChannels = filter.shape[4];
const outputList = [];
for (let c = 0; c < outChannels; c++) {
let ch = convOneOutputChannel(inputList, filter, biases, c, stride, pad, dilationRate, sliceSize);
if (applyNorm) {
const normed = LayerNormInPlace(ch); // centered-variance, fp16-safe, per-channel
ch.dispose();
ch = normed;
}
outputList.push(ch);
}
return outputList;
}
/**
* Channel-list transposed (strided up-sampling) Conv3D, for SpatialAE-style
* MeshNet variants (e.g. Tissue GWM / model_sae16ch3). Returns an ARRAY of
* single-channel [1, D', H', W', 1] tensors (one per output channel) without
* ever materializing a full multi-channel activation -- so the up-sampled
* 256^3 result stays under the WebGL2 8192 texture limit.
*
* The tfjs/Keras Conv3DTranspose kernel layout is [kD, kH, kW, outC, inC]
* (out/in swapped vs Conv3D). Each output channel is the sum over input
* channels of conv3dTranspose(inChannel, kernel[..., o, c]).
*
* @param {tf.Tensor[]} inputList Array of [1, D, H, W, 1] input channels.
* @param {tf.Tensor} filter Conv3DTranspose kernel [kD, kH, kW, outC, inC].
* @param {tf.Tensor|null} biases Bias vector [outC] or null.
* @param {number[]} outSpatialShape Output [D', H', W'] (from layer.computeOutputShape).
* @returns {tf.Tensor[]} Array of `outC` single-channel tensors.
*/
export function convTransposeChannelList(inputList, filter, biases, outSpatialShape, stride, pad) {
const outChannels = filter.shape[3];
const inChannels = filter.shape[4];
const outShape5d = [1, outSpatialShape[0], outSpatialShape[1], outSpatialShape[2], 1];
const outputList = [];
for (let o = 0; o < outChannels; o++) {
const ch = tf.tidy(() => {
let acc = null;
for (let c = 0; c < inChannels; c++) {
const kSlice = filter.slice([0, 0, 0, o, c], [-1, -1, -1, 1, 1]); // [kD,kH,kW,1,1]
const part = tf.conv3dTranspose(inputList[c], kSlice, outShape5d, stride, pad);
acc = acc === null ? part : acc.add(part);
}
if (biases) {
acc = acc.add(biases.slice([o], [1]));
}
return acc;
});
outputList.push(ch);
}
return outputList;
}
/**
* Final classifier + argmax over a channel-list input, without ever building
* the full [1, D, H, W, numClasses] logits tensor. Computes each class logit as
* a single-channel tensor and folds it into a running (max-logit, argmax-index)
* pair -- the same incremental-argmax trick as SequentialConvLayer, but reading
* from a channel-list instead of a packed tensor.
*
* @param {tf.Tensor[]} inputList Array of [1, D, H, W, 1] activations (backbone output).
* @param {tf.Tensor} weights Final Conv3D kernel [kD, kH, kW, inC, numClasses].
* @param {tf.Tensor|null} biases Bias vector [numClasses] or null.
* @param {function} [callbackUI] Optional progress callback (msg, frac).
* @returns {Promise<tf.Tensor>} Squeezed [D, H, W] argmax label volume (float32).
*/
export async function seqConvArgMaxChannelList(inputList, weights, biases, stride, pad, dilationRate, callbackUI, isWebWorker = true) {
const numClasses = weights.shape[4];
const sliceSize = 3;
// The running max/argmax are kept at RANK 3 ([D, H, W]). tf.where (select) on
// the WebGL backend only supports up to rank 4 -- Firefox throws "Where for
// rank 5 is not yet supported" on the [1, D, H, W, 1] form -- so we reshape
// each single-channel logit down to [D, H, W] before the compare/select.
let outB = null; // running max logit [D, H, W]
let outC = null; // running argmax idx [D, H, W]
let spatialShape = null;
for (let k = 0; k < numClasses; k++) {
const logit5d = convOneOutputChannel(inputList, weights, biases, k, stride, pad, dilationRate, sliceSize);
if (spatialShape === null) {
// [1, D, H, W, 1] -> [D, H, W]
spatialShape = [logit5d.shape[1], logit5d.shape[2], logit5d.shape[3]];
}
const logit = tf.tidy(() => logit5d.reshape(spatialShape));
logit5d.dispose();
if (outB === null) {
outB = logit;
outC = tf.zerosLike(logit);
} else {
const [newB, newC] = tf.tidy(() => {
const greater = tf.greater(logit, outB);
return [tf.where(greater, logit, outB), tf.where(greater, tf.fill(outC.shape, k), outC)];
});
outB.dispose();
outC.dispose();
logit.dispose();
outB = newB;
outC = newC;
}
if (callbackUI) callbackUI(`Final layer class ${k + 1}/${numClasses}`, (k + 1) / numClasses);
// Yield to the event loop periodically so the UI can update / avoid GPU
// watchdog timeouts on the long classifier loop (only on main thread).
if (!isWebWorker && (k % 8 === 0)) {
await new Promise(resolve => setTimeout(resolve, 0));
}
}
outB.dispose();
return outC; // already [D, H, W]
}
/**
* Split a packed [1, D, H, W, C] tensor into a channel-list of C single-channel
* [1, D, H, W, 1] tensors. For C===1 the input is returned as a one-element list
* WITHOUT copying (the caller then owns disposal via the list).
*
* @param {tf.Tensor} tensor Packed [1, D, H, W, C] tensor.
* @returns {tf.Tensor[]} Array of C single-channel tensors.
*/
export function splitToChannelList(tensor) {
const C = tensor.shape[4];
if (C === 1) return [tensor];
const list = [];
for (let c = 0; c < C; c++) {
list.push(tensor.slice([0, 0, 0, 0, c], [-1, -1, -1, -1, 1]));
}
return list;
}
/**
* Applies instance normalization to a tensor and disposes the input tensor
* to simulate an in-place operation, minimizing peak memory usage.
* Assumes input shape [1, D, H, W, C]. Normalization is per-channel.
*
* @param {tf.Tensor} x The input tensor to normalize.
* @param {number} [epsilon=1e-5] A small float added to variance to avoid division by zero.
* @returns {tf.Tensor} The new, normalized tensor.
*/
export function LayerNormInPlace(x, epsilon = 1e-5) {
// Per-channel z-score over the spatial axes (NDHWC: reduce D,H,W; keep N,C).
//
// The straightforward `tf.moments(x, [1,2,3])` is expensive on WebGL: because
// the channel axis is innermost and is KEPT, each of its two internal
// reductions (mean, then mean-of-squared-deviations) transposes the full
// ~256M-element volume, and it also materializes a full (x - mean) volume.
// That cost ~965 ms/layer x 13 layers in profiling.
//
// Here we transpose ONCE to channel-first, take both reductions over the now
// innermost (contiguous) spatial block -- so they need no further transpose --
// and compute variance in a single pass as E[x^2] - E[x]^2. The per-channel
// [C] stats then broadcast directly over the innermost axis of the original
// NDHWC tensor, so the final normalize needs no transpose either. Result is
// numerically equivalent (variance clamped >= 0 to absorb fp round-off).
// IMPORTANT: use the CENTERED two-pass variance (mean of (x-mean)^2), NOT the
// one-pass E[x^2]-E[x]^2. The one-pass form is mathematically identical but in
// fp16 textures it cancels catastrophically (E[x^2] ~ E[x]^2, both large), which
// produced pure-noise segmentations (~1.5M connected components instead of ~2.5k).
return tf.tidy(() => {
const rank = x.shape.length; // expected 5: [1, D, H, W, C]
const C = x.shape[rank - 1];
const N = x.shape[1] * x.shape[2] * x.shape[3]; // D * H * W
// One transpose to channel-first, then both reductions run over the now
// innermost (contiguous) spatial axis -- no further transpose. tf.moments
// would transpose the full volume twice (once per internal reduction).
const flatCN = x.transpose([0, 4, 1, 2, 3]).reshape([C, N]); // [C, N]
const mean = flatCN.mean(1); // E[x] [C]
const centered = flatCN.sub(mean.reshape([C, 1])); // x - mean [C, N]
const variance = centered.square().mean(1); // E[(x-mean)^2] [C]
const invStd = tf.rsqrt(tf.add(variance, epsilon)); // [C]
const meanB = mean.reshape([1, 1, 1, 1, C]);
const invStdB = invStd.reshape([1, 1, 1, 1, C]);
return x.sub(meanB).mul(invStdB);
});
}
export async function draw3dObjBoundingVolume(unstackOutVolumeTensor, opts, modelEntry, callbackImg) {
const allOutputSlices3DCC = []
// dataSync() using to flatten array. Takes around 1.5 s
for (let sliceTensorIdx = 0; sliceTensorIdx < unstackOutVolumeTensor.length; sliceTensorIdx++) {
allOutputSlices3DCC[sliceTensorIdx] = Array.from(unstackOutVolumeTensor[sliceTensorIdx].dataSync())
}
// Use this conversion to download output slices as nii file. Takes around 30 ms
// does not use `push` to avoid stack overflows. In future: consider .set() with typed arrays
const allOutputSlices3DCC1DimArray = new Array(allOutputSlices3DCC[0].length * allOutputSlices3DCC.length)
let index = 0
for (let sliceIdx = 0; sliceIdx < allOutputSlices3DCC.length; sliceIdx++) {
for (let i = 0; i < allOutputSlices3DCC[sliceIdx].length; i++) {
allOutputSlices3DCC1DimArray[index++] = allOutputSlices3DCC[sliceIdx][i]
}
}
console.log('Done with allOutputSlices3DCC1DimArray ')
const brainMaskTensor1d = await binarizeVolumeDataTensor(tf.tensor1d(allOutputSlices3DCC1DimArray))
const brainOut = Array.from(brainMaskTensor1d.dataSync())
callbackImg(brainOut, opts, modelEntry)
}
// return first and last non-zero voxel in row (dim = 0), column (1) or slice (2) dimension
async function firstLastNonZero(tensor3D, dim = 0) {
let mxs = []
if (dim === 0) {
mxs = await tensor3D.max(2).max(1).arraySync()
} else if (dim === 1) {
mxs = await tensor3D.max(2).max(0).arraySync()
} else {
mxs = await tensor3D.max(1).max(0).arraySync()
}
let mn = mxs.length
let mx = 0
for (let i = 0; i < mxs.length; i++) {
if (mxs[i] > 0) {
mn = i
break
}
}
for (let i = mxs.length - 1; i >= 0; i--) {
if (mxs[i] > 0) {
mx = i
break
}
}
return [mn, mx]
}
export async function firstLastNonZero3D(tensor3D) {
const [row_min, row_max] = await firstLastNonZero(tensor3D, 0)
const [col_min, col_max] = await firstLastNonZero(tensor3D, 1)
const [depth_min, depth_max] = await firstLastNonZero(tensor3D, 2)
console.log('row min and max :', row_min, row_max)
console.log('col min and max :', col_min, col_max)
console.log('depth min and max :', depth_min, depth_max)
return [row_min, row_max, col_min, col_max, depth_min, depth_max]
}
/*
//simpler function, but x4 slower
export async function firstLastNonZero3D(tensor3D) {
const coords = await tf.whereAsync(tensor3D)
const row_min = coords.min(0).arraySync()[0]
const row_max = coords.max(0).arraySync()[0]
const col_min = coords.min(0).arraySync()[1]
const col_max = coords.max(0).arraySync()[1]
const depth_min = coords.min(0).arraySync()[2]
const depth_max = coords.max(0).arraySync()[2]
coords.dispose()
return [row_min, row_max, col_min, col_max, depth_min, depth_max]
}
*/
export async function generateBrainMask(
unstackOutVolumeTensor,
num_of_slices,
slice_height,
slice_width,
modelEntry,
opts,
callbackUI,
callbackImg,
isFinalImage = true
) {
if (unstackOutVolumeTensor[0].dtype !== 'int32') {
callbackUI('', -1, 'generateBrainMask assumes int32')
}
if (modelEntry.preModelPostProcess) {
callbackUI('', -1, 'generateBrainMask assumes BWLabeler instead of preModelPostProcess')
}
const numSlices = unstackOutVolumeTensor.length
const numPixels2D = unstackOutVolumeTensor[0].size
const numVox3D = numSlices * numPixels2D
// preallocate to reduce heap usage
const brainOut = new Int32Array(numVox3D)
let offset = 0
for (let i = 0; i < numSlices; i++) {
brainOut.set(unstackOutVolumeTensor[i].dataSync(), offset)
offset += numPixels2D
}
for (let i = 0; i < numVox3D; i++) {
brainOut[i] = brainOut[i] !== 0 ? 1 : 0
}
if (isFinalImage || opts.showPhase1Output) {
// all done
callbackImg(brainOut, opts, modelEntry)
callbackUI('Segmentation finished', 0)
}
return tf.tensor(brainOut, [num_of_slices, slice_height, slice_width])
}
export async function generateOutputSlicesV2(
img,
OutVolumeTensorShape,
OutVolumeTensorType,
num_of_slices,
numSegClasses,
slice_height,
slice_width,
modelEntry,
opts,
niftiImage
) {
// Convert all slices into 1 Dim array
if (opts.isPostProcessEnable) {
const BWInstance = new BWLabeler()
const dim = new Uint32Array(OutVolumeTensorShape)
const conn = 6 // Example connectivity
const binarize = true
const onlyLargestClusterPerClass = true
const [_labelCount, labeledImage] = BWInstance.bwlabel(img, dim, conn, binarize, onlyLargestClusterPerClass)
for (let i = 0; i < img.length; i++) {
img[i] *= labeledImage[i]
}
} // if isPostProcessEnable
const typedArrayConstructor = {
float32: Float32Array,
int32: Int32Array
// Add other cases as needed for different dtypes
}[OutVolumeTensorType]
// Create a new TypedArray from img with the same type as outLabelVolume
const allOutputSlices3DCC1DimArray = new Uint8Array(img)
switch (modelEntry.type) {
case 'Brain_Masking': {
const brainMask = new Uint8Array(allOutputSlices3DCC1DimArray.length)
for (let i = 0; i < allOutputSlices3DCC1DimArray.length; i++) {
brainMask[i] = allOutputSlices3DCC1DimArray[i] !== 0 ? 1 : 0
}
return brainMask
}
case 'Brain_Extraction': {
if (modelEntry.returnMaskForExtraction) {
const brainMask = new Uint8Array(allOutputSlices3DCC1DimArray.length)
for (let i = 0; i < allOutputSlices3DCC1DimArray.length; i++) {
brainMask[i] = allOutputSlices3DCC1DimArray[i] !== 0 ? 1 : 0
}
return brainMask
}
const maskedData = new niftiImage.constructor(allOutputSlices3DCC1DimArray.length)
for (let i = 0; i < allOutputSlices3DCC1DimArray.length; i++) {
// Create the mask - 1 where the value is non-zero, 0 where it is zero.
const maskValue = allOutputSlices3DCC1DimArray[i] !== 0 ? 1 : 0
// Apply the mask to the data - multiply by the mask value.
maskedData[i] = niftiImage[i] * maskValue
}
return maskedData
}
}
return img
}
export async function getAllSlicesDataAsTF3D(num_of_slices, niftiHeader, niftiImage) {
// Get nifti dimensions
const cols = niftiHeader.dims[1] // Slice width
const rows = niftiHeader.dims[2] // Slice height
let typedData
if (niftiHeader.datatypeCode === 2) {
// enum from nvimage/utils DT_UINT8 = 2
typedData = new Uint8Array(niftiImage)
} else if (niftiHeader.datatypeCode === 4) {
// DT_INT16 = 4
typedData = new Int16Array(niftiImage)
} else if (niftiHeader.datatypeCode === 8) {
// DT_INT32 = 8
typedData = new Int32Array(niftiImage)
} else if (niftiHeader.datatypeCode === 16) {
// DT_FLOAT32 = 16
typedData = new Float32Array(niftiImage)
} else if (niftiHeader.datatypeCode === 64) {
// DT_FLOAT64 = 64
typedData = new Float64Array(niftiImage)
} else if (niftiHeader.datatypeCode === 256) {
// DT_INT8 = 256
typedData = new Int8Array(niftiImage)
} else if (niftiHeader.datatypeCode === 512) {
// DT_UINT16 = 512
typedData = new Uint16Array(niftiImage)
} else if (niftiHeader.datatypeCode === 768) {
// DT_UINT32 = 768
typedData = new Uint32Array(niftiImage)
} else {
return
}
const allSlices_2D = []
let offset3D = 0
// Draw pixels
for (let slice = 0; slice < num_of_slices; slice++) {
const slice = new Array(rows * cols)
let offset2D = 0
for (let row = 0; row < rows; row++) {
for (let col = 0; col < cols; col++) {
const value = typedData[offset3D++]
// Create 1Dim Array of pixel value, this 1 dim represents one channel
slice[offset2D++] = value & 0xff
}
}
allSlices_2D.push(tf.tensor(slice, [rows, cols])) // slice_height, slice_width
}
const allSlices_3D = tf.stack(allSlices_2D)
tf.dispose(allSlices_2D)
return allSlices_3D
}
export async function getModelNumLayers(modelObj) {
return modelObj.layers.length
}
export async function getModelNumParameters(modelObj) {
let numParameters = 0
for (let layerIdx = 0; layerIdx < modelObj.layers.length; layerIdx++) {
numParameters += modelObj.layers[layerIdx].countParams()
}
return numParameters
}
export async function isModelChnlLast(modelObj) {
for (let layerIdx = 0; layerIdx < modelObj.layers.length; layerIdx++) {
if (modelObj.layersByDepth[layerIdx][0].dataFormat) {
return modelObj.layersByDepth[layerIdx][0].dataFormat === 'channelsLast'
}
}
}
export async function load_model(modelUrl) {
return await tf.loadLayersModel(modelUrl)
}
export async function minMaxNormalizeVolumeData(volumeData) {
// Normalize the data to the range 0 - 1 using min-max scaling
const volumeData_Max = volumeData.max()
const volumeData_Min = volumeData.min()
const normalizedSlices_3d = await volumeData.sub(volumeData_Min).div(volumeData_Max.sub(volumeData_Min))
return normalizedSlices_3d
}
function processTensorInChunks(inputTensor, filterWeights, chunkSize) {
// Assuming inputTensor's shape: [batch, depth, height, width, inChannels]
// and filterWeights's shape: [filterDepth, filterHeight, filterWidth, inChannels, outChannels]
const stride = 1
const pad = 0
const dilationRate = 1
const inChannels = inputTensor.shape[4]
const numSlices = Math.ceil(inChannels / chunkSize)
let accumulatedResult = null
for (let i = 0; i < numSlices; i++) {
const startChannel = i * chunkSize
const endChannel = Math.min((i + 1) * chunkSize, inChannels)
const channels = endChannel - startChannel
const inputSlice = tf.tidy(() => {
// Slice the input tensor to get the current chunk
return inputTensor.slice([0, 0, 0, 0, startChannel], [-1, -1, -1, -1, channels])
})
const filterSlice = tf.tidy(() => {
// Slice the filter weights to match the input tensor's current chunk
return filterWeights.slice([0, 0, 0, startChannel, 0], [-1, -1, -1, channels, -1])
})
const resultSlice = tf.conv3d(inputSlice, filterSlice, stride, pad, 'NDHWC', dilationRate)
// Clean up the slices to free memory
inputSlice.dispose()
filterSlice.dispose()
// Squeeze the result slice to remove dimensions of size 1
const squeezedResultSlice = tf.squeeze(resultSlice)
resultSlice.dispose() // Dispose of the original resultSlice after squeezing
if (accumulatedResult === null) {
accumulatedResult = squeezedResultSlice
} else {
// Accumulate the result by adding the new result slice to it
const newAccumulatedResult = accumulatedResult.add(squeezedResultSlice)
// Dispose of the previous accumulatedResult and squeezedResultSlice
accumulatedResult.dispose()
// Dispose of squeezedResultSlice only if it wasn't assigned to accumulatedResult
if (accumulatedResult !== squeezedResultSlice) {
squeezedResultSlice.dispose()
}
// Update accumulatedResult with the new result
accumulatedResult = newAccumulatedResult
}
tf.tidy(() => {
tf.matMul(tf.zeros([1, 1]), tf.zeros([1, 1]))
})
}
return accumulatedResult
}
export async function quantileNormalizeVolumeData(
tensor,
lowerQuantile = 0.02,
upperQuantile = 0.98,
denominatorEpsilon = 1e-3
) {
if (!(lowerQuantile >= 0 && lowerQuantile < upperQuantile && upperQuantile <= 1)) {
throw new Error(`Invalid normalization percentiles: ${lowerQuantile}, ${upperQuantile}`)
}
// Call calculateQuantiles and wait for the result
const { qmin, qmax } = await calculateQuantiles(tensor, lowerQuantile, upperQuantile)
console.log(
`[Normalization] ${lowerQuantile * 100}-${upperQuantile * 100} percentiles: ` +
`low=${qmin}, high=${qmax}, epsilon=${denominatorEpsilon}, clip=[0,1]`
)
// Perform the operation: (tensor - qmin) / (qmax - qmin)
// Break up chained operations to properly dispose intermediate tensors
const range = qmax - qmin + denominatorEpsilon
const shifted = tensor.sub(qmin)
const scaled = shifted.div(range)
const resultTensor = scaled.clipByValue(0, 1)
shifted.dispose() // Dispose intermediate tensor to prevent memory leak
scaled.dispose()
// Return the resulting tensor (caller is responsible for disposing input tensor)
return resultTensor
}
export async function removeZeroPaddingFrom3dTensor(tensor3d, rowPad = 1, colPad = 1, depthPad = 1) {
if (tensor3d.rank !== 3) {
throw new Error('Tensor must be 3D')
}
const [h, w, d] = tensor3d.shape
return tensor3d.slice([rowPad, colPad, depthPad], [h - 2 * rowPad, w - 2 * colPad, d - 2 * depthPad])
}
export async function resizeWithZeroPadding(croppedTensor3d, newDepth, newHeight, newWidth, refVoxel, boundVolSizeArr) {
const row_pad_befor = refVoxel[0]
const col_pad_befor = refVoxel[1]
const depth_pad_befor = refVoxel[2]
// last and lower volume voxel
const row_max = row_pad_befor + boundVolSizeArr[0] - 1 // size [2, 2, 2] means 2 voxels total in each dim
const col_max = col_pad_befor + boundVolSizeArr[1] - 1
const depth_max = depth_pad_befor + boundVolSizeArr[2] - 1
const row_pad_after = newHeight - row_max - 1 > 0 ? newHeight - row_max - 1 : 0
const col_pad_after = newWidth - col_max - 1 > 0 ? newWidth - col_max - 1 : 0
const depth_pad_after = newDepth - depth_max - 1 > 0 ? newDepth - depth_max - 1 : 0
return croppedTensor3d.pad([
[row_pad_befor, row_pad_after],