-
Notifications
You must be signed in to change notification settings - Fork 18
/
context.ts
104 lines (87 loc) 路 2.48 KB
/
context.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
import '@tensorflow/tfjs-backend-webgl';
import '@tensorflow/tfjs-backend-webgpu';
import '@tensorflow/tfjs-backend-cpu';
import * as wasm from '@tensorflow/tfjs-backend-wasm';
import * as tf from '@tensorflow/tfjs-core';
import { MLComputeResult, MLGraph, MLNamedArrayBufferViews } from './graph';
import * as utils from './utils';
/** @internal */
export enum MLContextType {
'default' = 'default',
'webgpu' = 'webgpu'
}
/**
* [spec](https://webmachinelearning.github.io/webnn/#enumdef-mldevicetype)
*/
export enum MLDeviceType {
'cpu' = 'cpu',
'gpu' = 'gpu'
}
/**
* [spec](https://webmachinelearning.github.io/webnn/#enumdef-mlpowerpreference)
*/
export enum MLPowerPreference {
'default' = 'default',
'high-performance' = 'high-performance',
'low-power' = 'low-power'
}
/**
* [spec](https://webmachinelearning.github.io/webnn/#dictdef-mlcontextoptions)
*/
export interface MLContextOptions {
deviceType?: MLDeviceType;
powerPreference?: MLPowerPreference;
}
/**
* [API spec](https://webmachinelearning.github.io/webnn/#api-mlcontext)
*/
export class MLContext {
private options_: MLContextOptions;
private type_: MLContextType;
/** @internal */
// eslint-disable-next-line @typescript-eslint/no-empty-function
constructor(options: MLContextOptions = {}) {
utils.assert(options instanceof Object, 'Invalid options.');
if (options.deviceType !== undefined) {
utils.assert(
options.deviceType in MLDeviceType,
'Invalid device type.');
}
if (options.powerPreference !== undefined) {
utils.assert(
options.powerPreference in MLPowerPreference,
'Invalid power preference.');
}
this.options_ = options;
this.type_ = MLContextType.default;
}
/** @internal */
get options(): MLContextOptions {
return this.options_;
}
/** @internal */
get type(): MLContextType {
return this.type_;
}
/**
* [spec](https://webmachinelearning.github.io/webnn/#api-mlcontext-compute)
*/
async compute(
graph: MLGraph,
inputs: MLNamedArrayBufferViews,
outputs: MLNamedArrayBufferViews): Promise<MLComputeResult> {
const result = await graph.compute(inputs, outputs);
return result;
}
/** @internal */
// Expose tf interfance for setting backend.
get tf(): unknown {
return tf;
}
/** @internal */
// Expose wasm interface for supporting configure threads for wasm backend.
// wasm.setThreadsCount(n)
get wasm(): unknown {
return wasm;
}
}