mirror of
https://github.com/saymrwulf/onnxruntime.git
synced 2026-05-30 23:18:20 +00:00
### Description
This change introduced the following new components into ONNX Runtime
Web:
- JavaScript Execution Provider (JSEP)
- Asynchronized inferencing execution powered by Emscripten's Asyncify
- WebGPU backend implemented in TypeScript
- initial implementation of kernels:
- elementwise operators (22)
- binary operators (5)
- tensor: Shape, Reshape, Transpose, Gemm
- nn: Conv, {Global}Maxpool, {Global}AveragePool
Code need to be polished. still working on it.
## Q&A
What is JSEP?
> JSEP, aka JavaScript Execution Provider, is a new ONNXRuntime
execution provider that specifically works on Web environment
(browsers). JSEP allows JavaScript code to kick in from various places
when ONNX Runtime inferences a model.
Why JSEP?
> JSEP is a hybrid mode EP that contains both C/C++ and
TypeScript/JavaScript implementation. There are 2 strong reasons why we
introduces JSEP:
> 1. the C/C++ part helps JSEP to leverage ONNX Runtime's capabilities
as much as possible including graph transformer, optimizers and also the
capabilities to fallback to CPU EP. TypeScript/JavaScript helps JSEP to
develop and debug much easier in the browser for the kernel
implementation.
> 2. the requirement of asynchronized execution from JavaScript API (eg.
`buffer.mapAsync()`) makes it impossible to run `OrtRun()` in a
synchronized context (see "async problem" section below). This is done
by using Emscripten's Asyncify.
What is WebGPU?
> WebGPU is the new GPU API that available in browser. It's one of the
only 2 APIs that currently available to access the GPU from browser (the
other is WebGL).
> WebGPU is designed with more advanced and stronger features comparing
to WebGL and is potentially solution that offer the best GPU performance
for model inferencing that currently available.
What is the async problem and why we have the problem?
> The "async problem" is a problem that you cannot call an async
function in a synchronous context. Think about the following C++ code:
> ```c
> // C-style declarations (API)
> typedef void (*ON_COMPLETE)(PVOID state, DATA *data);
> void read_data_from_file(FILEHANDLE file, ON_COMPLETE on_complete);
>
> // implementation
> DATA * my_impl_read_data_from_file_sync(FILEHANDLE file) {
> // how to implement?
> }
> ```
> The answer is, it's impossible to implement this function. Usually we
try to find a sync version API, or launch a thread to call the async
function and sync-wait on the main thread. Unfortunately, in browser
environment, neither is possible.
>
> WebGPU does not offer any synchronized API for data downloading (GPU
to CPU). This is the only operation that MUST be async. As `OrtRun()`
will eventually call into DataTransfer for copy data from GPU to CPU,
and `OrtRun()` is a synchronized function, this cannot be done in normal
way.
What is Emscripten? How is the Asyncify feature resolved the problem?
> Emscripten is the C/C++ compiler for WebAssembly. It's what we use to
compile ORT and generates the WebAssembly artifacts which runs on
browsers.
>
> Asyncify is a [compiler
feature](https://emscripten.org/docs/porting/asyncify.html) that allows
calling async functions from a synchronized context. In short, it
generates code to unwind and rewind call stack to emulate async
execution. With this feature, we are able to call the async function
inside `OrtRun()` call.
## Design Overview
**Inter-op**
JSEP is doing pretty much same thing to just another EP. It exposes an
interface for inter-op with JavaScript, which is defined in
onnxruntime/wasm/js_internal_api.js:
```js
// init JSEP
Module["jsepInit"] = function (backend, alloc, free, copy, copyAsync, createKernel, releaseKernel, run) {
Module.jsepBackend = backend;
Module.jsepAlloc = alloc;
Module.jsepFree = free;
Module.jsepCopy = copy;
Module.jsepCopyAsync = copyAsync;
Module.jsepCreateKernel = createKernel;
Module.jsepReleaseKernel = releaseKernel;
Module.jsepRun = run;
};
```
This simple JavaScript snippet defines all language barrier level
functions that requires by JSEP to achieve implementing kernels and data
transfers using JavaScript inside ONNX Runtime:
- `jsepBackend`: assign the singleton object to webassembly module
- `jsepAlloc` and `jsepFree`: implementation of data transfer's Alloc()
and Free()
- `jsepCopy`: synchronized copy ( GPU to GPU, CPU to GPU)
- `jsepCopyAsync`: asynchronized copy ( GPU to CPU)
- `jsepCreateKernel` and `jsepReleaseKernel`: a corresponding object
that maintained in JS to match lifecycle of Kernel in ORT
- `jsepRun`: OpKernel::Compute() should call into this
The abstraction above allows to tie as little as possible connections
and dependencies between C/C++ and TypeScript/JavaScript.
**Resource Management**
Lifecycle of tensor data and kernels are managed by ORT(C/C++) but the
implementation are left to JavaScript. JavaScript code are responsible
to implement the callbacks correctly.
For WebGPU, the GPU data is managed by JavaScript using a singleton map
(tensot_data_id => GPUBuffer). GPU pipeline is managed as singleton.
Shaders are managed using a singletonmap (shader_key => gpu_program),
while shader_key is generated by cache_key (OP specific, including
attributes) and input shapes.
**about data transfer**
`js::DataTransfer::CopyTensor` implemented to call either synchronized
or asynchronized copy callback, depending on the destination is GPU or
not. Emscripten's macro `EM_ASYNC_JS` is used to wrap the async function
to be called in the synchronized context.
**run kernel in JS**
Kernel class constructor calls once `jsepCreateKernel()` with an
optional per-kernel specific serialization to pass attributes into
JavaScript.
`Compute()` are implemented in a way that a metadata serialization is
performed in a base class and JavaScript code can access the data using
the Emscripten specific builtin macro `EM_ASM_*`.
**disabled features**
memory pattern is force disabled, because the WebGPU data is not
presented by a general memory model (a buffer can be represented by
offset + size).
concurrent run support is disabled. WebGPU is stateful and it also has
async function call. To support concurrent run will significantly
increase the complexity and we don't get any real benefit from it.
**prefer channels last**
JSEP prefers channels last and returns `DataLayout::NHWC` in method
`GetPreferredLayout()`. This will let the graph transformers to
preprocess the graph into a channels last form so that a more optimized
WebGPU shader can be used.
**Testing code**
It's impossible to test JSEP directly because JSEP itself does not
contain any kernel implementation. However, it has the kernel
registration which need to work together with the corresponding
JavaScript code. There are unit tests that run onnx models from
JavaScript API.
---------
Co-authored-by: Scott McKay <skottmckay@gmail.com>
231 lines
7.5 KiB
TypeScript
231 lines
7.5 KiB
TypeScript
// Copyright (c) Microsoft Corporation. All rights reserved.
|
|
// Licensed under the MIT License.
|
|
|
|
import {WebGpuBackend} from '../backend-webgpu';
|
|
import {LOG_DEBUG} from '../log';
|
|
|
|
import {GpuData, GpuDataId, GpuDataType} from './types';
|
|
|
|
/**
|
|
* manages GpuDataId -> GpuBuffer
|
|
*/
|
|
export interface GpuDataManager {
|
|
/**
|
|
* copy data from CPU to GPU.
|
|
*/
|
|
upload(id: GpuDataId, data: Uint8Array): void;
|
|
/**
|
|
* copy data from GPU to GPU.
|
|
*/
|
|
memcpy(sourceId: GpuDataId, destinationId: GpuDataId): void;
|
|
/**
|
|
* create new data on GPU.
|
|
*/
|
|
create(size: number, usage?: number): GpuData;
|
|
/**
|
|
* get GPU data by ID.
|
|
*/
|
|
get(id: GpuDataId): GpuData|undefined;
|
|
/**
|
|
* release the data on GPU by ID.
|
|
*
|
|
* @return size of the data released
|
|
*/
|
|
release(id: GpuDataId): number;
|
|
/**
|
|
* copy data from GPU to CPU.
|
|
*/
|
|
download(id: GpuDataId): Promise<ArrayBufferLike>;
|
|
|
|
/**
|
|
* refresh the buffers that marked for release.
|
|
*
|
|
* when release() is called, the buffer is not released immediately. this is because we need to wait for the commands
|
|
* to be submitted to the GPU. this function is called after the commands are submitted so that the buffers can be
|
|
* actually released.
|
|
*/
|
|
refreshPendingBuffers(): void;
|
|
}
|
|
|
|
interface StorageCacheValue {
|
|
gpuData: GpuData;
|
|
originalSize: number;
|
|
}
|
|
|
|
interface DownloadCacheValue {
|
|
data: Promise<ArrayBufferLike>;
|
|
}
|
|
|
|
/**
|
|
* normalize the buffer size so that it fits the 128-bits (16 bytes) alignment.
|
|
*/
|
|
const calcNormalizedBufferSize = (size: number) => Math.ceil(size / 16) * 16;
|
|
|
|
let guid = 0;
|
|
const createNewGpuDataId = () => guid++;
|
|
|
|
class GpuDataManagerImpl implements GpuDataManager {
|
|
// GPU Data ID => GPU Data ( storage buffer )
|
|
storageCache: Map<GpuDataId, StorageCacheValue>;
|
|
|
|
// GPU Data ID => GPU Data ( read buffer )
|
|
downloadCache: Map<GpuDataId, DownloadCacheValue>;
|
|
|
|
// pending buffers for uploading ( data is unmapped )
|
|
private buffersForUploadingPending: GPUBuffer[];
|
|
// pending buffers for computing
|
|
private buffersPending: GPUBuffer[];
|
|
|
|
constructor(private backend: WebGpuBackend /* , private reuseBuffer: boolean */) {
|
|
this.storageCache = new Map();
|
|
this.downloadCache = new Map();
|
|
this.buffersForUploadingPending = [];
|
|
this.buffersPending = [];
|
|
}
|
|
|
|
upload(id: GpuDataId, data: Uint8Array): void {
|
|
const srcArrayBuffer = data.buffer;
|
|
const srcOffset = data.byteOffset;
|
|
const srcLength = data.byteLength;
|
|
const size = calcNormalizedBufferSize(srcLength);
|
|
|
|
// get destination gpu buffer
|
|
const gpuDataCache = this.storageCache.get(id);
|
|
if (!gpuDataCache) {
|
|
throw new Error('gpu data for uploading does not exist');
|
|
}
|
|
if (gpuDataCache.originalSize !== srcLength) {
|
|
throw new Error(`inconsistent data size. gpu data size=${gpuDataCache.originalSize}, data size=${srcLength}`);
|
|
}
|
|
|
|
// create gpu buffer
|
|
const gpuBufferForUploading = this.backend.device.createBuffer(
|
|
// eslint-disable-next-line no-bitwise
|
|
{mappedAtCreation: true, size, usage: GPUBufferUsage.MAP_WRITE | GPUBufferUsage.COPY_SRC});
|
|
|
|
// copy (upload) data
|
|
const arrayBuffer = gpuBufferForUploading.getMappedRange();
|
|
new Uint8Array(arrayBuffer).set(new Uint8Array(srcArrayBuffer, srcOffset, srcLength));
|
|
gpuBufferForUploading.unmap();
|
|
|
|
|
|
// GPU copy
|
|
const commandEncoder = this.backend.getCommandEncoder();
|
|
this.backend.endComputePass();
|
|
commandEncoder.copyBufferToBuffer(gpuBufferForUploading, 0, gpuDataCache.gpuData.buffer, 0, size);
|
|
|
|
LOG_DEBUG('verbose', () => `[WebGPU] GpuDataManager.upload(id=${id})`);
|
|
|
|
this.buffersForUploadingPending.push(gpuBufferForUploading);
|
|
}
|
|
|
|
memcpy(sourceId: GpuDataId, destinationId: GpuDataId): void {
|
|
// get source gpu buffer
|
|
const sourceGpuDataCache = this.storageCache.get(sourceId);
|
|
if (!sourceGpuDataCache) {
|
|
throw new Error('source gpu data for memcpy does not exist');
|
|
}
|
|
// get destination gpu buffer
|
|
const destinationGpuDataCache = this.storageCache.get(destinationId);
|
|
if (!destinationGpuDataCache) {
|
|
throw new Error('destination gpu data for memcpy does not exist');
|
|
}
|
|
if (sourceGpuDataCache.originalSize !== destinationGpuDataCache.originalSize) {
|
|
throw new Error('inconsistent source and destination gpu data size');
|
|
}
|
|
const size = calcNormalizedBufferSize(sourceGpuDataCache.originalSize);
|
|
// GPU copy
|
|
this.backend.getCommandEncoder().copyBufferToBuffer(
|
|
sourceGpuDataCache.gpuData.buffer, 0, destinationGpuDataCache.gpuData.buffer, 0, size);
|
|
}
|
|
|
|
// eslint-disable-next-line no-bitwise
|
|
create(size: number, usage = GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST): GpuData {
|
|
// !!!
|
|
// !!! IMPORTANT: TODO: whether we should keep the storage buffer every time, or always create new ones.
|
|
// !!! This need to be figured out by performance test results.
|
|
// !!!
|
|
|
|
const bufferSize = calcNormalizedBufferSize(size);
|
|
|
|
// create gpu buffer
|
|
const gpuBuffer = this.backend.device.createBuffer({size: bufferSize, usage});
|
|
|
|
const gpuData = {id: createNewGpuDataId(), type: GpuDataType.default, buffer: gpuBuffer};
|
|
this.storageCache.set(gpuData.id, {gpuData, originalSize: size});
|
|
|
|
LOG_DEBUG('verbose', () => `[WebGPU] GpuDataManager.create(size=${size}) => id=${gpuData.id}`);
|
|
return gpuData;
|
|
}
|
|
|
|
get(id: GpuDataId): GpuData|undefined {
|
|
return this.storageCache.get(id)?.gpuData;
|
|
}
|
|
|
|
release(id: GpuDataId): number {
|
|
const cachedData = this.storageCache.get(id);
|
|
if (!cachedData) {
|
|
throw new Error('releasing data does not exist');
|
|
}
|
|
|
|
LOG_DEBUG('verbose', () => `[WebGPU] GpuDataManager.release(id=${id}), gpuDataId=${cachedData.gpuData.id}`);
|
|
|
|
this.storageCache.delete(id);
|
|
this.buffersPending.push(cachedData.gpuData.buffer);
|
|
// cachedData.gpuData.buffer.destroy();
|
|
|
|
const downloadingData = this.downloadCache.get(id);
|
|
if (downloadingData) {
|
|
this.downloadCache.delete(id);
|
|
}
|
|
|
|
return cachedData.originalSize;
|
|
}
|
|
|
|
async download(id: GpuDataId): Promise<ArrayBufferLike> {
|
|
const downloadData = this.downloadCache.get(id);
|
|
if (downloadData) {
|
|
return downloadData.data;
|
|
}
|
|
|
|
const cachedData = this.storageCache.get(id);
|
|
if (!cachedData) {
|
|
throw new Error('data does not exist');
|
|
}
|
|
|
|
const commandEncoder = this.backend.getCommandEncoder();
|
|
this.backend.endComputePass();
|
|
const gpuReadBuffer = this.backend.device.createBuffer(
|
|
// eslint-disable-next-line no-bitwise
|
|
{size: cachedData.originalSize, usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ});
|
|
commandEncoder.copyBufferToBuffer(
|
|
cachedData.gpuData.buffer /* source buffer */, 0 /* source offset */, gpuReadBuffer /* destination buffer */,
|
|
0 /* destination offset */, cachedData.originalSize /* size */
|
|
);
|
|
this.backend.flush();
|
|
|
|
const readDataPromise = new Promise<ArrayBuffer>((resolve) => {
|
|
gpuReadBuffer.mapAsync(GPUMapMode.READ).then(() => {
|
|
const data = gpuReadBuffer.getMappedRange().slice(0);
|
|
gpuReadBuffer.destroy();
|
|
resolve(data);
|
|
});
|
|
});
|
|
|
|
this.downloadCache.set(id, {data: readDataPromise});
|
|
|
|
return readDataPromise;
|
|
}
|
|
|
|
refreshPendingBuffers(): void {
|
|
for (const buffer of this.buffersForUploadingPending) {
|
|
buffer.destroy();
|
|
}
|
|
for (const buffer of this.buffersPending) {
|
|
buffer.destroy();
|
|
}
|
|
}
|
|
}
|
|
|
|
export const createGpuDataManager = (...args: ConstructorParameters<typeof GpuDataManagerImpl>): GpuDataManager =>
|
|
new GpuDataManagerImpl(...args);
|