question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

tf.LayersModel.save fails in a worker as window object is absent

See original GitHub issue

To get help from the community, we encourage using Stack Overflow and the tensorflow.js tag.

TensorFlow.js version

1.13

Browser version

Chrome 79

Describe the problem

tf.LayersModel.save("indexeddb://my-model-1") does not work in a web worker as window object is not found. It is due https://github.com/tensorflow/tfjs/blob/master/tfjs-core/src/io/indexed_db.ts#L60 line

ReferenceError: window is not defined
    at sp (indexed_db.ts:60)
    at new t (indexed_db.ts:89)
    at cp (indexed_db.ts:242)
    at router_registry.ts:96
    at Array.forEach (<anonymous>)
    at Function.t.getHandlers (router_registry.ts:95)
    at Function.t.getSaveHandlers (router_registry.ts:71)
    at Object.getSaveHandlers (router_registry.ts:110)
    at e.<anonymous> (training.ts:1814)
    at common.ts:14

Code to reproduce the bug / link to feature request

Simply try to save a model in a worker. You can try the below example in a worker,

worker.js

const model = tf.sequential(
    {layers: [tf.layers.dense({units: 1, inputShape: [3]})]});
console.log('Prediction from original model:');
model.predict(tf.ones([1, 3])).print();

const saveResults = await model.save('indexeddb://my-model-1');

main-thread.js

const w = new Worker("worker.js");
...

const loadedModel = await tf.loadLayersModel('indexeddb://my-model-1');
console.log('Prediction from loaded model:');
loadedModel.predict(tf.ones([1, 3])).print();

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Reactions:1
  • Comments:5 (2 by maintainers)

github_iconTop GitHub Comments

1reaction
paulkrecommented, Jun 7, 2020

I still have this issue in version 2.0.0. I’m using workerize-loader in a project bootstrapped with create-react-app.

1reaction
Josef-Hauptcommented, Mar 10, 2020

As of Version 1.7.0 this issues still existed for me.

0.worker.js:106656 Uncaught (in promise) ReferenceError: window is not defined
    at Ef (0.worker.js:106656)
    at new t (0.worker.js:106656)
    at kf (0.worker.js:106656)
    at 0.worker.js:106656
    at Array.forEach (<anonymous>)
    at Function.t.getHandlers (0.worker.js:106656)
    at Function.t.getSaveHandlers (0.worker.js:106656)
    at Object.getSaveHandlers (0.worker.js:106656)
    at t.<anonymous> (0.worker.js:107602)
    at 0.worker.js:107602

If anybody else still has this problem, this worked for me:

I created a custom IOHandler, which is basically a copy of the existing BrowserIndexedDB class and I updated the getIndexedDBFactory function the handler uses like so:

function getIndexedDBFactory(): IDBFactory {
    if (!env().getBool('IS_BROWSER')) {
        // TODO(cais): Add more info about what IOHandler subtypes are available.
        //   Maybe point to a doc page on the web and/or automatically determine
        //   the available IOHandlers and print them in the error message.
        throw new Error(
            'Failed to obtain IndexedDB factory because the current environment' +
            'is not a web browser.');
    }
    // tslint:disable-next-line:no-any
    let theWindow;
    try {
        theWindow = window;
    }
    catch {
        theWindow = self;
    }
    const factory = theWindow.indexedDB || theWindow.mozIndexedDB ||
        theWindow.webkitIndexedDB || theWindow.msIndexedDB ||
        theWindow.shimIndexedDB;
    if (factory == null) {
        throw new Error(
            'The current browser does not appear to support IndexedDB.');
    }
    return factory;
}

Usage:

//saveurl without the indexeddb:// scheme
model.save(new IDBWorkerSaveHandler(saveUrl))
Read more comments on GitHub >

github_iconTop Results From Across the Web

Creates a tf.Tensor with the provided values, shape and dtype.
Pass a `WebGLData` object and specify a shape yourself. // This makes it possible for TF.js applications to avoid GPU / CPU sync....
Read more >
Workers, web or service; anyway to access window object?
My idea was to try web workers to download the files, hopefully meaning the issue would go away/the app would be a bit...
Read more >
Tensorflow.js tf.LayersModel class .save() Method
An IOHandler is an object which possesses a save method concerning the accurate signature specified. The save method controls the accumulation ...
Read more >
How to Train an Object Detection Model with Keras
A Mask R-CNN model can be fit from scratch, although like other computer vision applications, time can be saved and performance can be...
Read more >
How to solve "window is not defined" errors in React and Next.js
I initially tried to do if (typeof window !== undefined) and this failed hard because of the reasons mentioned earlier. The other solutions ......
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found