-
Notifications
You must be signed in to change notification settings - Fork 3.2k
/
Copy pathwasm-factory.ts
251 lines (218 loc) · 8.29 KB
/
wasm-factory.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
import { Env } from 'onnxruntime-common';
import type { OrtWasmModule } from './wasm-types';
import { importWasmModule, inferWasmPathPrefixFromScriptSrc } from './wasm-utils-import';
let wasm: OrtWasmModule | undefined;
let initialized = false;
let initializing = false;
let aborted = false;
const isMultiThreadSupported = (): boolean => {
// If 'SharedArrayBuffer' is not available, WebAssembly threads will not work.
if (typeof SharedArrayBuffer === 'undefined') {
return false;
}
try {
// Test for transferability of SABs (for browsers. needed for Firefox)
// https://groups.google.com/forum/#!msg/mozilla.dev.platform/IHkBZlHETpA/dwsMNchWEQAJ
if (typeof MessageChannel !== 'undefined') {
new MessageChannel().port1.postMessage(new SharedArrayBuffer(1));
}
// Test for WebAssembly threads capability (for both browsers and Node.js)
// This typed array is a WebAssembly program containing threaded instructions.
return WebAssembly.validate(
new Uint8Array([
0, 97, 115, 109, 1, 0, 0, 0, 1, 4, 1, 96, 0, 0, 3, 2, 1, 0, 5, 4, 1, 3, 1, 1, 10, 11, 1, 9, 0, 65, 0, 254, 16,
2, 0, 26, 11,
]),
);
} catch (e) {
return false;
}
};
const isSimdSupported = (): boolean => {
try {
// Test for WebAssembly SIMD capability (for both browsers and Node.js)
// This typed array is a WebAssembly program containing SIMD instructions.
// The binary data is generated from the following code by wat2wasm:
//
// (module
// (type $t0 (func))
// (func $f0 (type $t0)
// (drop
// (i32x4.dot_i16x8_s
// (i8x16.splat
// (i32.const 0))
// (v128.const i32x4 0x00000000 0x00000000 0x00000000 0x00000000)))))
return WebAssembly.validate(
new Uint8Array([
0, 97, 115, 109, 1, 0, 0, 0, 1, 4, 1, 96, 0, 0, 3, 2, 1, 0, 10, 30, 1, 28, 0, 65, 0, 253, 15, 253, 12, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 253, 186, 1, 26, 11,
]),
);
} catch (e) {
return false;
}
};
const isRelaxedSimdSupported = (): boolean => {
try {
// Test for WebAssembly Relaxed SIMD capability (for both browsers and Node.js)
// This typed array is a WebAssembly program containing Relaxed SIMD instructions.
// The binary data is generated from the following code by wat2wasm:
// (module
// (func (result v128)
// i32.const 1
// i8x16.splat
// i32.const 2
// i8x16.splat
// i32.const 3
// i8x16.splat
// i32x4.relaxed_dot_i8x16_i7x16_add_s
// )
// )
return WebAssembly.validate(
new Uint8Array([
0, 97, 115, 109, 1, 0, 0, 0, 1, 5, 1, 96, 0, 1, 123, 3, 2, 1, 0, 10, 19, 1, 17, 0, 65, 1, 253, 15, 65, 2, 253,
15, 65, 3, 253, 15, 253, 147, 2, 11,
]),
);
} catch (e) {
return false;
}
};
export const initializeWebAssembly = async (flags: Env.WebAssemblyFlags): Promise<void> => {
if (initialized) {
return Promise.resolve();
}
if (initializing) {
throw new Error("multiple calls to 'initializeWebAssembly()' detected.");
}
if (aborted) {
throw new Error("previous call to 'initializeWebAssembly()' failed.");
}
initializing = true;
// wasm flags are already initialized
const timeout = flags.initTimeout!;
let numThreads = flags.numThreads!;
// ensure SIMD is supported
if (flags.simd === false) {
// skip SIMD feature checking as it is disabled explicitly by user
} else if (flags.simd === 'relaxed') {
// check if relaxed SIMD is supported
if (!isRelaxedSimdSupported()) {
throw new Error('Relaxed WebAssembly SIMD is not supported in the current environment.');
}
} else if (!isSimdSupported()) {
throw new Error('WebAssembly SIMD is not supported in the current environment.');
}
// check if multi-threading is supported
const multiThreadSupported = isMultiThreadSupported();
if (numThreads > 1 && !multiThreadSupported) {
if (typeof self !== 'undefined' && !self.crossOriginIsolated) {
// eslint-disable-next-line no-console
console.warn(
'env.wasm.numThreads is set to ' +
numThreads +
', but this will not work unless you enable crossOriginIsolated mode. ' +
'See https://web.dev/cross-origin-isolation-guide/ for more info.',
);
}
// eslint-disable-next-line no-console
console.warn(
'WebAssembly multi-threading is not supported in the current environment. ' + 'Falling back to single-threading.',
);
// set flags.numThreads to 1 so that OrtInit() will not create a global thread pool.
flags.numThreads = numThreads = 1;
}
const wasmPaths = flags.wasmPaths;
const wasmPrefixOverride = typeof wasmPaths === 'string' ? wasmPaths : undefined;
const mjsPathOverrideFlag = (wasmPaths as Env.WasmFilePaths)?.mjs;
const mjsPathOverride = (mjsPathOverrideFlag as URL)?.href ?? mjsPathOverrideFlag;
const wasmPathOverrideFlag = (wasmPaths as Env.WasmFilePaths)?.wasm;
const wasmPathOverride = (wasmPathOverrideFlag as URL)?.href ?? wasmPathOverrideFlag;
const wasmBinaryOverride = flags.wasmBinary;
const [objectUrl, ortWasmFactory] = await importWasmModule(mjsPathOverride, wasmPrefixOverride, numThreads > 1);
let isTimeout = false;
const tasks: Array<Promise<void>> = [];
// promise for timeout
if (timeout > 0) {
tasks.push(
new Promise((resolve) => {
setTimeout(() => {
isTimeout = true;
resolve();
}, timeout);
}),
);
}
// promise for module initialization
tasks.push(
new Promise((resolve, reject) => {
const config: Partial<OrtWasmModule> = {
/**
* The number of threads. WebAssembly will create (Module.numThreads - 1) workers. If it is 1, no worker will be
* created.
*/
numThreads,
};
if (wasmBinaryOverride) {
// Set a custom buffer which contains the WebAssembly binary. This will skip the wasm file fetching.
config.wasmBinary = wasmBinaryOverride;
} else if (wasmPathOverride || wasmPrefixOverride) {
// A callback function to locate the WebAssembly file. The function should return the full path of the file.
//
// Since Emscripten 3.1.58, this function is only called for the .wasm file.
config.locateFile = (fileName) => wasmPathOverride ?? wasmPrefixOverride + fileName;
} else if (mjsPathOverride && mjsPathOverride.indexOf('blob:') !== 0) {
// if mjs path is specified, use it as the base path for the .wasm file.
config.locateFile = (fileName) => new URL(fileName, mjsPathOverride).href;
} else if (objectUrl) {
const inferredWasmPathPrefix = inferWasmPathPrefixFromScriptSrc();
if (inferredWasmPathPrefix) {
// if the wasm module is preloaded, use the inferred wasm path as the base path for the .wasm file.
config.locateFile = (fileName) => inferredWasmPathPrefix + fileName;
}
}
ortWasmFactory(config).then(
// wasm module initialized successfully
(module) => {
initializing = false;
initialized = true;
wasm = module;
resolve();
if (objectUrl) {
URL.revokeObjectURL(objectUrl);
}
},
// wasm module failed to initialize
(what) => {
initializing = false;
aborted = true;
reject(what);
},
);
}),
);
await Promise.race(tasks);
if (isTimeout) {
throw new Error(`WebAssembly backend initializing failed due to timeout: ${timeout}ms`);
}
};
export const getInstance = (): OrtWasmModule => {
if (initialized && wasm) {
return wasm;
}
throw new Error('WebAssembly is not initialized yet.');
};
export const dispose = (): void => {
if (initialized && !initializing && !aborted) {
// TODO: currently "PThread.terminateAllThreads()" is not exposed in the wasm module.
// And this function is not yet called by any code.
// If it is needed in the future, we should expose it in the wasm module and uncomment the following line.
// wasm?.PThread?.terminateAllThreads();
wasm = undefined;
initializing = false;
initialized = false;
aborted = true;
}
};