onnxruntime/js/node/lib/backend.ts
Caroline Zhu 6a5f469d44
Add training interfaces to js/common (#17333)
### Description
Following the design document:
* Added CreateTrainingSessionHandler to the Backend interface
* All existing Backend implementations throw an error for the new method
createTrainingSessionHandler
* Created TrainingSession namespace, interface, and
TrainingSessionFactory interface
* Created TrainingSessionImpl class implementation 

As methods are implemented, the TrainingSession interface will be added
to or modified.

### Motivation and Context
Adding the public-facing interfaces to the onnxruntime-common package is
one of the first steps to support ORT training for web bindings.

---------

Co-authored-by: Caroline Zhu <carolinezhu@microsoft.com>
2023-09-29 19:05:10 -07:00

72 lines
2.2 KiB
TypeScript

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
import {Backend, InferenceSession, InferenceSessionHandler, SessionHandler} from 'onnxruntime-common';
import {Binding, binding} from './binding';
class OnnxruntimeSessionHandler implements InferenceSessionHandler {
#inferenceSession: Binding.InferenceSession;
constructor(pathOrBuffer: string|Uint8Array, options: InferenceSession.SessionOptions) {
this.#inferenceSession = new binding.InferenceSession();
if (typeof pathOrBuffer === 'string') {
this.#inferenceSession.loadModel(pathOrBuffer, options);
} else {
this.#inferenceSession.loadModel(pathOrBuffer.buffer, pathOrBuffer.byteOffset, pathOrBuffer.byteLength, options);
}
this.inputNames = this.#inferenceSession.inputNames;
this.outputNames = this.#inferenceSession.outputNames;
}
async dispose(): Promise<void> {
return Promise.resolve();
}
readonly inputNames: string[];
readonly outputNames: string[];
startProfiling(): void {
// TODO: implement profiling
}
endProfiling(): void {
// TODO: implement profiling
}
async run(feeds: SessionHandler.FeedsType, fetches: SessionHandler.FetchesType, options: InferenceSession.RunOptions):
Promise<SessionHandler.ReturnType> {
return new Promise((resolve, reject) => {
process.nextTick(() => {
try {
resolve(this.#inferenceSession.run(feeds, fetches, options));
} catch (e) {
// reject if any error is thrown
reject(e);
}
});
});
}
}
class OnnxruntimeBackend implements Backend {
async init(): Promise<void> {
return Promise.resolve();
}
async createInferenceSessionHandler(pathOrBuffer: string|Uint8Array, options?: InferenceSession.SessionOptions):
Promise<InferenceSessionHandler> {
return new Promise((resolve, reject) => {
process.nextTick(() => {
try {
resolve(new OnnxruntimeSessionHandler(pathOrBuffer, options || {}));
} catch (e) {
// reject if any error is thrown
reject(e);
}
});
});
}
}
export const onnxruntimeBackend = new OnnxruntimeBackend();
export const listSupportedBackends = binding.listSupportedBackends;