Running custom machine learning models in the browser

Running your own model weights in the browser keeps user data on the device and removes server inference costs. Use this guide when your app ships its own model or model layers, such as a classifier head on top of embeddings, a small vision or audio model, or a custom neural network layer.

Choose how to run the model

  • WebGPU compute shaders (this guide): models and layers you define yourself, such as dense (fully connected) layers, small multilayer perceptrons, classifier heads, similarity scoring, or custom operators. You control the weight format, the precision, and the fallback.
  • An ML runtime with a WebGPU backend: standard architectures exported from a training framework, such as transformers, convolutional networks, or speech models with dozens of operator types. Writing and maintaining WGSL kernels for every operator may not be practical. See Alternative solutions.

To decide, ask: does the model use only a few operators that you can write as compute shaders? If yes, use WebGPU directly. If the model is a large standard architecture, use a runtime.

WebGPU provides compute shaders, general-purpose storage buffers, workgroup shared memory, and optional 16-bit floating-point (f16) shader arithmetic, which efficient neural network inference relies on.

Create the GPU device

Create the device only when the user asks for the feature.

Request a new adapter each time you create a device, including after device loss: an adapter can create only one device.

  • requestAdapter() resolves to null when no suitable GPU is available. requestDevice() can reject, for example when the requested features or limits aren't supported. Treat both cases as "use the fallback".
  • Request only the optional features and limits your app uses. A device enforces exactly the limits it was created with, so an app that requests only what it needs gets the same validation errors on every device, instead of depending on the limits of the development machine. Higher limits can also cost performance on some devices.
  • Request shader-f16 only when the app uses f16 and the adapter supports it. Requesting an unsupported feature makes requestDevice() reject.
  • The default maxStorageBufferBindingSize (128 MiB) and maxBufferSize (256 MiB) are enough for most apps. Request larger limits only when your data needs them, and no more than the adapter supports.
const LARGE_BUFFER_BYTES = 1024 * 1024 * 1024; // 1 GiB: set this to the largest buffer your app creates

// Returns null when the GPU path isn't available; use the fallback then.
async function createGpuDevice({ f16 = false, largeBuffers = false } = {}) {
  if (!('gpu' in navigator)) return null;
  try {
    const adapter = await navigator.gpu.requestAdapter(); // New adapter per device
    if (!adapter) return null;
    // Only request what's needed. The device enforces exactly the features and limits it
    // was created with, so exceeding a default limit fails on every device, not only on
    // users' devices with lower limits than the development machine.
    const supportsF16 = f16 && adapter.features.has('shader-f16');
    const requiredLimits = {};
    if (largeBuffers) {
      requiredLimits.maxBufferSize = Math.min(LARGE_BUFFER_BYTES, adapter.limits.maxBufferSize);
      requiredLimits.maxStorageBufferBindingSize =
        Math.min(LARGE_BUFFER_BYTES, adapter.limits.maxStorageBufferBindingSize);
    }
    const device = await adapter.requestDevice({
      requiredFeatures: supportsF16 ? ['shader-f16'] : [],
      requiredLimits,
    });
    return { device, supportsF16 };
  } catch {
    return null;
  }
}

If you need more resources, for example to process datasets as large as the GPU allows, request the adapter's maximums instead. Check the resulting device.limits before allocating, because the maximums differ between devices:

const device = await adapter.requestDevice({
  requiredLimits: {
    maxBufferSize: adapter.limits.maxBufferSize,
    maxStorageBufferBindingSize: adapter.limits.maxStorageBufferBindingSize,
  },
});

This guide stores weights as f16 when the GPU supports it, so it requests f16. Small models fit in the default buffer limits; pass largeBuffers: true only when the largest weight buffer is bigger than 128 MiB:

const gpu = await createGpuDevice({ f16: true, largeBuffers: false });
if (!gpu) return useCpuFallback();
const { device, supportsF16 } = gpu;

Choose f16 or f32 precision

  • f16 (half precision): half the memory and memory bandwidth of f32, and faster arithmetic on GPUs with native f16 support. Its range is about ±65,504 with roughly 3 decimal digits of precision.
  • f32 (single precision): about 7 decimal digits and a much wider range.

f16 requires the shader-f16 feature. Summing hundreds of f16 values loses accuracy, so accumulate long sums in f32 even when you store data as f16.

Recommendation:

  • Use f16 to store weights and inputs, which is enough for most inference.
  • Use f32 when the GPU doesn't support shader-f16, for values outside the f16 range or that need more precision, and for accumulating long sums.

If you publish weight files in both precisions, download the f16 file only when supportsF16 is true, which halves the download.

Load and cache model weights

Weight files can be tens to hundreds of megabytes. Choose when to download them:

  • On-demand loading: when the model powers a feature that only some users use, download the weights when the user first uses that feature.
  • Default loading: when the model is central to the app, start the download early, for example after the page has loaded or while the browser is idle, so the model is ready when the user needs it. Show progress for large files.

Store the weights with the Cache API so later visits don't download them again.

Upload weights to GPU buffers

Upload static weights once, and per inference call only write the new input.

writeBuffer() byte counts and storage buffer bindings must be multiples of 4 bytes. f32 values are always aligned, but an odd-length f16 array is not, so pad it by one element:

// Converts f32 values to the GPU storage format, padded to a multiple of 4 bytes.
function toGpuArray(float32Values, supportsF16) {
  if (!supportsF16) return float32Values;
  const length = float32Values.length + (float32Values.length % 2);
  if (typeof Float16Array !== 'function') {
    return toHalfBits(float32Values, length); // See "`Float16Array` fallback"
  }
  const half = new Float16Array(length);
  half.set(float32Values); // Converts each value to f16
  return half;
}

function createStorageBuffer(device, data) {
  const buffer = device.createBuffer({
    size: data.byteLength,
    usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST,
  });
  device.queue.writeBuffer(buffer, 0, data);
  return buffer;
}

Run the inference kernel

This dense layer computes output = ReLU(W · x + b). It reads f16 or f32 values through a type alias, and accumulates in f32, as recommended above. The uniform struct is padded to 16 bytes to match the 16-byte uniform buffer:

function createDenseLayerModule(device, supportsF16) {
  const header = supportsF16 ? 'enable f16;\nalias wtype = f16;' : 'alias wtype = f32;';
  return device.createShaderModule({
    code: `
      ${header}
      struct Dims { inputSize: u32, outputSize: u32, _pad0: u32, _pad1: u32 };

      @group(0) @binding(0) var<uniform> dims: Dims;
      @group(0) @binding(1) var<storage, read> weights: array<wtype>;
      @group(0) @binding(2) var<storage, read> inputVec: array<wtype>;
      @group(0) @binding(3) var<storage, read> biasVec: array<wtype>;
      @group(0) @binding(4) var<storage, read_write> outputVec: array<f32>;

      @compute @workgroup_size(64)
      fn main(@builtin(global_invocation_id) id: vec3u) {
        let row = id.x;
        if (row >= dims.outputSize) { return; } // Guard the last partial workgroup
        var sum = f32(biasVec[row]);
        let rowOffset = row * dims.inputSize;
        for (var col = 0u; col < dims.inputSize; col++) {
          sum += f32(weights[rowOffset + col]) * f32(inputVec[col]);
        }
        outputVec[row] = max(0.0, sum);
      }
    `,
  });
}

// Uniform buffer: [inputSize, outputSize, padding, padding]
const dimsBuffer = device.createBuffer({ size: 16, usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST });
device.queue.writeBuffer(dimsBuffer, 0, new Uint32Array([inputSize, outputSize, 0, 0]));

This kernel is written for the first layer of a network. For later layers, read inputVec as f32, because each layer writes f32 output. Skip ReLU on the output layer, for example with a relu flag in Dims and select(sum, max(0.0, sum), dims.relu == 1u).

Dispatch Math.ceil(outputSize / 64) workgroups and copy outputVec to a MAP_READ staging buffer. Wrap encoder.finish() and submit() in a 'validation' error scope, as shown in Handle GPU errors and device loss, and throw if popErrorScope() reports an error. Otherwise mapAsync() resolves with zeroed or stale data, and the caller never switches to the CPU fallback. Then read the result with await stagingBuffer.mapAsync(GPUMapMode.READ).

This kernel computes one output row per thread. For large matrix multiplications, tile the inputs into var<workgroup> shared memory so that each workgroup reuses loaded values.

Run inference off the main thread

Run weight loading and inference in a dedicated module Worker so input, scrolling, and rendering stay responsive. WebGPU and the Cache API are available in workers. Load the model on the first request rather than when the worker starts:

// main.js
const worker = new Worker(new URL('./inference-worker.js', import.meta.url), { type: 'module' });
worker.addEventListener('message', ({ data }) => renderResult(data.output));
runButton.addEventListener('click', () => worker.postMessage({ type: 'infer', input }));
// inference-worker.js
let modelPromise = null; // Weights, plus the GPU resources or null for the CPU fallback
let queue = Promise.resolve();

self.addEventListener('message', ({ data }) => {
  if (data.type !== 'infer') return;
  // Run one inference at a time: the staging buffer can't be mapped twice at once.
  queue = queue.then(() => infer(data.input));
});

async function infer(input) {
  modelPromise ??= loadModel(); // Weights, device, and pipeline: created once, on demand
  try {
    const model = await modelPromise;
    let output = null;
    if (model.gpu) {
      try {
        output = await model.gpu.run(input);
      } catch {
        model.gpu.device.destroy(); // Release GPU memory, and stop using the GPU path
        model.gpu = null;
      }
    }
    output ??= runOnCpu(model.weights, input); // denseLayerOnCpu() for each layer
    self.postMessage({ type: 'result', output });
  } catch (err) {
    modelPromise = null; // Loading the weights failed: allow a retry
    self.postMessage({ type: 'error', message: err.message });
  }
}

loadModel() returns gpu: null when the GPU path isn't available, so a failed GPU setup doesn't prevent CPU inference.

Handle GPU errors and device loss

GPU setup and execution can fail after detection succeeds. Most WebGPU calls don't throw: createBuffer(), createBindGroup(), encoder commands such as dispatchWorkgroups() or draw(), and submit() report validation and out-of-memory errors to error scopes, or to the device's uncapturederror event, and return objects that are silently invalid. An invalid submit is dropped, and mapAsync() can still resolve with stale or zeroed data. One exception: device.queue.writeBuffer() throws an OperationError when the number of bytes to write isn't a multiple of 4, which is why f16 data needs padding. In each case, switch to the fallback (a CPU implementation for computations, or another renderer for graphics) instead of using the result:

  • Setup fails: createGpuDevice() returns null, createComputePipelineAsync() or createRenderPipelineAsync() rejects, or an error scope around buffer and bind group creation reports an error.
  • Data exceeds the device limits: buffers larger than maxBufferSize, or bindings larger than maxStorageBufferBindingSize, produce a validation error. Check sizes before allocating.
  • The GPU runs out of memory: allocation failures are reported as a GPUOutOfMemoryError through an 'out-of-memory' error scope.
  • A run fails: wrap each run's encoder.finish() and submit() in a 'validation' error scope, because invalid encoder commands are reported when the encoder finishes. Discard the result if the scope reports an error. mapAsync() rejects if the device is lost, and popErrorScope() then resolves to null.
  • An error escapes every scope: it's reported to the uncapturederror event.
  • The device is lost (driver reset or GPU process crash): device.lost resolves. Switch to the fallback, or create a new device with a new adapter.
// Setup: check limits, then capture allocation and validation errors.
const maxBytes = Math.min(device.limits.maxBufferSize, device.limits.maxStorageBufferBindingSize);
if (data.byteLength > maxBytes) return useFallback();

device.pushErrorScope('out-of-memory');
device.pushErrorScope('validation');
const dataBuffer = device.createBuffer({
  size: data.byteLength,
  usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST,
});
const validationError = await device.popErrorScope(); // Scopes pop in reverse order
const oomError = await device.popErrorScope();
if (validationError || oomError) return useFallback();
device.queue.writeBuffer(dataBuffer, 0, data); // Write only to a buffer known to be valid

// Each run: an invalid command buffer is dropped without an exception.
device.pushErrorScope('validation');
device.queue.submit([encoder.finish()]);
if (await device.popErrorScope()) return useFallback();

// Errors outside any error scope, and device loss. One failure can trigger several of
// these (a single invalid pass reports errors from both finish() and submit()), so react
// only while this device is still the active one.
device.addEventListener('uncapturederror', () => {
  if (gpu?.device === device) useFallback();
});
device.lost.then((info) => {
  if (info.reason !== 'destroyed' && gpu?.device === device) useFallback();
});

In this snippet, gpu holds the active GPU resources after setup succeeds. useFallback() switches to the fallback, destroys the device, and sets gpu to null. Make it safe to call more than once, for example with a flag that records that the fallback is already active.

Verify before finishing

Test the result. Check each of these, and fix and re-test any that fail:

  • No WebGPU: with WebGPU unavailable, or with requestAdapter() resolving to null, inference still produces results on the CPU.
  • Precision: f16 storage is used only when shader-f16 is available, and odd-length f16 arrays are padded.
  • Responsiveness: the page keeps responding to input while weights load and inference runs.
  • On demand: no weights download before the user asks for the feature.
  • Caching: reloading the page doesn't download the weights again.

Alternative solutions

For standard model architectures, an ML runtime may be more practical than hand-written kernels. Several open-source runtimes run models in the browser with a WebGPU backend and a WebAssembly backend, for example MediaPipe, ONNX Runtime Web, TensorFlow.js, Transformers.js, and WebLLM. Choose based on the model formats and tasks your project needs.

When you use a runtime, apply the same practices as the native path:

  • Select the WebGPU backend only after requestAdapter() resolves to a non-null adapter, and select the WebAssembly backend otherwise.
  • Load f16 or q4f16 model variants only when shader-f16 is available.
  • Run the runtime in a Web Worker, load the model on demand, and cache model files.
  • If creating a WebGPU session or running inference fails, recreate it with the WebAssembly backend.

Fallback strategies

WebGPU fallback

When 'gpu' in navigator is false, requestAdapter() resolves to null, or GPU setup fails, run the same layers on the CPU in the Worker. For larger models, compile the CPU path to WebAssembly with SIMD. The CPU path produces comparable results.

function denseLayerOnCpu(weights, inputVec, biasVec, inputSize, outputSize) {
  const out = new Float32Array(outputSize);
  for (let row = 0; row < outputSize; row++) {
    let sum = biasVec[row];
    for (let col = 0; col < inputSize; col++) sum += weights[row * inputSize + col] * inputVec[col];
    out[row] = Math.max(0, sum);
  }
  return out;
}

shader-f16 fallback

When adapter.features.has('shader-f16') is false, compile the kernel with alias wtype = f32; and upload f32 data, as shown above.

Float16Array fallback

If your Baseline target doesn't include Float16Array, convert f32 values to 16-bit bit patterns in a Uint16Array and upload that instead:

// Converts f32 values to IEEE 754 half-precision bits, padded to a multiple of 4 bytes.
// Truncates the mantissa and flushes values too small for f16 to zero, which is
// acceptable for most GPU data. Unlike Float16Array, NaN becomes Infinity.
function toHalfBits(float32Values, length = float32Values.length + (float32Values.length % 2)) {
  const bits = new Uint16Array(length);
  const u32 = new Uint32Array(new Float32Array(float32Values).buffer);
  for (let i = 0; i < u32.length; i++) {
    const x = u32[i];
    const sign = (x >>> 16) & 0x8000;
    const exp = ((x >>> 23) & 0xff) - 112; // Re-bias the exponent: 127 - 15
    if (exp <= 0) bits[i] = sign; // Too small: signed zero
    else if (exp >= 31) bits[i] = sign | 0x7c00; // Too large: infinity
    else bits[i] = sign | (exp << 10) | ((x >>> 13) & 0x3ff);
  }
  return bits;
}

Module workers

If your Baseline target doesn't include module workers, build the worker as a classic script, for example with your bundler's worker output format, and create it without { type: 'module' }. Inside a classic worker, load dependencies with importScripts() instead of import.