Skip to Content
💡The WebNN Origin Trial is coming! Developers can sign up for trial keys to explore →

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

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

MethodDescription
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

syntax.js
createContext() createContext(options) createContext(gpuDevice)

Parameters

  • options optional

    An MLContextOptions dictionary describing the application’s preferences for the context. The resulting context has the context type "default".

  • gpuDevice

    A 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 a powerPreference of "default" and an accelerated value of true.

Return value

A Promise that fulfills with an MLContext object.

Exceptions

The returned promise is rejected with:

  • SecurityError DOMException

    The document is not allowed to use the webnn Permissions Policy feature.

  • NotSupportedError DOMException

    The 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.

MemberTypeDefaultDescription
powerPreferenceMLPowerPreference"default"The application’s preference related to power consumption.
acceleratedbooleantrueThe 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.

MLContextOptions is 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

ValueDescription
"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 codeClosest 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 deviceType for compatibility while the API is in development. New code should rely on powerPreference and accelerated only. See Browser Compatibility: Device Selection.

Examples

Creating a context with default options

default-context.js
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

power-preference.js
// 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

cpu-context.js
const context = await navigator.ml.createContext({ accelerated: false }); console.log(context.accelerated); // usually false

Creating a context from a WebGPU device

webgpu-context.js
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

SpecificationStatus
Web Neural Network API — ML interfaceCandidate 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.

See also

Last updated on