ML
实验性: 这是一项实验性技术。在生产环境中使用前,请仔细检查浏览器兼容性表格。
Web 神经网络(WebNN)API 的 ML 接口是创建 MLContext 对象的入口。ML 对象通过 navigator.ml 属性获得。
此特性仅在安全上下文 (HTTPS 或 localhost)中可用,并且在主线程和 Web Worker 中均可使用。
Web IDL
enum MLPowerPreference {
"default",
"high-performance",
"low-power"
};
dictionary MLContextOptions {
MLPowerPreference powerPreference = "default";
boolean accelerated = true;
};
[SecureContext, Exposed=(Window, Worker)]
interface ML {
Promise<MLContext> createContext(optional MLContextOptions options = {});
Promise<MLContext> createContext(GPUDevice gpuDevice);
};实例属性
无。
实例方法
| 方法 | 描述 |
|---|---|
createContext() | 返回一个 Promise,其兑现值为新的 MLContext,该上下文可通过 MLContextOptions 字典或 WebGPU GPUDevice 进行配置。 |
createContext()
ML 接口的 createContext() 方法用于创建 MLContext,它保存图编译和执行的全局状态。
语法
createContext()
createContext(options)
createContext(gpuDevice)参数
-
options可选一个
MLContextOptions字典,描述应用程序对上下文的偏好。所得上下文的上下文类型为"default"。 -
gpuDevice一个 WebGPU
GPUDevice。所得上下文的上下文类型为"webgpu",并与该设备关联,从而实现 WebNN 与 WebGPU 之间的互操作。以这种方式创建的上下文使用"default"的powerPreference以及值为true的accelerated。
返回值
一个 Promise,其兑现值为 MLContext 对象。
异常
返回的 Promise 会因以下异常而被拒绝:
-
SecurityErrorDOMException文档不被允许使用
webnn权限策略特性。 -
NotSupportedErrorDOMException用户代理无法创建所请求类型的上下文(例如,平台没有可用的后端,或不支持 WebGPU 互操作)。
字典和枚举
MLContextOptions
一个提示字典,用户代理使用它来选择底层计算设备和执行模式。这些是偏好而非要求:实现会在当前平台上选择最合适的可用匹配项。
| 成员 | 类型 | 默认值 | 描述 |
|---|---|---|---|
powerPreference | MLPowerPreference | "default" | 应用程序与功耗相关的偏好。 |
accelerated | boolean | true | 应用程序对大规模并行加速的偏好。为 true 时,平台会尝试使用可用的加速器,例如 GPU 或 NPU(同时也会考虑 powerPreference)。为 false 时,表示应用程序更倾向于 CPU 推理。 |
accelerated 的优先级低于 powerPreference。如果两者相互矛盾(例如 powerPreference: "high-performance" 与 accelerated: false 同时出现),实现会选择最合适的可用匹配项,例如高性能 CPU 模式,或者忽略 accelerated。
之后可以通过 MLContext.accelerated 属性检查上下文是否确实被加速。
MLContextOptions正在积极开发中,其设计可能会发生变化。工作组正在考虑针对回退设备、首选设备的有序列表、排除特定设备、错误处理以及量化算子的控制方式。背景信息请参阅设备选择说明文档 。
MLPowerPreference
| 值 | 描述 |
|---|---|
"default" | 由用户代理选择最合适的行为。 |
"high-performance" | 优先考虑执行速度而非功耗。 |
"low-power" | 优先考虑功耗而非执行速度等其他因素。 |
从 deviceType 迁移
规范的早期草案在 MLContextOptions 上定义了 MLDeviceType 枚举和 deviceType 成员("cpu"、"gpu"、"npu")。为了让上下文默认与设备无关,这些内容已从规范中移除。下列提示可以表达类似的意图,但最终的设备选择始终由实现决定(例如,在某些设备上 NPU 可能比 GPU 更快):
| 早期代码 | 最接近的当前提示 |
|---|---|
{ deviceType: 'cpu' } | { accelerated: false } |
{ deviceType: 'gpu' } | { powerPreference: 'high-performance' } (或传入 GPUDevice 以与 WebGPU 共享工作) |
{ deviceType: 'npu' } | { powerPreference: 'low-power' } |
在 API 开发期间,部分浏览器出于兼容性考虑可能仍接受
deviceType。新代码应仅依赖powerPreference和accelerated。参见浏览器兼容性:设备选择。
示例
使用默认选项创建上下文
try {
const context = await navigator.ml.createContext();
console.log('Accelerated:', context.accelerated);
} catch (error) {
console.error(`Failed to create an MLContext: ${error.name}: ${error.message}`);
}请求功耗偏好
// 优先考虑电池续航,例如用于常驻后台的背景模糊效果。
const lowPowerContext = await navigator.ml.createContext({
powerPreference: 'low-power',
});
// 优先考虑吞吐量,例如用于交互式图像生成。
const fastContext = await navigator.ml.createContext({
powerPreference: 'high-performance',
});倾向于 CPU 推理
const context = await navigator.ml.createContext({ accelerated: false });
console.log(context.accelerated); // 通常为 false从 WebGPU 设备创建上下文
const adapter = await navigator.gpu.requestAdapter();
const gpuDevice = await adapter.requestDevice();
try {
const context = await navigator.ml.createContext(gpuDevice);
// 使用 context.createExportableTensor(descriptor, gpuDevice) 创建的张量
// 可以通过 context.exportToGPU(tensor) 与 WebGPU 共享。
} catch (error) {
console.error('WebNN/WebGPU interop is not available:', error);
}规范
| 规范 | 状态 |
|---|---|
Web 神经网络 API — ML 接口 | 候选推荐草案 |
最新的编辑草案可在 webmachinelearning.github.io/webnn 查看。
浏览器兼容性
WebNN 正在积极开发中,不同浏览器、操作系统和硬件的支持情况各不相同。