Skip to content
This repository has been archived by the owner on Nov 16, 2023. It is now read-only.

Commit

Permalink
Initial commit of ONNX.js v0.1.0
Browse files Browse the repository at this point in the history
  • Loading branch information
fs-eire committed Nov 29, 2018
0 parents commit 3331225
Show file tree
Hide file tree
Showing 197 changed files with 26,762 additions and 0 deletions.
7 changes: 7 additions & 0 deletions .clang-format
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
Language: JavaScript
BasedOnStyle: Google
ColumnLimit: 120
---
Language: Cpp
BasedOnStyle: LLVM
14 changes: 14 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
dist/
node_modules/
types/

lib/**/*.js
lib/**/*.js.map
test/**/*.js
test/**/*.js.map
tools/**/*.js
tools/**/*.js.map

npm-debug.log
.DS_Store
yarn-error.log
12 changes: 12 additions & 0 deletions .gitmodules
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
[submodule "deps/emsdk"]
path = deps/emsdk
url = https://github.com/juj/emsdk.git
ignore = dirty
[submodule "deps/eigen"]
path = deps/eigen
url = https://github.com/eigenteam/eigen-git-mirror.git
ignore = dirty
[submodule "deps/data"]
path = deps/data
url = https://github.com/Microsoft/onnxjs-demo.git
branch = data
6 changes: 6 additions & 0 deletions .huskyrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"skipCI": false,
"hooks": {
"pre-commit": "npm run lint && npm run format && node -e \"var lines = require('child_process').execSync('git ls-files -m').toString(); var tsFound = lines.split('\\n').map(i => i.trim()).find(i => i.endsWith('.ts')); if (tsFound) { console.error('ERR File not formatted: ' + tsFound); process.exit(1); }\""
}
}
23 changes: 23 additions & 0 deletions .npmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
benchmark/
deps/
examples/
node_modules/
src/
test/
tools/

lib/**/*.ts

.vscode

.clang-format
.huskyrc
.gitmodules
.npmrc
.npmignore
npm-debug.log

karma.conf.js
tsconfig.json
tslint.json
webpack.config.js
34 changes: 34 additions & 0 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "chrome",
"request": "attach",
"name": "Attach to Chrome",
"port": 9333,
"webRoot": "${workspaceFolder}",
"sourceMaps": true,
"smartStep": true
},
{
"type": "node",
"request": "launch",
"name": "Launch Mocha Tests (node)",
"program": "${workspaceFolder}/node_modules/mocha/bin/_mocha",
"args": [
"-u",
"tdd",
"--timeout",
"999999",
"--colors",
"${workspaceFolder}/test/unittest"
],
"internalConsoleOptions": "openOnSessionStart",
"sourceMaps": true,
"smartStep": true
}
]
}
28 changes: 28 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
// Place your settings in this file to overwrite default and user settings.
{
"search.exclude": {
"**/node_modules": true,
"./dist": true,
"./types": true,
},
"files.exclude": {
"lib/**/*.js.map": true,
"lib/**/*.js": true,
},
"tslint.enable": true,
"tslint.run": "onType",
"tslint.configFile": "tslint.json",
"files.trimTrailingWhitespace": true,
"editor.tabSize": 2,
"editor.insertSpaces": true,
"[typescript]": {
"editor.formatOnSave": true
},
"editor.rulers": [120],
"clang-format.style": "file",
"files.insertFinalNewline": true,
"editor.detectIndentation": false,
"editor.wrappingIndent": "none",
"typescript.tsdk": "node_modules/typescript/lib",
"clang-format.executable": "${workspaceRoot}/node_modules/.bin/clang-format"
}
13 changes: 13 additions & 0 deletions .vscode/tasks.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "2.0.0",
"tasks": [
{
"label": "test: suite0",
"group": "test",
"type": "shell",
"command": "${workspaceFolder}/tools/test-runner-cli suite0"
}
]
}
14 changes: 14 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@

You are welcome to contribute to ONNX.js!

You can contribute to ONNX.js in following ways:

* Contribute to core module functionality
* For example- implement ONNX operators to support more models, implement optimizations to the model execution framework, etc.
* Contribute bug fixes.
* Review the [source code changes](https://github.com/Microsoft/onnxjs/pulls).
* [Report issues](https://github.com/Microsoft/onnxjs/issues) and help us verify fixes as they are checked in.

Any changes are required to be reviewed. Please submit a [pull request](https://help.github.com/articles/about-pull-requests/) so that changes can be reviewed.

This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [email protected] with any additional questions or comments.
11 changes: 11 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
ONNX.js

Copyright (c) Microsoft Corporation. All rights reserved.

MIT License

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ""Software""), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
146 changes: 146 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
# ONNX.js
ONNX.js is a Javascript library for running ONNX models on browsers and on Node.js.

ONNX.js has adopted WebAssembly and WebGL technologies for providing an optimized ONNX model inference runtime for both CPUs and GPUs.

### Why ONNX models
The [Open Neural Network Exchange](http://onnx.ai/) (ONNX) is an open standard for representing machine learning models. The biggest advantage of ONNX is that it allows interoperability across different open source AI frameworks, which itself offers more flexibility for AI frameworks adoption. [This](#Getting-ONNX-models) is a great place to start getting acquainted with ONNX models.

### Why ONNX.js
With ONNX.js, web developers can score pre-trained ONNX models directly on browsers with various benefits of reducing server-client communication and protecting user privacy, as well as offering install-free and cross-platform in-browser ML experience.

ONNX.js can run on both CPU and GPU. For running on CPU, [WebAssembly](https://developer.mozilla.org/en-US/docs/WebAssembly) is adopted to execute model at near-native speed. Furthermore, ONNX.js utilizes [Web Workers](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers) to provide a "multi-threaded" environment to parallelize data processing. Empirical evaluation shows very promising performance gains on CPU by taking full advantage of WebAssembly and Web Workers. For running on GPUs, a popular standard for accessing GPU capabilities - WebGL is adopted. ONNX.js has further adopted several novel optimization techniques for reducing data transfer between CPU and GPU, as well as some techniques to reduce GPU processing cycles to further push the performance to the maximum.

### Benchmarks

Benchmarks have been run against the most prominent open source solutions in the same market. Below are the results collected for Chrome and Edge browsers on one sample machine (computations run on both CPU and GPU):

![alt text](./docs/perf-resnet50.png "Resnet50 Perf numbers")

> NOTE:
> 1. Keras.js doesn't support WebGL usage on Edge
> 2. Keras.js and TensorFlow.js doesn't support WebAssembly usage on any browser
> The specs of the machine that was used to perform the benchmarking is listed below:
> * OS: Microsoft Windows 10 Enterprise Insider Preview
> * Model: HP Z240 Tower Workstation
> * Processor: Intel(R) Core(TM) i7-6700 CPU @ 3.40GHz, 3401 Mhz, 4 Core(s), 8 Logical Processor(s)
> * Installed Physical Memory (RAM): 32.0 GB
> * GPU make / Chip type: AMD FirePro W2100 / AMD FirePro SDI (0x6608)
> * GPU Memory (approx.): 18.0 GB
### Demo

[ONNX.js demo website](https://microsoft.github.io/onnxjs-demo/) shows the capabilities of ONNX.js. Check the [code](https://github.com/Microsoft/onnxjs-demo).

## Getting Started
There are multiple ways to use ONNX.js in a project:

### Using `<script>` tag

This is the most straightforward way to use ONNX.js. The following HTML example shows how to use it:

```html
<html>
<head>
</head>

<body>
<!-- Load ONNX.js -->
<script src="https://cdn.jsdelivr.net/npm/onnxjs/dist/onnx.min.js"></script>
<!-- Code that consume ONNX.js -->
<script>
// create a session
const myOnnxSession = new onnx.InferenceSession();
// load the ONNX model file
myOnnxSession.loadModel("./my-model.onnx").then(()=>{
// generate model input
const inferenceInputs = getInputs();
// execute the model
session.run(inferenceInputs).then(output=>{
// consume the output
const outputTensor = output.values().next().value;
console.log(`model output tensor: ${outputTensor.data}.`);
});
})
</script>
</body>
</html>
```

Refer to [browser/Add](./examples/browser/add) for an example.

### Using NPM and bundling tools

Modern browser based applications are usually built by frameworks like [Angular](https://angular.io/), [React](https://reactjs.org/), [Vue.js](https://vuejs.org/) and so on. This solution usually builds the source code into one or more bundle file(s). The following TypeScript example shows how to use ONNX.js in an async context:

1. Import `Tensor` and `InferenceSession`.
```ts
import {Tensor, InferenceSession} from 'onnxjs';
```

2. Create an instance of `InferenceSession`.
```ts
const session = new InferenceSession();
```

3. Load the ONNX.js model
```ts
// use the following in an async method
const url = './data/models/resnet/model.onnx';
await session.loadModel(url);
```

4. Create your input Tensor(s) similar to the example below. You need to do any pre-processing required by
your model at this stage. For that refer to the documentation of the model you have:
```javascript
// creating an array of input Tensors is the easiest way. For other options see the API documentation
const inputs = [new Tensor(new Float32Array([1.0,2.0,3.0,4.0]), 'float32', [2,2])];
```
5. Run the model with the input Tensors. The output Tensor(s) are available once the run operation is complete:
```javascript
// run this in an async method:
const outputMap = await session.run(inputs);
const outputTensor = outputMap.values().next().value;
```
More verbose examples on how to use ONNX.js are located under the `examples` folder. For further info see [Examples](./examples/README.md)

### Running in Node.js

ONNX.js can run in Node.js as well. This is usually for testing purpose. Use the `require()` function to load ONNX.js:
```js
require('onnxjs');
```

Refer to [node/Add](./examples/node/add) for a detailed example.

*NOTE: Currently, the supported platforms are Windows 10 + Edge/Chrome/Firefox/Electron/Node.js (support for other platforms is coming soon).*

## Documents

### Developers
For information on development ONNX.js, please check [Development](./docs/development.md)

For API reference, please check [API](./docs/api.md).

### Getting ONNX models
You could get ONNX models easily in multiple ways:
- Choose a pre-trained ONNX model from the [ONNX Model Zoo](https://github.com/onnx/models)
- Convert models from mainstream frameworks, e.g. PyTorch, TensorFlow and Keras, by following [ONNX tutorials](https://github.com/onnx/tutorials)
- Use your data to generate a customized ONNX model from [Azure Custom Vision service](https://docs.microsoft.com/en-us/azure/cognitive-services/Custom-Vision-Service/home)
- [Train a custom model in AzureML](https://github.com/Azure/MachineLearningNotebooks/tree/master/training) and save it in the ONNX format

Learn more about ONNX
- [ONNX website](http://onnx.ai/)
- [ONNX on GitHub](https://github.com/onnx/onnx)

### Operators supported
The [list](./docs/operators.md) of ONNX operators supported by each of the 3 available builtin backends (cpu, wasm, and webgl).

## Contribute
We’d love to embrace your contribution to ONNX.js. Please refer to [CONTRIBUTING.md](./CONTRIBUTING.md).

## License
Copyright (c) Microsoft Corporation. All rights reserved.

Licensed under the [MIT](./LICENSE) License.
11 changes: 11 additions & 0 deletions benchmark/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# Licenses

TensorFlow.js:
https://github.com/tensorflow/tfjs/blob/master/LICENSE

Keras.js:
https://github.com/transcranial/keras-js/blob/master/LICENSE

WebDNN:
https://github.com/mil-tokyo/webdnn/blob/master/LICENSE.txt

47 changes: 47 additions & 0 deletions benchmark/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
# Benchmarks
This sub project is to benchmark and compare ONNX.js peformance vs other leading in-browser AI Inference frameworks.

## Frameworks
- TensorFlow.js
- Keras.js
- WebDNN
- ONNX.js

## Backends
(not all backends supported by all platforms)
- WebGL
- WebAssembly
- CPU

## Browsers
(not all framework/backend combinations are supported by all browsers)
- Chrome (WebGL 2)
- Edge (WebGL 1)

## Instructions
Please download all the sub-folders (containing the model files and corresponding test data) under
https://github.com/Microsoft/onnxjs-demo/tree/data/data/benchmark and place them in ./benchmark/data prior to running the benchmark tests

1. Ensure that the ONNX.js project (the parent) is already installed and built:
```bash
npm ci
npm run build
```
2. Change to `benchmark` subfolder and run npm ci and build in the benchmark folder
```bash
cd benchmark
npm install
npm run build
```
3. Run tests (Chrome)
```bash
npm run test
```
4. Run tests (Edge)

Note that the Edge tests are likely to crash the broswer. A recommended way would be to comment out
all Frameworks and backends except one and repeat this for all others. Look in the definition for
`BenchmarkImageNetData` in src/index.js
```bash
npm run test-edge
```
Loading

0 comments on commit 3331225

Please sign in to comment.