@@ -54,21 +54,25 @@ export function findKNNGPUCosDistNorm<T>(
54
54
. runAsyncTask (
55
55
'Finding nearest neighbors...' ,
56
56
async ( ) => {
57
- const typedArray = vector . toTypedArray ( dataPoints , accessor ) ;
58
- const bigMatrix = tf . tensor ( typedArray , [ N , dim ] ) ;
59
- const bigMatrixTransposed = tf . transpose ( bigMatrix ) ;
60
- // A * A^T.
61
- const cosSimilarityMatrix = tf . matMul ( bigMatrix , bigMatrixTransposed ) ;
62
- bigMatrix . dispose ( ) ;
63
- bigMatrixTransposed . dispose ( ) ;
57
+ const cosSimilarityMatrix = tf . tidy ( ( ) => {
58
+ const typedArray = vector . toTypedArray ( dataPoints , accessor ) ;
59
+ const bigMatrix = tf . tensor ( typedArray , [ N , dim ] ) ;
60
+ const bigMatrixTransposed = tf . transpose ( bigMatrix ) ;
61
+ // A * A^T.
62
+ return tf . matMul ( bigMatrix , bigMatrixTransposed ) ;
63
+ } ) ;
64
64
// `.data()` returns flattened Float32Array of B * N dimension.
65
65
// For matrix of
66
66
// [ 1 2 ]
67
67
// [ 3 4 ],
68
68
// `.data()` returns [1, 2, 3, 4].
69
- const partial = await cosSimilarityMatrix . data ( ) ;
70
- // Discard all tensors and free up the memory.
71
- cosSimilarityMatrix . dispose ( ) ;
69
+ let partial ;
70
+ try {
71
+ partial = await cosSimilarityMatrix . data ( ) ;
72
+ } finally {
73
+ // Discard all tensors and free up the memory.
74
+ cosSimilarityMatrix . dispose ( ) ;
75
+ }
72
76
for ( let i = 0 ; i < N ; i ++ ) {
73
77
let kMin = new KMin < NearestEntry > ( k ) ;
74
78
for ( let j = 0 ; j < N ; j ++ ) {
0 commit comments