Giter VIP home page Giter VIP logo

libtorchjs's Introduction

LibtorchJS

Simple Node.js N-API module that wraps few pieces of pytorch C++ library (libtorch) to allow loading and running pytorch-trained models in Node.js.

Node.js non-blocking model is great for scheduling heavy computational tasks such as NN inference. This wrapper provides async methods that do not block event loop, so it's possible to use it in a web-service.

This module was made just for fun, to check if it's easily possible to create image style transfer app with Node.js.

Installation

With npm: npm i --save libtorchjs

Module binary is pre-built and published using node-pre-gyp so it's not required to download libtorch/pytorch or install build tools.

Currently, Linux & Windows builds are available.

Usage Example

const torch = require('libtorchjs');

const input = torch.randn([1, 3, 224, 224]);
torch.load('model.pt', function(err, model) {
    model.forward(input, function(err, result) {
        const output = result.toUint8Array();
        console.log(output);
    });
});

API

The overall goal is to mirror pytorch API where possible. Currently just a few methods are exposed.

Tensor

ones(Array shape)

Create tensor of specified shape filled with 1's (autograd is disabled) and return Tensor object.

randn(Array shape)

Create tensor of specified shape (autograd is disabled) filled with random values in (0..1) range.

ScriptModule

load(String filename, callback)

Load traced model async from file and return resulting ScripModule.

forward(Tensor tensor, callback)

Forward tensor async and return resulting Tensor.

Acknowledgments

Following resources were extremely useful for creating this module:

Possible Future

  • Expose more of libtorch
  • Promisify libtorchjs API
  • GPU support
  • Windows ✔️, Mac support
  • Use travis/appveyor for automatic builds

libtorchjs's People

Contributors

vvmnnnkv avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

libtorchjs's Issues

Underrated

Not gonna lie, this repo is hella underrated. PyTorch is an excellent machine learning framework, c++ is hella fast, and the community for production it is hella small. You can bind pytorch (c++ libtorch) with golang, rust, nodejs so I'm quite impressed with ur readme.md explanation.

"Error: Expected tensor for argument #1 'indices' to have scalar type Long; but got CPUFloatType instead"

Hi @vvmnnnkv

So as discussed before, the lib only supports float tensors and it can only converts back to JS as Uint8 array atm. It could be great to expose more types/functions and make it more generic.

In C++ I've managed to fix the issue by changing the input tensor type to 'kLong':
torch::jit::IValue input = torch::from_blob(data, shape, torch::TensorOptions().dtype(torch::kLong))

Thank you in advance and let me know if I can help in any way !

Mac Support

I made a fork that supports MacOS locally https://github.com/jlarmstrongiv/libtorchjs

To demo the fork, be sure to:

  • install pytorch pip install torch torchvision torchaudio
  • download LibTorch from https://download.pytorch.org/libtorch/cpu/libtorch-macos-1.8.1.zip
  • unzip LibTorch in the project root (so you have the libtorch folder as a sibling to lib)
  • run npm --build-from-source install

Check out the changes in the binding.gyp and add darwin to the os array in the package.json. The fork is more of an example than a PR, since I’m not quite sure how your build process works.

Would love to add support in the official package though 😄 keep up the great work!

New Pytorch versions available.

Hello! I am using your library and it is awesome. But there are new PT versions, this way lib cannot run some modern models.
Can you please make it run at least 1.8 ver?
I have tried to do it myself, but I have no idea why compilation failing all time (spend 3 days and 0 result)

Compatibility issue with newer versions of libtorch

Hi there,

As discussed before, there are some compatibility issue when loading a newer version of pytorch model, so it could be great if you recompile the module binaries with the latest version of libtorch.

Thank you in advance!

Error while downloading in npm window

node-pre-gyp WARN Using needle for node-pre-gyp https download
node-pre-gyp ERR! install error
node-pre-gyp ERR! stack Error: 404 status code downloading tarball https://libtorchjs.s3.amazonaws.com/libtorchjs/v1.0.0-alpha.4/Release/win32-x64-napi-v3.tar.gz
node-pre-gyp ERR! stack at PassThrough. (C:\Users\troop\server\node_modules\node-pre-gyp\lib\install.js:142:27)
node-pre-gyp ERR! stack at PassThrough.emit (events.js:323:22)
node-pre-gyp ERR! stack at ClientRequest. (C:\Users\troop\server\node_modules\needle\lib\needle.js:488:9)
node-pre-gyp ERR! stack at Object.onceWrapper (events.js:418:26)
node-pre-gyp ERR! stack at ClientRequest.emit (events.js:311:20)
node-pre-gyp ERR! stack at HTTPParser.parserOnIncomingClient [as onIncoming] (_http_client.js:603:27)
node-pre-gyp ERR! stack at HTTPParser.parserOnHeadersComplete (_http_common.js:119:17)
node-pre-gyp ERR! stack at TLSSocket.socketOnData (_http_client.js:476:22)
node-pre-gyp ERR! stack at TLSSocket.emit (events.js:311:20)
node-pre-gyp ERR! stack at addChunk (_stream_readable.js:294:12)
node-pre-gyp ERR! System Windows_NT 10.0.18362
node-pre-gyp ERR! command "C:\Program Files\nodejs\node.exe" "C:\Users\troop\server\node_modules\node-pre-gyp\bin\node-pre-gyp" "install" "--fallback-to-build=false"
node-pre-gyp ERR! cwd C:\Users\troop\server\node_modules\libtorchjs
node-pre-gyp ERR! node -v v12.16.1
node-pre-gyp ERR! node-pre-gyp -v v0.14.0
node-pre-gyp ERR! not ok
404 status code downloading tarball https://libtorchjs.s3.amazonaws.com/libtorchjs/v1.0.0-alpha.4/Release/win32-x64-napi-v3.tar.gz
npm WARN [email protected] No description
npm WARN [email protected] No repository field.

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] install: node-pre-gyp install --fallback-to-build=false
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] install script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.


how can I solve and download libtorchjs??

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.