Skip to content

js: dispose the graph model output after squeezing it - #1467

Open
Dev-next-gen wants to merge 1 commit into
google:mainfrom
Dev-next-gen:js-dispose-model-output
Open

Dev-next-gen wants to merge 1 commit into
google:mainfrom
Dev-next-gen:js-dispose-model-output

Conversation

@Dev-next-gen

Copy link
Copy Markdown

While reading js/src/model.ts I noticed that Model.predict disposes modelInput, maxScoreIndexTensor and modelOutput, but not the tensor that executeAsync actually returned. tf.squeeze builds a new tensor over the same data, so the original output stays registered in the tfjs engine and its data bucket keeps a reference. One tensor is leaked per prediction, for the lifetime of the Magika instance.

I checked it on standard_v3_3 with the Node binding, calling identifyBytes repeatedly on the same small buffer and reading tf.memory().numTensors after a warm-up call:

after call 1: numTensors=76 (delta vs baseline 1)
after call 2: numTensors=77 (delta vs baseline 2)
after call 3: numTensors=78 (delta vs baseline 3)
after call 4: numTensors=79 (delta vs baseline 4)
after call 5: numTensors=80 (delta vs baseline 5)

With tf.dispose(rawOutput) added, the same loop stays flat at the baseline. This matters most for the long-lived cases: the website demo keeps one Magika around for the whole page, and magika-js scans every path given on the command line with a single instance, so on WebGL this is retained GPU memory that only goes away when the tab does.

The reads of rawScores were already done before the existing dispose() calls, so the new one changes nothing for the returned prediction; tf.dispose is used rather than .dispose() so the Tensor | Tensor[] return type of executeAsync stays handled the way the current as any cast leaves it.

I also added a regression test to js/test/magika.test.ts. It fails on main (Expected: 75, Received: 80) and passes with the fix. The full suite is green: 9823 tests, 4 suites, Node 22, yarn test.

AI tools used

`Model.predict` squeezes the tensor returned by `executeAsync` and disposes
the squeezed tensor, but never the tensor it was squeezed from. `squeeze`
returns a new tensor that shares the data of its input, so the original
output stays registered in the tfjs engine and its data is never released:
`tf.memory().numTensors` grows by one on every prediction, for the lifetime
of the `Magika` instance.

Dispose it explicitly and add a regression test asserting that repeated
`identifyBytes` calls leave the tensor count unchanged.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant