ML
Experimental: This is an experimental technology. Check the browser compatibility table carefully before using it in production.
The ML interface of the Web Neural Network (WebNN) API is the entry point for creating MLContext objects. An ML object is obtained through the navigator.ml property.
This feature is available only in secure contexts (HTTPS or localhost), and is available in both the main thread and Web Workers .
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);
};Instance properties
None.
Instance methods
| Method | Description |
|---|---|
createContext() | Returns a Promise that resolves to a new MLContext, configured either from an MLContextOptions dictionary or from a WebGPU GPUDevice. |
createContext()
The createContext() method of the ML interface creates an MLContext, which holds the global state for graph compilation and execution.
Syntax
createContext()
createContext(options)
createContext(gpuDevice)Parameters
-
optionsoptionalAn
MLContextOptionsdictionary describing the application’s preferences for the context. The resulting context has the context type"default". -
gpuDeviceA WebGPU
GPUDevice. The resulting context has the context type"webgpu"and is associated with that device, which enables interoperability between WebNN and WebGPU. A context created this way uses apowerPreferenceof"default"and anacceleratedvalue oftrue.
Return value
A Promise that fulfills with an MLContext object.
Exceptions
The returned promise is rejected with:
-
SecurityErrorDOMExceptionThe document is not allowed to use the
webnnPermissions Policy feature. -
NotSupportedErrorDOMExceptionThe user agent cannot create a context of the requested type (for example, the platform has no usable backend, or WebGPU interop is not supported).
Dictionaries and enumerations
MLContextOptions
A dictionary of hints that the user agent uses to select the underlying compute device and execution mode. These are preferences, not requirements: the implementation chooses the best available match on the current platform.
| Member | Type | Default | Description |
|---|---|---|---|
powerPreference | MLPowerPreference | "default" | The application’s preference related to power consumption. |
accelerated | boolean | true | The application’s preference for massively parallel acceleration. When true, the platform attempts to use an available accelerator such as a GPU or NPU (also taking powerPreference into account). When false, the application indicates that it prefers CPU inference. |
accelerated has lower priority than powerPreference. If the two contradict each other (for example powerPreference: "high-performance" together with accelerated: false), the implementation picks the best available match, for instance a high-performance CPU mode, or ignores accelerated.
Whether a context is actually accelerated can be checked afterwards with the MLContext.accelerated property.
MLContextOptionsis under active development and its design may change. The Working Group is considering controls for fallback devices, an ordered list of preferred devices, excluding specific devices, error handling, and quantized operators. See the device selection explainer for background.
MLPowerPreference
| Value | Description |
|---|---|
"default" | Lets the user agent select the most suitable behavior. |
"high-performance" | Prioritizes execution speed over power consumption. |
"low-power" | Prioritizes power consumption over other considerations such as execution speed. |
Migrating from deviceType
Earlier drafts of the specification defined an MLDeviceType enum and a deviceType member ("cpu", "gpu", "npu") on MLContextOptions. These have been removed from the specification to make contexts device-agnostic by default. The following hints express similar intent, but the final device choice is always made by the implementation (for example, an NPU may be faster than the GPU on some devices):
| Earlier code | Closest current hint |
|---|---|
{ deviceType: 'cpu' } | { accelerated: false } |
{ deviceType: 'gpu' } | { powerPreference: 'high-performance' } (or pass a GPUDevice to share work with WebGPU) |
{ deviceType: 'npu' } | { powerPreference: 'low-power' } |
Some browsers may still accept
deviceTypefor compatibility while the API is in development. New code should rely onpowerPreferenceandacceleratedonly. See Browser Compatibility: Device Selection.
Examples
Creating a context with default options
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}`);
}Requesting a power preference
// Favor battery life, e.g. for an always-on background-blur effect.
const lowPowerContext = await navigator.ml.createContext({
powerPreference: 'low-power',
});
// Favor throughput, e.g. for interactive image generation.
const fastContext = await navigator.ml.createContext({
powerPreference: 'high-performance',
});Preferring CPU inference
const context = await navigator.ml.createContext({ accelerated: false });
console.log(context.accelerated); // usually falseCreating a context from a WebGPU device
const adapter = await navigator.gpu.requestAdapter();
const gpuDevice = await adapter.requestDevice();
try {
const context = await navigator.ml.createContext(gpuDevice);
// Tensors created with context.createExportableTensor(descriptor, gpuDevice)
// can be shared with WebGPU via context.exportToGPU(tensor).
} catch (error) {
console.error('WebNN/WebGPU interop is not available:', error);
}Specifications
| Specification | Status |
|---|---|
Web Neural Network API — ML interface | Candidate Recommendation Draft |
The latest Editor’s Draft is available at webmachinelearning.github.io/webnn .
Browser compatibility
WebNN is under active development and support varies across browsers, operating systems, and hardware.
See Browser Compatibility: WebNN APIs and Device Selection.