WebGPU

Editor’s Draft,

More details about this document
This version:
https://gpuweb.github.io/gpuweb/
https://github.com/gpuweb/gpuweb/blob/908844bb2a4d3575344534f578029addb48b656e/spec/index.bs
Latest published version:
https://www.w3.org/TR/webgpu/
Feedback:
[email protected] with subject line “[webgpu] … message topic …” (archives)
GitHub
Editors:
(Google)
(Google)
(Mozilla)
Former Editors:
(Apple Inc.)
(Mozilla)
(Apple Inc.)
Participate:
File an issue (open issues)
Test Suite:
WebGPU CTS

Abstract

WebGPU exposes an API for performing operations, such as rendering and computation, on a Graphics Processing Unit.

Status of this document

This section describes the status of this document at the time of its publication. A list of current W3C publications and the latest revision of this technical report can be found in the W3C standards and drafts index.

Feedback and comments on this specification are welcome. GitHub Issues are preferred for discussion on this specification. Alternatively, you can send comments to the GPU for the Web Working Group’s mailing-list, [email protected] (archives). This draft highlights some of the pending issues that are still to be discussed in the working group. No decision has been taken on the outcome of these issues including whether they are valid.

This document was published by the GPU for the Web Working Group as an Editor’s Draft.

The group expects to demonstrate implementation of each feature in at least two deployed browsers on top of modern GPU system APIs. The test suite will be used to build an implementation report.

This document is maintained and updated at any time. Some parts of this document are work in progress.

This document was produced by a group operating under the W3C Patent Policy. W3C maintains a public list of any patent disclosures made in connection with the deliverables of the group; that page also includes instructions for disclosing a patent. An individual who has actual knowledge of a patent that the individual believes contains Essential Claim(s) must disclose the information in accordance with section 6 of the W3C Patent Policy.

This document is governed by the 18 August 2025 W3C Process Document.

1. Introduction

This section is non-normative.

Graphics Processing Units, or GPUs for short, have been essential in enabling rich rendering and computational applications in personal computing. WebGPU is an API that exposes the capabilities of GPU hardware for the Web. The API is designed from the ground up to efficiently map to (post-2014) native GPU APIs. WebGPU is not related to WebGL and does not explicitly target OpenGL ES.

WebGPU sees physical GPU hardware as GPUAdapters. It provides a connection to an adapter via GPUDevice, which manages resources, and the device’s GPUQueues, which execute commands. GPUDevice may have its own memory with high-speed access to the processing units. GPUBuffer and GPUTexture are the physical resources backed by GPU memory. GPUCommandBuffer and GPURenderBundle are containers for user-recorded commands. GPUShaderModule contains shader code. The other resources, such as GPUSampler or GPUBindGroup, configure the way physical resources are used by the GPU.

GPUs execute commands encoded in GPUCommandBuffers by feeding data through a pipeline, which is a mix of fixed-function and programmable stages. Programmable stages execute shaders, which are special programs designed to run on GPU hardware. Most of the state of a pipeline is defined by a GPURenderPipeline or a GPUComputePipeline object. The state not included in these pipeline objects is set during encoding with commands, such as beginRenderPass() or setBlendConstant().

2. Malicious use considerations

This section is non-normative. It describes the risks associated with exposing this API on the Web.

2.1. Security Considerations

The security requirements for WebGPU are the same as ever for the web, and are likewise non-negotiable. The general approach is strictly validating all the commands before they reach GPU, ensuring that a page can only work with its own data.

2.1.1. CPU-based undefined behavior

A WebGPU implementation translates the workloads issued by the user into API commands specific to the target platform. Native APIs specify the valid usage for the commands (for example, see vkCreateDescriptorSetLayout) and generally don’t guarantee any outcome if the valid usage rules are not followed. This is called "undefined behavior", and it can be exploited by an attacker to access memory they don’t own, or force the driver to execute arbitrary code.

In order to disallow insecure usage, the range of allowed WebGPU behaviors is defined for any input. An implementation has to validate all the input from the user and only reach the driver with the valid workloads. This document specifies all the error conditions and handling semantics. For example, specifying the same buffer with intersecting ranges in both "source" and "destination" of copyBufferToBuffer() results in GPUCommandEncoder generating an error, and no other operation occurring.

See § 22 Errors & Debugging for more information about error handling.

2.1.2. GPU-based undefined behavior

WebGPU shaders are executed by the compute units inside GPU hardware. In native APIs, some of the shader instructions may result in undefined behavior on the GPU. In order to address that, the shader instruction set and its defined behaviors are strictly defined by WebGPU. When a shader is provided to createShaderModule(), the WebGPU implementation has to validate it before doing any translation (to platform-specific shaders) or transformation passes.

2.1.3. Uninitialized data

Generally, allocating new memory may expose the leftover data of other applications running on the system. In order to address that, WebGPU conceptually initializes all the resources to zero, although in practice an implementation may skip this step if it sees the developer initializing the contents manually. This includes variables and shared workgroup memory inside shaders.

The precise mechanism of clearing the workgroup memory can differ between platforms. If the native API does not provide facilities to clear it, the WebGPU implementation transforms the compute shader to first do a clear across all invocations, synchronize them, and continue executing developer’s code.

NOTE:
The initialization status of a resource used in a queue operation can only be known when the operation is enqueued (not when it is encoded into a command buffer, for example). Therefore, some implementations will require an unoptimized late-clear at enqueue time (e.g. clearing a texture, rather than changing GPULoadOp "load" to "clear").

As a result, all implementations should issue a developer console warning about this potential performance penalty, even if there is no penalty in that implementation.

2.1.4. Out-of-bounds access in shaders

Shaders can access physical resources either directly (for example, as a "uniform" GPUBufferBinding), or via texture units, which are fixed-function hardware blocks that handle texture coordinate conversions. Validation in the WebGPU API can only guarantee that all the inputs to the shader are provided and they have the correct usage and types. The WebGPU API can not guarantee that the data is accessed within bounds if the texture units are not involved.

In order to prevent the shaders from accessing GPU memory an application doesn’t own, the WebGPU implementation may enable a special mode (called "robust buffer access") in the driver that guarantees that the access is limited to buffer bounds.

Alternatively, an implementation may transform the shader code by inserting manual bounds checks. When this path is taken, the out-of-bound checks only apply to array indexing. They aren’t needed for plain field access of shader structures due to the minBindingSize validation on the host side.

If the shader attempts to load data outside of physical resource bounds, the implementation is allowed to:

  1. return a value at a different location within the resource bounds

  2. return a value vector of "(0, 0, 0, X)" with any "X"

  3. partially discard the draw or dispatch call

If the shader attempts to write data outside of physical resource bounds, the implementation is allowed to:

  1. write the value to a different location within the resource bounds

  2. discard the write operation

  3. partially discard the draw or dispatch call

2.1.5. Invalid data

When uploading floating-point data from CPU to GPU, or generating it on the GPU, we may end up with a binary representation that doesn’t correspond to a valid number, such as infinity or NaN (not-a-number). The GPU behavior in this case is subject to the accuracy of the GPU hardware implementation of the IEEE-754 standard. WebGPU guarantees that introducing invalid floating-point numbers would only affect the results of arithmetic computations and will not have other side effects.

2.1.6. Driver bugs

GPU drivers are subject to bugs like any other software. If a bug occurs, an attacker could possibly exploit the incorrect behavior of the driver to get access to unprivileged data. In order to reduce the risk, the WebGPU working group will coordinate with GPU vendors to integrate the WebGPU Conformance Test Suite (CTS) as part of their driver testing process, like it was done for WebGL. WebGPU implementations are expected to have workarounds for some of the discovered bugs, and disable WebGPU on drivers with known bugs that can’t be worked around.

2.1.7. Timing attacks

2.1.7.1. Content-timeline timing

WebGPU does not expose new states to JavaScript (the content timeline) which are shared between agents in an agent cluster. Content timeline states such as [[mapping]] only change during explicit content timeline tasks, like in plain JavaScript.

2.1.7.2. Device/queue-timeline timing

Writable storage buffers and other cross-invocation communication may be usable to construct high-precision timers on the queue timeline.

The optional "timestamp-query" feature also provides high precision timing of GPU operations. To mitigate security and privacy concerns, the timing query values are aligned to a lower precision: see current queue timestamp. Note in particular:

2.1.8. Row hammer attacks

Row hammer is a class of attacks that exploit the leaking of states in DRAM cells. It could be used on GPU. WebGPU does not have any specific mitigations in place, and relies on platform-level solutions, such as reduced memory refresh intervals.

2.1.9. Denial of service

WebGPU applications have access to GPU memory and compute units. A WebGPU implementation may limit the available GPU memory to an application, in order to keep other applications responsive. For GPU processing time, a WebGPU implementation may set up "watchdog" timer that makes sure an application doesn’t cause GPU unresponsiveness for more than a few seconds. These measures are similar to those used in WebGL.

2.1.10. Workload identification

WebGPU provides access to constrained global resources shared between different programs (and web pages) running on the same machine. An application can try to indirectly probe how constrained these global resources are, in order to reason about workloads performed by other open web pages, based on the patterns of usage of these shared resources. These issues are generally analogous to issues with Javascript, such as system memory and CPU execution throughput. WebGPU does not provide any additional mitigations for this.

2.1.11. Memory resources

WebGPU exposes fallible allocations from machine-global memory heaps, such as VRAM. This allows for probing the size of the system’s remaining available memory (for a given heap type) by attempting to allocate and watching for allocation failures.

GPUs internally have one or more (typically only two) heaps of memory shared by all running applications. When a heap is depleted, WebGPU would fail to create a resource. This is observable, which may allow a malicious application to guess what heaps are used by other applications, and how much they allocate from them.

2.1.12. Computation resources

If one site uses WebGPU at the same time as another, it may observe the increase in time it takes to process some work. For example, if a site constantly submits compute workloads and tracks completion of work on the queue, it may observe that something else also started using the GPU.

A GPU has many parts that can be tested independently, such as the arithmetic units, texture sampling units, atomic units, etc. A malicious application may sense when some of these units are stressed, and attempt to guess the workload of another application by analyzing the stress patterns. This is analogous to the realities of CPU execution of Javascript.

2.1.13. Abuse of capabilities

Malicious sites could abuse the capabilities exposed by WebGPU to run computations that don’t benefit the user or their experience and instead only benefit the site. Examples would be hidden crypto-mining, password cracking or rainbow tables computations.

It is not possible to guard against these types of uses of the API because the browser is not able to distinguish between valid workloads and abusive workloads. This is a general problem with all general-purpose computation capabilities on the Web: JavaScript, WebAssembly or WebGL. WebGPU only makes some workloads easier to implement, or slightly more efficient to run than using WebGL.

To mitigate this form of abuse, browsers can throttle operations on background tabs, could warn that a tab is using a lot of resource, and restrict which contexts are allowed to use WebGPU.

User agents can heuristically issue warnings to users about high power use, especially due to potentially malicious usage. If a user agent implements such a warning, it should include WebGPU usage in its heuristics, in addition to JavaScript, WebAssembly, WebGL, and so on.

2.2. Privacy Considerations

There is a tracking vector here. The privacy considerations for WebGPU are similar to those of WebGL. GPU APIs are complex and must expose various aspects of a device’s capabilities out of necessity in order to enable developers to take advantage of those capabilities effectively. The general mitigation approach involves normalizing or binning potentially identifying information and enforcing uniform behavior where possible.

A user agent must not reveal more than 32 distinguishable configurations or buckets.

2.2.1. Machine-specific features and limits

WebGPU can expose a lot of detail on the underlying GPU architecture and the device geometry. This includes available physical adapters, many limits on the GPU and CPU resources that could be used (such as the maximum texture size), and any optional hardware-specific capabilities that are available.

User agents are not obligated to expose the real hardware limits, they are in full control of how much the machine specifics are exposed. One strategy to reduce fingerprinting is binning all the target platforms into a few number of bins. In general, the privacy impact of exposing the hardware limits matches the one of WebGL.

The default limits are also deliberately high enough to allow most applications to work without requesting higher limits. All the usage of the API is validated according to the requested limits, so the actual hardware capabilities are not exposed to the users by accident.

2.2.2. Machine-specific artifacts

There are some machine-specific rasterization/precision artifacts and performance differences that can be observed roughly in the same way as in WebGL. This applies to rasterization coverage and patterns, interpolation precision of the varyings between shader stages, compute unit scheduling, and more aspects of execution.

Generally, rasterization and precision fingerprints are identical across most or all of the devices of each vendor. Performance differences are relatively intractable, but also relatively low-signal (as with JS execution performance).

Privacy-critical applications and user agents should utilize software implementations to eliminate such artifacts.

2.2.3. Machine-specific performance

Another factor for differentiating users is measuring the performance of specific operations on the GPU. Even with low precision timing, repeated execution of an operation can show if the user’s machine is fast at specific workloads. This is a fairly common vector (present in both WebGL and Javascript), but it’s also low-signal and relatively intractable to truly normalize.

WebGPU compute pipelines expose access to GPU unobstructed by the fixed-function hardware. This poses an additional risk for unique device fingerprinting. User agents can take steps to dissociate logical GPU invocations with actual compute units to reduce this risk.

2.2.4. User Agent State

This specification doesn’t define any additional user-agent state for an origin. However it is expected that user agents will have compilation caches for the result of expensive compilation like GPUShaderModule, GPURenderPipeline and GPUComputePipeline. These caches are important to improve the loading time of WebGPU applications after the first visit.

For the specification, these caches are indifferentiable from incredibly fast compilation, but for applications it would be easy to measure how long createComputePipelineAsync() takes to resolve. This can leak information across origins (like "did the user access a site with this specific shader") so user agents should follow the best practices in storage partitioning.

The system’s GPU driver may also have its own cache of compiled shaders and pipelines. User agents may want to disable these when at all possible, or add per-partition data to shaders in ways that will make the GPU driver consider them different.

2.2.5. Driver bugs

In addition to the concerns outlined in Security Considerations, driver bugs may introduce differences in behavior that can be observed as a method of differentiating users. The mitigations mentioned in Security Considerations apply here as well, including coordinating with GPU vendors and implementing workarounds for known issues in the user agent.

2.2.6. Adapter Identifiers

Past experience with WebGL has demonstrated that developers have a legitimate need to be able to identify the GPU their code is running on in order to create and maintain robust GPU-based content. For example, to identify adapters with known driver bugs in order to work around them or to avoid features that perform more poorly than expected on a given class of hardware.

But exposing adapter identifiers also naturally expands the amount of fingerprinting information available, so there’s a desire to limit the precision with which we identify the adapter.

There are several mitigations that can be applied to strike a balance between enabling robust content and preserving privacy. First is that user agents can reduce the burden on developers by identifying and working around known driver issues, as they have since browsers began making use of GPUs.

When adapter identifiers are exposed by default they should be as broad as possible while still being useful. Possibly identifying, for example, the adapter’s vendor and general architecture without identifying the specific adapter in use. Similarly, in some cases identifiers for an adapter that is considered a reasonable proxy for the actual adapter may be reported.

In cases where full and detailed information about the adapter is useful (for example: when filing bug reports) the user can be asked for consent to reveal additional information about their hardware to the page.

Finally, the user agent will always have the discretion to not report adapter identifiers at all if it considers it appropriate, such as in enhanced privacy modes.

3. Fundamentals

3.1. Conventions

3.1.1. Syntactic Shorthands

In this specification, the following syntactic shorthands are used:

The . ("dot") syntax, common in programming languages.

The phrasing "Foo.Bar" means "the Bar member of the value (or interface) Foo." If Foo is an ordered map and Bar does not exist in Foo, returns undefined.

The phrasing "Foo.Bar is provided" means "the Bar member exists in the map value Foo"

The ?. ("optional chaining") syntax, adopted from JavaScript.

The phrasing "Foo?.Bar" means "if Foo is null or undefined or Bar does not exist in Foo, undefined; otherwise, Foo.Bar".

For example, where buffer is a GPUBuffer, buffer?.\[[device]].\[[adapter]] means "if buffer is null or undefined, then undefined; otherwise, the \[[adapter]] internal slot of the \[[device]] internal slot of buffer.

The ?? ("nullish coalescing") syntax, adopted from JavaScript.

The phrasing "x ?? y" means "x, if x is not null or undefined, and y otherwise".

slot-backed attribute

A WebIDL attribute which is backed by an internal slot of the same name. It may or may not be mutable.

3.1.2. WebGPU Objects

A WebGPU object consists of a WebGPU Interface and an internal object.

The WebGPU interface defines the public interface and state of the WebGPU object. It can be used on the content timeline where it was created, where it is a JavaScript-exposed WebIDL interface.

Any interface which includes GPUObjectBase is a WebGPU interface.

The internal object tracks the state of the WebGPU object on the device timeline. All reads/writes to the mutable state of an internal object occur from steps executing on a single well-ordered device timeline.

The following special property types can be defined on WebGPU objects:

immutable property

A read-only slot set during initialization of the object. It can be accessed from any timeline.

Note: Since the slot is immutable, implementations may have a copy on multiple timelines, as needed. Immutable properties are defined in this way to avoid describing multiple copies in this spec.

If named [[with brackets]], it is an internal slot.
If named withoutBrackets, it is a readonly slot-backed attribute of the WebGPU interface.

content timeline property

A property which is only accessible from the content timeline where the object was created.

If named [[with brackets]], it is an internal slot.
If named withoutBrackets, it is a slot-backed attribute of the WebGPU interface.

device timeline property

A property which tracks state of the internal object and is only accessible from the device timeline where the object was created. device timeline properties may be mutable.

Device timeline properties are named [[with brackets]], and are internal slots.

queue timeline property

A property which tracks state of the internal object and is only accessible from the queue timeline where the object was created. queue timeline properties may be mutable.

Queue timeline properties are named [[with brackets]], and are internal slots.

interface mixin GPUObjectBase {
    attribute USVString label;
};
To create a new WebGPU object(GPUObjectBase parent, interface T, GPUObjectDescriptorBase descriptor) (where T extends GPUObjectBase), run the following content timeline steps:
  1. Let device be parent.[[device]].

  2. Let object be a new instance of T.

  3. Set object.[[device]] to device.

  4. Set object.label to descriptor.label.

  5. Return object.

GPUObjectBase has the following immutable properties:

[[device]], of type device, readonly

The device that owns the internal object.

Operations on the contents of this object assert they are running on the device timeline, and that the device is valid.

GPUObjectBase has the following content timeline properties:

label, of type USVString

A developer-provided label which is used in an implementation-defined way. It can be used by the browser, OS, or other tools to help identify the underlying internal object to the developer. Examples include displaying the label in GPUError messages, console warnings, browser developer tools, and platform debugging utilities.

NOTE:
Implementations should use labels to enhance error messages by using them to identify WebGPU objects.

However, this need not be the only way of identifying objects: implementations should also use other available information, especially when no label is available. For example:

NOTE:
The label is a property of the GPUObjectBase. Two GPUObjectBase "wrapper" objects have completely separate label states, even if they refer to the same underlying object (for example returned by getBindGroupLayout()). The label property will not change except by being set from JavaScript.

This means one underlying object could be associated with multiple labels. This specification does not define how the label is propagated to the device timeline. How labels are used is completely implementation-defined: error messages could show the most recently set label, all known labels, or no labels at all.

It is defined as a USVString because some user agents may supply it to the debug facilities of the underlying native APIs.

GPUObjectBase has the following device timeline properties:

[[valid]], of type boolean, initially true.

If true, indicates that the internal object is valid to use.

NOTE:
Ideally WebGPU interfaces should not prevent their parent objects, such as the [[device]] that owns them, from being garbage collected. This cannot be guaranteed, however, as holding a strong reference to a parent object may be required in some implementations.

As a result, developers should assume that a WebGPU interface may not be garbage collected until all child objects of that interface have also been garbage collected. This may cause some resources to remain allocated longer than anticipated.

Calling the destroy method on a WebGPU interface (such as GPUDevice.destroy() or GPUBuffer.destroy()) should be favored over relying on garbage collection if predictable release of allocated resources is needed.

3.1.3. Object Descriptors

An object descriptor holds the information needed to create an object, which is typically done via one of the create* methods of GPUDevice.

dictionary GPUObjectDescriptorBase {
    USVString label = "";
};

GPUObjectDescriptorBase has the following members:

label, of type USVString, defaulting to ""

The initial value of GPUObjectBase.label.

3.2. Asynchrony

3.2.1. Invalid Internal Objects & Contagious Invalidity

Object creation operations in WebGPU don’t return promises, but nonetheless are internally asynchronous. Returned objects refer to internal objects which are manipulated on a device timeline. Rather than fail with exceptions or rejections, most errors that occur on a device timeline are communicated through GPUErrors generated on the associated device.

Internal objects are either valid or invalid. An invalid object will never become valid at a later time, but some valid objects may be invalidated.

Objects are invalid from creation if it wasn’t possible to create them. This can happen, for example, if the object descriptor doesn’t describe a valid object, or if there is not enough memory to allocate a resource. It can also happen if an object is created with or from another invalid object (for example calling createView() on an invalid GPUTexture) (for example the GPUTexture of a createView() call): this case is referred to as contagious invalidity.

Internal objects of most types cannot become invalid after they are created, but still may become unusable, e.g. if the owning device is lost or destroyed, or the object has a special internal state, like buffer state "destroyed".

Internal objects of some types can become invalid after they are created; specifically, devices, adapters, GPUCommandBuffers, and command/pass/bundle encoders.

A given GPUObjectBase object is valid if object.[[valid]] is true.
A given GPUObjectBase object is invalid if object.[[valid]] is false.
A given GPUObjectBase object is valid to use with a targetObject if the all of the requirements in the following device timeline steps are met:
To invalidate a GPUObjectBase object, run the following device timeline steps:
  1. object.[[valid]] to false.

3.2.2. Promise Ordering

Several operations in WebGPU return promises.

WebGPU does not make any guarantees about the order in which these promises settle (resolve or reject), except for the following:

Applications must not rely on any other promise settlement ordering.

3.3. Coordinate Systems

Rendering operations use the following coordinate systems:

Note: WebGPU’s coordinate systems match DirectX’s coordinate systems in a graphics pipeline.

3.4. Programming Model

3.4.1. Timelines

WebGPU’s behavior is described in terms of "timelines". Each operation (defined as algorithms) occurs on a timeline. Timelines clearly define both the order of operations, and which state is available to which operations.

Note: This "timeline" model describes the constraints of the multi-process models of browser engines (typically with a "content process" and "GPU process"), as well as the GPU itself as a separate execution unit in many implementations. Implementing WebGPU does not require timelines to execute in parallel, so does not require multiple processes, or even multiple threads. (It does require concurrency for cases like get a copy of the image contents of a context which synchronously blocks on another timeline to complete.)

Content timeline

Associated with the execution of the Web script. It includes calling all methods described by this specification.

To issue steps to the content timeline from an operation on GPUDevice device, queue a global task for GPUDevice device with those steps.

Device timeline

Associated with the GPU device operations that are issued by the user agent. It includes creation of adapters, devices, and GPU resources and state objects, which are typically synchronous operations from the point of view of the user agent part that controls the GPU, but can live in a separate OS process.

Queue timeline

Associated with the execution of operations on the compute units of the GPU. It includes actual draw, copy, and compute jobs that run on the GPU.

Timeline-agnostic

Associated with any of the above timelines

Steps may be issued to any timeline if they only operate on immutable properties or arguments passed from the calling steps.

The following show the styling of steps and values associated with each timeline. This styling is non-normative; the specification text always describes the association.
Immutable value example term definition

Can be used on any timeline.

Content-timeline example term definition

Can only be used on the content timeline.

Device-timeline example term definition

Can only be used on the device timeline.

Queue-timeline example term definition

Can only be used on the queue timeline.

Steps which are timeline-agnostic look like this.

Immutable value example term usage.

Steps executed on the content timeline look like this.

Immutable value example term usage. Content-timeline example term usage.

Steps executed on the device timeline look like this.

Immutable value example term usage. Device-timeline example term usage.

Steps executed on the queue timeline look like this.

Immutable value example term usage. Queue-timeline example term usage.

In this specification, asynchronous operations are used when the return value depends on work that happens on any timeline other than the Content timeline. They are represented by promises and events in API.

GPUComputePassEncoder.dispatchWorkgroups():
  1. User encodes a dispatchWorkgroups command by calling a method of the GPUComputePassEncoder which happens on the Content timeline.

  2. User issues GPUQueue.submit() that hands over the GPUCommandBuffer to the user agent, which processes it on the Device timeline by calling the OS driver to do a low-level submission.

  3. The submit gets dispatched by the GPU invocation scheduler onto the actual compute units for execution, which happens on the Queue timeline.

GPUDevice.createBuffer():
  1. User fills out a GPUBufferDescriptor and creates a GPUBuffer with it, which happens on the Content timeline.

  2. User agent creates a low-level buffer on the Device timeline.

GPUBuffer.mapAsync():
  1. User requests to map a GPUBuffer on the Content timeline and gets a promise in return.

  2. User agent checks if the buffer is currently used by the GPU and makes a reminder to itself to check back when this usage is over.

  3. After the GPU operating on Queue timeline is done using the buffer, the user agent maps it to memory and resolves the promise.

3.4.2. Memory Model

This section is non-normative.

Once a GPUDevice has been obtained during an application initialization routine, we can describe the WebGPU platform as consisting of the following layers:

  1. User agent implementing the specification.

  2. Operating system with low-level native API drivers for this device.

  3. Actual CPU and GPU hardware.

Each layer of the WebGPU platform may have different memory types that the user agent needs to consider when implementing the specification:

Most physical resources are allocated in the memory of type that is efficient for computation or rendering by the GPU. When the user needs to provide new data to the GPU, the data may first need to cross the process boundary in order to reach the user agent part that communicates with the GPU driver. Then it may need to be made visible to the driver, which sometimes requires a copy into driver-allocated staging memory. Finally, it may need to be transferred to the dedicated GPU memory, potentially changing the internal layout into one that is most efficient for GPUs to operate on.

All of these transitions are done by the WebGPU implementation of the user agent.

Note: This example describes the worst case, while in practice the implementation may not need to cross the process boundary, or may be able to expose the driver-managed memory directly to the user behind an ArrayBuffer, thus avoiding any data copies.

3.4.3. Resource Usages

A physical resource can be used with an internal usage by a GPU command:

input

Buffer with input data for draw or dispatch calls. Preserves the contents. Allowed by buffer INDEX, buffer VERTEX, or buffer INDIRECT.

constant

Resource bindings that are constant from the shader point of view. Preserves the contents. Allowed by buffer UNIFORM or texture TEXTURE_BINDING.

storage

Read/write storage resource binding. Allowed by buffer STORAGE or texture STORAGE_BINDING.

storage-read

Read-only storage resource bindings. Preserves the contents. Allowed by buffer STORAGE or texture STORAGE_BINDING.

attachment

Texture used as a read/write output attachment or write-only resolve target in a render pass. Allowed by texture RENDER_ATTACHMENT.

attachment-read

Texture used as a read-only attachment in a render pass. Preserves the contents. Allowed by texture RENDER_ATTACHMENT.

We define subresource to be either a whole buffer, or a texture subresource.

Some internal usages are compatible with others. A subresource can be in a state that combines multiple usages together. We consider a list U to be a compatible usage list if (and only if) it satisfies any of the following rules:

Enforcing that the usages are only combined into a compatible usage list allows the API to limit when data races can occur in working with memory. That property makes applications written against WebGPU more likely to run without modification on different platforms.

EXAMPLE:
Binding the same buffer for storage as well as for input within the same GPURenderPassEncoder results in a non-compatible usage list for that buffer.
EXAMPLE:
These rules allow for read-only depth-stencil: a single depth/stencil texture can be used as two different read-only usages in a render pass simultaneously:
EXAMPLE:
The usage scope storage exception allows two cases that would not be allowed otherwise:
EXAMPLE:
The usage scope attachment exception allows a texture subresource to be used as attachment more than once. This is necessary to allow disjoint slices of 3D textures to be bound as different attachments to a single render pass.

One slice may not be bound twice for two different attachments; this is checked by beginRenderPass().

3.4.4. Synchronization

A usage scope is a map from subresource to list<internal usage>>. Each usage scope covers a range of operations which may execute in a concurrent fashion with each other, and therefore may only use subresources in consistent compatible usage lists within the scope.

A usage scope scope passes usage scope validation if, for each [subresource, usageList] in scope, usageList is a compatible usage list.
To add a subresource subresource to usage scope usageScope with usage (internal usage or set of internal usages) usage:
  1. If usageScope[subresource] does not exist, set it to [].

  2. Append usage to usageScope[subresource].

To merge usage scope A into usage scope B:
  1. For each [subresource, usage] in A:

    1. Add subresource to B with usage usage.

Usage scopes are constructed and validated during encoding:

The usage scopes are as follows:

Note: Copy commands are standalone operations and don’t use usage scopes for validation. They implement their own validation to prevent self-races.

EXAMPLE:
The following example resource usages are included in usage scopes:

3.5. Core Internal Objects

3.5.1. Adapters

An adapter identifies an implementation of WebGPU on the system: both an instance of compute/rendering functionality on the platform underlying a browser, and an instance of a browser’s implementation of WebGPU on top of that functionality.

Adapters are exposed via GPUAdapter.

Adapters do not uniquely represent underlying implementations: calling requestAdapter() multiple times returns a different adapter object each time.

Each adapter object can only be used to create one device: upon a successful requestDevice() call, the adapter’s [[state]] changes to "consumed". Additionally, adapter objects may expire at any time.

Note: This ensures applications use the latest system state for adapter selection when creating a device. It also encourages robustness to more scenarios by making them look similar: first initialization, reinitialization due to an unplugged adapter, reinitialization due to a test GPUDevice.destroy() call, etc.

An adapter may be considered a fallback adapter if it has significant performance caveats in exchange for some combination of wider compatibility, more predictable behavior, or improved privacy. It is not required that a fallback adapter is available on every system.

adapter has the following immutable properties:

[[features]], of type ordered set<GPUFeatureName>, readonly

The features which can be used to create devices on this adapter.

[[limits]], of type supported limits, readonly

The best limits which can be used to create devices on this adapter.

Each adapter limit must be the same or better than its default value in supported limits.

[[fallback]], of type boolean, readonly

If set to true indicates that the adapter is a fallback adapter.

[[xrCompatible]], of type boolean

If set to true indicates that the adapter was requested with compatibility with WebXR sessions.

adapter has the following device timeline properties:

[[state]], initially "valid"
"valid"

The adapter can be used to create a device.

"consumed"

The adapter has already been used to create a device, and cannot be used again.

"expired"

The adapter has expired for some other reason.

To expire a GPUAdapter adapter, run the following device timeline steps:
  1. Set adapter.[[adapter]].[[state]] to "expired".

3.5.2. Devices

A device is the logical instantiation of an adapter, through which internal objects are created.

Devices are exposed via GPUDevice.

A device is the exclusive owner of all internal objects created from it: when the device becomes invalid (is lost or destroyed), it and all objects created on it (directly, e.g. createTexture(), or indirectly, e.g. createView()) become implicitly unusable.

device has the following immutable properties:

[[adapter]], of type adapter, readonly

The adapter from which this device was created.

[[features]], of type ordered set<GPUFeatureName>, readonly

The features which can be used on this device, as computed at creation. No additional features can be used, even if the underlying adapter can support them.

[[limits]], of type supported limits, readonly

The limits which can be used on this device, as computed at creation. No better limits can be used, even if the underlying adapter can support them.

device has the following content timeline properties:

[[content device]], of type GPUDevice, readonly

The Content timeline GPUDevice interface which this device is associated with.

To create a new device from adapter adapter with GPUDeviceDescriptor descriptor, run the following device timeline steps:
  1. Let features be the set of values in descriptor.requiredFeatures.

  2. If features contains "texture-formats-tier2":

    1. Append "texture-formats-tier1" to features

  3. If features contains "texture-formats-tier1":

    1. Append "rg11b10ufloat-renderable" to features

  4. Append "core-features-and-limits" to features.

  5. Let limits be a supported limits object with all values set to their defaults.

  6. For each (key, value) pair in descriptor.requiredLimits:

    1. If value is not undefined and value is better than limits[key]:

      1. Set limits[key] to value.

  7. Let device be a device object.

  8. Set device.[[adapter]] to adapter.

  9. Set device.[[features]] to features.

  10. Set device.[[limits]] to limits.

  11. Return device.

Any time the user agent needs to revoke access to a device, it calls lose the device(device, "unknown") on the device’s device timeline, potentially ahead of other operations currently queued on that timeline.

If an operation fails with side effects that would observably change the state of objects on the device or potentially corrupt internal implementation/driver state, the device should be lost to prevent these changes from being observable.

Note: For all device losses not initiated by the application (via destroy()), user agents should consider issuing developer-visible warnings unconditionally, even if the lost promise is handled. These scenarios should be rare, and the signal is vital to developers because most of the WebGPU API tries to behave like nothing is wrong to avoid interrupting the runtime flow of the application: no validation errors are raised, most promises resolve normally, etc.

To lose the device(device, reason) run the following device timeline steps:
  1. Invalidate device.

  2. Issue the following steps on the content timeline of device.[[content device]]:

    1. Resolve device.lost with a new GPUDeviceLostInfo with reason set to reason and message set to an implementation-defined value.

      Note: message should not disclose unnecessary user/system information and should never be parsed by applications.

  3. Complete any outstanding steps that are waiting until device becomes lost.

Note: No errors are generated from a device which is lost. See § 22 Errors & Debugging.

To listen for timeline event event on device device, handled by steps on timeline timeline:

Then issue steps on timeline.

3.6. Optional Capabilities

WebGPU adapters and devices have capabilities, which describe WebGPU functionality that differs between different implementations, typically due to hardware or system software constraints. A capability is either a feature or a limit.

A user agent must not reveal more than 32 distinguishable configurations or buckets.

The capabilities of an adapter must conform to § 4.2.1 Adapter Capability Guarantees.

Only supported capabilities may be requested in requestDevice(); requesting unsupported capabilities results in failure.

The capabilities of a device are determined in "a new device" by starting with the adapter’s defaults (no features and the default supported limits) and adding capabilities as requested in requestDevice(). These capabilities are enforced regardless of the capabilities of the adapter.

There is a tracking vector here. For privacy considerations, see § 2.2.1 Machine-specific features and limits.

3.6.1. Features

A feature is a set of optional WebGPU functionality that is not supported on all implementations, typically due to hardware or system software constraints.

All features are optional, but adapters make some guarantees about their availability (see § 4.2.1 Adapter Capability Guarantees).

A device supports the exact set of features determined at creation (see § 3.6 Optional Capabilities). API calls perform validation according to these features (not the adapter’s features):

A GPUFeatureName feature is enabled for a GPUObjectBase object if and only if object.[[device]].[[features]] contains feature.

See the Feature Index for a description of the functionality each feature enables.

Note: Enabling features may not necessarily be desirable, as doing so may have a performance impact. Because of this, and to improve portability across devices and implementations, applications should generally only request features that they may actually require.

3.6.2. Limits

Each limit is a numeric limit on the usage of WebGPU on a device.

Note: Setting "better" limits may not necessarily be desirable, as doing so may have a performance impact. Because of this, and to improve portability across devices and implementations, applications should generally only request limits better than the defaults if they may actually require them.

Each limit has a default value.

Adapters are always guaranteed to support the defaults or better (see § 4.2.1 Adapter Capability Guarantees).

A device supports the exact set of limits determined at creation (see § 3.6 Optional Capabilities). API calls perform validation according to these limits (not the adapter’s limits), no better or worse.

For any given limit, some values are better than others. A better limit value always relaxes validation, enabling strictly more programs to be valid. For each limit class, "better" is defined.

Different limits have different limit classes:

maximum

The limit enforces a maximum on some value passed into the API.

Higher values are better.

May only be set to values ≥ the default. Lower values are clamped to the default.

alignment

The limit enforces a minimum alignment on some value passed into the API; that is, the value must be a multiple of the limit.

Lower values are better.

May only be set to powers of 2 which are ≤ the default. Values which are not powers of 2 are invalid. Higher powers of 2 are clamped to the default.

A supported limits object has a value for every limit defined by WebGPU:

Limit name Type Limit class Default
maxTextureDimension1D GPUSize32 maximum 8192
The maximum allowed value for the size.width of a texture created with dimension "1d".
maxTextureDimension2D GPUSize32 maximum 8192
The maximum allowed value for the size.width and size.height of a texture created with dimension "2d".
maxTextureDimension3D GPUSize32 maximum 2048
The maximum allowed value for the size.width, size.height and size.depthOrArrayLayers of a texture created with dimension "3d".
maxTextureArrayLayers GPUSize32 maximum 256
The maximum allowed value for the size.depthOrArrayLayers of a texture created with dimension "2d".
maxBindGroups GPUSize32 maximum 4
The maximum number of GPUBindGroupLayouts allowed in bindGroupLayouts when creating a GPUPipelineLayout.
maxBindGroupsPlusVertexBuffers GPUSize32 maximum 24
The maximum number of bind group and vertex buffer slots used simultaneously, counting any empty slots below the highest index. Validated in createRenderPipeline() and in draw calls.
maxBindingsPerBindGroup GPUSize32 maximum 1000
The number of binding indices available when creating a GPUBindGroupLayout.

Note: This limit is normative, but arbitrary. With the default binding slot limits, it is impossible to use 1000 bindings in one bind group, but this allows GPUBindGroupLayoutEntry.binding values up to 999. This limit allows implementations to treat binding space as an array, within reasonable memory space, rather than a sparse map structure.

maxDynamicUniformBuffersPerPipelineLayout GPUSize32 maximum 8
The maximum number of GPUBindGroupLayoutEntry entries across a GPUPipelineLayout which are uniform buffers with dynamic offsets. See Exceeds the binding slot limits.
maxDynamicStorageBuffersPerPipelineLayout GPUSize32 maximum 4
The maximum number of GPUBindGroupLayoutEntry entries across a GPUPipelineLayout which are storage buffers with dynamic offsets. See Exceeds the binding slot limits.
maxSampledTexturesPerShaderStage GPUSize32 maximum 16
For each possible GPUShaderStage stage, the maximum number of GPUBindGroupLayoutEntry entries across a GPUPipelineLayout which are sampled textures. See Exceeds the binding slot limits.
maxSamplersPerShaderStage GPUSize32 maximum 16
For each possible GPUShaderStage stage, the maximum number of GPUBindGroupLayoutEntry entries across a GPUPipelineLayout which are samplers. See Exceeds the binding slot limits.
maxStorageBuffersPerShaderStage GPUSize32 maximum 8
For each possible GPUShaderStage stage, the maximum number of GPUBindGroupLayoutEntry entries across a GPUPipelineLayout which are storage buffers. See Exceeds the binding slot limits.
maxStorageTexturesPerShaderStage GPUSize32 maximum 4
For each possible GPUShaderStage stage, the maximum number of GPUBindGroupLayoutEntry entries across a GPUPipelineLayout which are storage textures. See Exceeds the binding slot limits.
maxUniformBuffersPerShaderStage GPUSize32 maximum 12
For each possible GPUShaderStage stage, the maximum number of GPUBindGroupLayoutEntry entries across a GPUPipelineLayout which are uniform buffers. See Exceeds the binding slot limits.
maxUniformBufferBindingSize GPUSize64 maximum 65536 bytes
The maximum GPUBufferBinding.size for bindings with a GPUBindGroupLayoutEntry entry for which entry.buffer?.type is "uniform".
maxStorageBufferBindingSize GPUSize64 maximum 134217728 bytes (128 MiB)
The maximum GPUBufferBinding.size for bindings with a GPUBindGroupLayoutEntry entry for which entry.buffer?.type is "storage" or "read-only-storage".
minUniformBufferOffsetAlignment GPUSize32 alignment 256 bytes
The required alignment for GPUBufferBinding.offset and the dynamic offsets provided in setBindGroup(), for bindings with a GPUBindGroupLayoutEntry entry for which entry.buffer?.type is "uniform".
minStorageBufferOffsetAlignment GPUSize32 alignment 256 bytes
The required alignment for GPUBufferBinding.offset and the dynamic offsets provided in setBindGroup(), for bindings with a GPUBindGroupLayoutEntry entry for which entry.buffer?.type is "storage" or "read-only-storage".
maxVertexBuffers GPUSize32 maximum 8
The maximum number of buffers when creating a GPURenderPipeline.
maxBufferSize GPUSize64 maximum 268435456 bytes (256 MiB)
The maximum size of size when creating a GPUBuffer.
maxVertexAttributes GPUSize32 maximum 16
The maximum number of attributes in total across buffers when creating a GPURenderPipeline.
maxVertexBufferArrayStride GPUSize32 maximum 2048 bytes
The maximum allowed arrayStride when creating a GPURenderPipeline.
maxInterStageShaderVariables GPUSize32 maximum 16
The maximum allowed number of input or output variables for inter-stage communication (like vertex outputs or fragment inputs).
maxColorAttachments GPUSize32 maximum 8
The maximum allowed number of color attachments in GPURenderPipelineDescriptor.fragment.targets, GPURenderPassDescriptor.colorAttachments, and GPURenderPassLayout.colorFormats.
maxColorAttachmentBytesPerSample GPUSize32 maximum 32
The maximum number of bytes necessary to hold one sample (pixel or subpixel) of render pipeline output data, across all color attachments.
maxComputeWorkgroupStorageSize GPUSize32 maximum 16384 bytes
The maximum number of bytes of workgroup storage used for a compute stage GPUShaderModule entry-point.
maxComputeInvocationsPerWorkgroup GPUSize32 maximum 256
The maximum value of the product of the workgroup_size dimensions for a compute stage GPUShaderModule entry-point.
maxComputeWorkgroupSizeX GPUSize32 maximum 256
The maximum value of the workgroup_size X dimension for a compute stage GPUShaderModule entry-point.
maxComputeWorkgroupSizeY GPUSize32 maximum 256
The maximum value of the workgroup_size Y dimensions for a compute stage GPUShaderModule entry-point.
maxComputeWorkgroupSizeZ GPUSize32 maximum 64
The maximum value of the workgroup_size Z dimensions for a compute stage GPUShaderModule entry-point.
maxComputeWorkgroupsPerDimension GPUSize32 maximum 65535
The maximum value for the arguments of dispatchWorkgroups(workgroupCountX, workgroupCountY, workgroupCountZ).
3.6.2.1. GPUSupportedLimits

GPUSupportedLimits exposes an adapter or device’s supported limits. See GPUAdapter.limits and GPUDevice.limits.

[Exposed=(Window, Worker), SecureContext]
interface GPUSupportedLimits {
    readonly attribute unsigned long maxTextureDimension1D;
    readonly attribute unsigned long maxTextureDimension2D;
    readonly attribute unsigned long maxTextureDimension3D;
    readonly attribute unsigned long maxTextureArrayLayers;
    readonly attribute unsigned long maxBindGroups;
    readonly attribute unsigned long maxBindGroupsPlusVertexBuffers;
    readonly attribute unsigned long maxBindingsPerBindGroup;
    readonly attribute unsigned long maxDynamicUniformBuffersPerPipelineLayout;
    readonly attribute unsigned long maxDynamicStorageBuffersPerPipelineLayout;
    readonly attribute unsigned long maxSampledTexturesPerShaderStage;
    readonly attribute unsigned long maxSamplersPerShaderStage;
    readonly attribute unsigned long maxStorageBuffersPerShaderStage;
    readonly attribute unsigned long maxStorageTexturesPerShaderStage;
    readonly attribute unsigned long maxUniformBuffersPerShaderStage;
    readonly attribute unsigned long long maxUniformBufferBindingSize;
    readonly attribute unsigned long long maxStorageBufferBindingSize;
    readonly attribute unsigned long minUniformBufferOffsetAlignment;
    readonly attribute unsigned long minStorageBufferOffsetAlignment;
    readonly attribute unsigned long maxVertexBuffers;
    readonly attribute unsigned long long maxBufferSize;
    readonly attribute unsigned long maxVertexAttributes;
    readonly attribute unsigned long maxVertexBufferArrayStride;
    readonly attribute unsigned long maxInterStageShaderVariables;
    readonly attribute unsigned long maxColorAttachments;
    readonly attribute unsigned long maxColorAttachmentBytesPerSample;
    readonly attribute unsigned long maxComputeWorkgroupStorageSize;
    readonly attribute unsigned long maxComputeInvocationsPerWorkgroup;
    readonly attribute unsigned long maxComputeWorkgroupSizeX;
    readonly attribute unsigned long maxComputeWorkgroupSizeY;
    readonly attribute unsigned long maxComputeWorkgroupSizeZ;
    readonly attribute unsigned long maxComputeWorkgroupsPerDimension;
};
3.6.2.2. GPUSupportedFeatures

GPUSupportedFeatures is a setlike interface. Its set entries are the GPUFeatureName values of the features supported by an adapter or device. It must only contain strings from the GPUFeatureName enum.

[Exposed=(Window, Worker), SecureContext]
interface GPUSupportedFeatures {
    readonly setlike<DOMString>;
};
NOTE:
The type of the GPUSupportedFeatures set entries is DOMString to allow user agents to gracefully handle valid GPUFeatureNames which are added in later revisions of the spec but which the user agent has not been updated to recognize yet. If the set entries type was GPUFeatureName the following code would throw an TypeError rather than reporting false:
Check for support of an unrecognized feature:
if (adapter.features.has('unknown-feature')) {
    // Use unknown-feature
} else {
    console.warn('unknown-feature is not supported by this adapter.');
}
3.6.2.3. WGSLLanguageFeatures

WGSLLanguageFeatures is the setlike interface of navigator.gpu.wgslLanguageFeatures. Its set entries are the string names of the WGSL language extensions supported by the implementation (regardless of the adapter or device).

[Exposed=(Window, Worker), SecureContext]
interface WGSLLanguageFeatures {
    readonly setlike<DOMString>;
};
3.6.2.4. GPUAdapterInfo

GPUAdapterInfo exposes various identifying information about an adapter.

None of the members in GPUAdapterInfo are guaranteed to be populated with any particular value; if no value is provided, the attribute will return the empty string "". It is at the user agent’s discretion which values to reveal, and it is likely that on some devices none of the values will be populated. As such, applications must be able to handle any possible GPUAdapterInfo values, including the absence of those values.

The GPUAdapterInfo for an adapter is exposed via GPUAdapter.info and GPUDevice.adapterInfo). This info is immutable: for a given adapter, each GPUAdapterInfo attribute will return the same value every time it’s accessed.

Note: Though the GPUAdapterInfo attributes are immutable once accessed, an implementation may delay the decision on what to expose for each attribute until the first time it is accessed.

Note: Other GPUAdapter instances, even if they represent the same physical adapter, may expose different values in GPUAdapterInfo. However, they should expose the same values unless a specific event has increased the amount of identifying information the page is allowed to access. (No such events are defined by this specification.)

There is a tracking vector here. For privacy considerations, see § 2.2.6 Adapter Identifiers.

[Exposed=(Window, Worker), SecureContext]
interface GPUAdapterInfo {
    readonly attribute DOMString vendor;
    readonly attribute DOMString architecture;
    readonly attribute DOMString device;
    readonly attribute DOMString description;
    readonly attribute unsigned long subgroupMinSize;
    readonly attribute unsigned long subgroupMaxSize;
    readonly attribute boolean isFallbackAdapter;
};

GPUAdapterInfo has the following attributes:

vendor, of type DOMString, readonly

The name of the vendor of the adapter, if available. Empty string otherwise.

architecture, of type DOMString, readonly

The name of the family or class of GPUs the adapter belongs to, if available. Empty string otherwise.

device, of type DOMString, readonly

A vendor-specific identifier for the adapter, if available. Empty string otherwise.

Note: This is a value that represents the type of adapter. For example, it may be a PCI device ID. It does not uniquely identify a given piece of hardware like a serial number.

description, of type DOMString, readonly

A human readable string describing the adapter as reported by the driver, if available. Empty string otherwise.

Note: Because no formatting is applied to description attempting to parse this value is not recommended. Applications which change their behavior based on the GPUAdapterInfo, such as applying workarounds for known driver issues, should rely on the other fields when possible.

subgroupMinSize, of type unsigned long, readonly

If the "subgroups" feature is supported, the minimum supported subgroup size for the adapter.

subgroupMaxSize, of type unsigned long, readonly

If the "subgroups" feature is supported, the maximum supported subgroup size for the adapter.

isFallbackAdapter, of type boolean, readonly

Whether the adapter is a fallback adapter.

To create a new adapter info for a given adapter adapter, run the following content timeline steps:
  1. Let adapterInfo be a new GPUAdapterInfo.

  2. If the vendor is known, set adapterInfo.vendor to the name of adapter’s vendor as a normalized identifier string. To preserve privacy, the user agent may instead set adapterInfo.vendor to the empty string or a reasonable approximation of the vendor as a normalized identifier string.

  3. If |the architecture is known, set adapterInfo.architecture to a normalized identifier string representing the family or class of adapters to which adapter belongs. To preserve privacy, the user agent may instead set adapterInfo.architecture to the empty string or a reasonable approximation of the architecture as a normalized identifier string.

  4. If the device is known, set adapterInfo.device to a normalized identifier string representing a vendor-specific identifier for adapter. To preserve privacy, the user agent may instead set adapterInfo.device to to the empty string or a reasonable approximation of a vendor-specific identifier as a normalized identifier string.

  5. If a description is known, set adapterInfo.description to a description of the adapter as reported by the driver. To preserve privacy, the user agent may instead set adapterInfo.description to the empty string or a reasonable approximation of a description.

  6. If "subgroups" is supported, set subgroupMinSize to the smallest supported subgroup size. Otherwise, set this value to 4.

    Note: To preserve privacy, the user agent may choose to not support some features or provide values for the property which do not distinguish different devices, but are still usable (e.g. use the default value of 4 for all devices).

  7. If "subgroups" is supported, set subgroupMaxSize to the largest supported subgroup size. Otherwise, set this value to 128.

    Note: To preserve privacy, the user agent may choose to not support some features or provide values for the property which do not distinguish different devices, but are still usable (e.g. use the default value of 128 for all devices).

  8. Set adapterInfo.isFallbackAdapter to adapter.[[fallback]].

  9. Return adapterInfo.

A normalized identifier string is one that follows the following pattern:

[a-z0-9]+(-[a-z0-9]+)*

a-z 0-9 -
Examples of valid normalized identifier strings include:
  • gpu

  • 3d

  • 0x3b2f

  • next-gen

  • series-x20-ultra

3.7. Extension Documents

"Extension Documents" are additional documents which describe new functionality which is non-normative and not part of the WebGPU/WGSL specifications. They describe functionality that builds upon these specifications, often including one or more new API feature flags and/or WGSL enable directives, or interactions with other draft web specifications.

WebGPU implementations must not expose extension functionality; doing so is a spec violation. New functionality does not become part of the WebGPU standard until it is integrated into the WebGPU specification (this document) and/or WGSL specification.

3.8. Origin Restrictions

WebGPU allows accessing image data stored in images, videos, and canvases. Restrictions are imposed on the use of cross-domain media, because shaders can be used to indirectly deduce the contents of textures which have been uploaded to the GPU.

WebGPU disallows uploading an image source if it is not origin-clean.

This also implies that the origin-clean flag for a canvas rendered using WebGPU will never be set to false.

For more information on issuing CORS requests for image and video elements, consult:

3.9. Task Sources

3.9.1. WebGPU Task Source

WebGPU defines a new task source called the WebGPU task source. It is used for the uncapturederror event and GPUDevice.lost.

To queue a global task for GPUDevice device, with a series of steps steps on the content timeline:
  1. Queue a global task on the WebGPU task source, with the global object that was used to create device, and the steps steps.

3.9.2. Automatic Expiry Task Source

WebGPU defines a new task source called the automatic expiry task source. It is used for the automatic, timed expiry (destruction) of certain objects:

To queue an automatic expiry task with GPUDevice device and a series of steps steps on the content timeline:
  1. Queue a global task on the automatic expiry task source, with the global object that was used to create device, and the steps steps.

Tasks from the automatic expiry task source should be processed with high priority; in particular, once queued, they should run before user-defined (JavaScript) tasks.

NOTE:
This behavior is more predictable, and the strictness helps developers write more portable applications by eagerly detecting incorrect assumptions about implicit lifetimes that may be hard to detect. Developers are still strongly encouraged to test in multiple implementations.

Implementation note: It is valid to implement a high-priority expiry "task" by instead inserting additional steps at a fixed point inside the event loop processing model rather than running an actual task.

3.10. Color Spaces and Encoding

WebGPU does not provide color management. All values within WebGPU (such as texture elements) are raw numeric values, not color-managed color values.

WebGPU does interface with color-managed outputs (via GPUCanvasConfiguration) and inputs (via copyExternalImageToTexture() and importExternalTexture()). Thus, color conversion must be performed between the WebGPU numeric values and the external color values. Each such interface point locally defines an encoding (color space, transfer function, and alpha premultiplication) in which the WebGPU numeric values are to be interpreted.

WebGPU allows all of the color spaces in the PredefinedColorSpace enum. Note, each color space is defined over an extended range, as defined by the referenced CSS definitions, to represent color values outside of its space (in both chrominance and luminance).

An out-of-gamut premultiplied RGBA value is one where any of the R/G/B channel values exceeds the alpha channel value. For example, the premultiplied sRGB RGBA value [1.0, 0, 0, 0.5] represents the (unpremultiplied) color [2, 0, 0] with 50% alpha, written rgb(srgb 2 0 0 / 50%) in CSS. Just like any color value outside the sRGB color gamut, this is a well defined point in the extended color space (except when alpha is 0, in which case there is no color). However, when such values are output to a visible canvas, the result is undefined (see GPUCanvasAlphaMode "premultiplied").

3.10.1. Color Space Conversions

A color is converted between spaces by translating its representation in one space to a representation in another according to the definitions above.

If the source value has fewer than 4 RGBA channels, the missing green/blue/alpha channels are set to 0, 0, 1, respectively, before converting for color space/encoding and alpha premultiplication. After conversion, if the destination needs fewer than 4 channels, the additional channels are ignored.

Note: Grayscale images generally represent RGB values (V, V, V), or RGBA values (V, V, V, A) in their color space.

Colors are not lossily clamped during conversion: converting from one color space to another will result in values outside the range [0, 1] if the source color values were outside the range of the destination color space’s gamut. For an sRGB destination, for example, this can occur if the source is rgba16float, in a wider color space like Display-P3, or is premultiplied and contains out-of-gamut values.

Similarly, if the source value has a high bit depth (e.g. PNG with 16 bits per component) or extended range (e.g. canvas with float16 storage), these colors are preserved through color space conversion, with intermediate computations having at least the precision of the source.

3.10.2. Color Space Conversion Elision

If the source and destination of a color space/encoding conversion are the same, then conversion is not necessary. In general, if any given step of the conversion is an identity function (no-op), implementations should elide it, for performance.

For optimal performance, applications should set their color space and encoding options so that the number of necessary conversions is minimized throughout the process. For various image sources of GPUCopyExternalImageSourceInfo:

Note: Check browser implementation support for these features before relying on them.

3.11. Numeric conversions from JavaScript to WGSL

Several parts of the WebGPU API (pipeline-overridable constants and render pass clear values) take numeric values from WebIDL (double or float) and convert them to WGSL values (bool, i32, u32, f32, f16).

To convert an IDL value idlValue of type double or float to WGSL type T, possibly throwing a TypeError, run the following device timeline steps:

Note: This TypeError is generated in the device timeline and never surfaced to JavaScript.

  1. Assert idlValue is a finite value, since it is not unrestricted double or unrestricted float.

  2. Let v be the ECMAScript Number resulting from ! converting idlValue to an ECMAScript value.

  3. If T is bool

    Return the WGSL bool value corresponding to the result of ! converting v to an IDL value of type boolean.

    Note: This algorithm is called after the conversion from an ECMAScript value to an IDL double or float value. If the original ECMAScript value was a non-numeric, non-boolean value like [] or {}, then the WGSL bool result may be different than if the ECMAScript value had been converted to IDL boolean directly.

    If T is i32

    Return the WGSL i32 value corresponding to the result of ? converting v to an IDL value of type [EnforceRange] long.

    If T is u32

    Return the WGSL u32 value corresponding to the result of ? converting v to an IDL value of type [EnforceRange] unsigned long.

    If T is f32

    Return the WGSL f32 value corresponding to the result of ? converting v to an IDL value of type float.

    If T is f16
    1. Let wgslF32 be the WGSL f32 value corresponding to the result of ? converting v to an IDL value of type float.

    2. Return f16(wgslF32), the result of ! converting the WGSL f32 value to f16 as defined in WGSL floating point conversion.

    Note: As long as the value is in-range of f32, no error is thrown, even if the value is out-of-range of f16.

To convert a GPUColor color to a texel value of texture format format, possibly throwing a TypeError, run the following device timeline steps:

Note: This TypeError is generated in the device timeline and never surfaced to JavaScript.

  1. If the components of format (assert they all have the same type) are:

    floating-point types or normalized types

    Let T be f32.

    signed integer types

    Let T be i32.

    unsigned integer types

    Let T be u32.

  2. Let wgslColor be a WGSL value of type vec4<T>, where the 4 components are the RGBA channels of color, each ? converted to WGSL type T.

  3. Convert wgslColor to format using the same conversion rules as the § 23.2.7 Output Merging step, and return the result.

    Note: For non-integer types, the exact choice of value is implementation-defined. For normalized types, the value is clamped to the range of the type.

Note: In other words, the value written will be as if it was written by a WGSL shader that outputs the value represented as a vec4 of f32, i32, or u32.

4. Initialization

A GPU object is available in the Window and WorkerGlobalScope contexts through the Navigator and WorkerNavigator interfaces respectively and is exposed via navigator.gpu:

interface mixin NavigatorGPU {
    [SameObject, SecureContext] readonly attribute GPU gpu;
};
Navigator includes NavigatorGPU;
WorkerNavigator includes NavigatorGPU;

NavigatorGPU has the following attributes:

gpu, of type GPU, readonly

A global singleton providing top-level entry points like requestAdapter().

4.2. GPU

GPU is the entry point to WebGPU.

[Exposed=(Window, Worker), SecureContext]
interface GPU {
    Promise<GPUAdapter?> requestAdapter(optional GPURequestAdapterOptions options = {});
    GPUTextureFormat getPreferredCanvasFormat();
    [SameObject] readonly attribute WGSLLanguageFeatures wgslLanguageFeatures;
};

GPU has the following methods:

requestAdapter(options)

Requests an adapter from the user agent. The user agent chooses whether to return an adapter, and, if so, chooses according to the provided options.

Called on: GPU this.

Arguments:

Arguments for the GPU.requestAdapter(options) method.
Parameter Type Nullable Optional Description
options GPURequestAdapterOptions Criteria used to select the adapter.

Returns: Promise<GPUAdapter?>

Content timeline steps:

  1. Let contentTimeline be the current Content timeline.

  2. Let promise be a new promise.

  3. Issue the initialization steps on the Device timeline of this.

  4. Return promise.

Device timeline initialization steps:
  1. All of the requirements in the following steps must be met.

    1. options.featureLevel must be a feature level string.

    If they are met and the user agent chooses to return an adapter:

    1. Set adapter to an adapter chosen according to the rules in § 4.2.2 Adapter Selection and the criteria in options, adhering to § 4.2.1 Adapter Capability Guarantees. Initialize the properties of adapter according to their definitions:

      1. Set adapter.[[limits]] and adapter.[[features]] according to the supported capabilities of the adapter. adapter.[[features]] must contain "core-features-and-limits".

      2. If adapter meets the criteria of a fallback adapter set adapter.[[fallback]] to true. Otherwise, set it to false.

      3. Set adapter.[[xrCompatible]] to options.xrCompatible.

    Otherwise:

    1. Let adapter be null.

  2. Issue the subsequent steps on contentTimeline.

Content timeline steps:
  1. If adapter is not null:

    1. Resolve promise with a new GPUAdapter encapsulating adapter.

    Otherwise:

    1. Resolve promise with null.

getPreferredCanvasFormat()

Returns an optimal GPUTextureFormat for displaying 8-bit depth, standard dynamic range content on this system. Must only return "rgba8unorm" or "bgra8unorm".

The returned value can be passed as the format to configure() calls on a GPUCanvasContext to ensure the associated canvas is able to display its contents efficiently.

Note: Canvases which are not displayed to the screen may or may not benefit from using this format.

Called on: GPU this.

Returns: GPUTextureFormat

Content timeline steps:

  1. Return either "rgba8unorm" or "bgra8unorm", depending on which format is optimal for displaying WebGPU canvases on this system.

GPU has the following attributes:

wgslLanguageFeatures, of type WGSLLanguageFeatures, readonly

The names of supported WGSL language extensions. Supported language extensions are automatically enabled.

Adapters may expire at any time. Upon any change in the system’s state that could affect the result of any requestAdapter() call, the user agent should expire all previously-returned adapters. For example:

Note: User agents may choose to expire adapters often, even when there has been no system state change (e.g. seconds or minutes after the adapter was created). This can help obfuscate real system state changes, and make developers more aware that calling requestAdapter() again is always necessary before calling requestDevice(). If an application does encounter this situation, standard device-loss recovery handling should allow it to recover.

Requesting a GPUAdapter with no hints:
const gpuAdapter = await navigator.gpu.requestAdapter();

4.2.1. Adapter Capability Guarantees

Any GPUAdapter returned by requestAdapter() must provide the following guarantees:

4.2.2. Adapter Selection

GPURequestAdapterOptions provides hints to the user agent indicating what configuration is suitable for the application.

dictionary GPURequestAdapterOptions {
    DOMString featureLevel = "core";
    GPUPowerPreference powerPreference;
    boolean forceFallbackAdapter = false;
    boolean xrCompatible = false;
};
enum GPUPowerPreference {
    "low-power",
    "high-performance",
};

GPURequestAdapterOptions has the following members:

featureLevel, of type DOMString, defaulting to "core"

"Feature level" for the adapter request.

The allowed feature level string values are:

"core"

No effect.

"compatibility"

No effect.

Note: This value is reserved for future use as a way to opt into additional validation restrictions. Applications should not use this value at this time.

powerPreference, of type GPUPowerPreference

Optionally provides a hint indicating what class of adapter should be selected from the system’s available adapters.

The value of this hint may influence which adapter is chosen, but it must not influence whether an adapter is returned or not.

Note: The primary utility of this hint is to influence which GPU is used in a multi-GPU system. For instance, some laptops have a low-power integrated GPU and a high-performance discrete GPU. This hint may also affect the power configuration of the selected GPU to match the requested power preference.

Note: Depending on the exact hardware configuration, such as battery status and attached displays or removable GPUs, the user agent may select different adapters given the same power preference. Typically, given the same hardware configuration and state and powerPreference, the user agent is likely to select the same adapter.

It must be one of the following values:

undefined (or not present)

Provides no hint to the user agent.

"low-power"

Indicates a request to prioritize power savings over performance.

Note: Generally, content should use this if it is unlikely to be constrained by drawing performance; for example, if it renders only one frame per second, draws only relatively simple geometry with simple shaders, or uses a small HTML canvas element. Developers are encouraged to use this value if their content allows, since it may significantly improve battery life on portable devices.

"high-performance"

Indicates a request to prioritize performance over power consumption.

Note: By choosing this value, developers should be aware that, for devices created on the resulting adapter, user agents are more likely to force device loss, in order to save power by switching to a lower-power adapter. Developers are encouraged to only specify this value if they believe it is absolutely necessary, since it may significantly decrease battery life on portable devices.

forceFallbackAdapter, of type boolean, defaulting to false

When set to true indicates that only a fallback adapter may be returned. If the user agent does not support a fallback adapter, will cause requestAdapter() to resolve to null.

Note: requestAdapter() may still return a fallback adapter if forceFallbackAdapter is set to false and either no other appropriate adapter is available or the user agent chooses to return a fallback adapter. Developers that wish to prevent their applications from running on fallback adapters should check the info.isFallbackAdapter attribute prior to requesting a GPUDevice.

xrCompatible, of type boolean, defaulting to false

When set to true indicates that the best adapter for rendering to a WebXR session must be returned. If the user agent or system does not support WebXR sessions then adapter selection may ignore this value.

Note: If xrCompatible is not set to true when the adapter is requested, GPUDevices created from the adapter cannot be used to render for WebXR sessions.

Requesting a "high-performance" GPUAdapter:
const gpuAdapter = await navigator.gpu.requestAdapter({
    powerPreference: 'high-performance'
});

4.3. GPUAdapter

A GPUAdapter encapsulates an adapter, and describes its capabilities (features and limits).

To get a GPUAdapter, use requestAdapter().

[Exposed=(Window, Worker), SecureContext]
interface GPUAdapter {
    [SameObject] readonly attribute GPUSupportedFeatures features;
    [SameObject] readonly attribute GPUSupportedLimits limits;
    [SameObject] readonly attribute GPUAdapterInfo info;

    Promise<GPUDevice> requestDevice(optional GPUDeviceDescriptor descriptor = {});
};

GPUAdapter has the following immutable properties

features, of type GPUSupportedFeatures, readonly

The set of values in this.[[adapter]].[[features]].

limits, of type GPUSupportedLimits, readonly

The limits in this.[[adapter]].[[limits]].

info, of type GPUAdapterInfo, readonly

Information about the physical adapter underlying this GPUAdapter.

For a given GPUAdapter, the GPUAdapterInfo values exposed are constant over time.

The same object is returned each time. To create that object for the first time:

Called on: GPUAdapter this.

Returns: GPUAdapterInfo

Content timeline steps:

  1. Return a new adapter info for this.[[adapter]].

[[adapter]], of type adapter, readonly

The adapter to which this GPUAdapter refers.

GPUAdapter has the following methods:

requestDevice(descriptor)

Requests a device from the adapter.

This is a one-time action: if a device is returned successfully, the adapter becomes "consumed".

Called on: GPUAdapter this.

Arguments:

Arguments for the GPUAdapter.requestDevice(descriptor) method.
Parameter Type Nullable Optional Description
descriptor GPUDeviceDescriptor Description of the GPUDevice to request.

Returns: Promise<GPUDevice>

Content timeline steps:

  1. Let contentTimeline be the current Content timeline.

  2. Let promise be a new promise.

  3. Let adapter be this.[[adapter]].

  4. Issue the initialization steps to the Device timeline of this.

  5. Return promise.

Device timeline initialization steps:
  1. If any of the following requirements are unmet:

    Then issue the following steps on contentTimeline and return:

    Content timeline steps:
    1. Reject promise with a TypeError.

    Note: This is the same error that is produced if a feature name isn’t known by the browser at all (in its GPUFeatureName definition). This converges the behavior when the browser doesn’t support a feature with the behavior when a particular adapter doesn’t support a feature.

  2. All of the requirements in the following steps must be met.

    1. adapter.[[state]] must not be "consumed".

    2. For each [key, value] in descriptor.requiredLimits for which value is not undefined:

      1. key must be the name of a member of supported limits.

      2. value must be no better than adapter.[[limits]][key].

      3. If key’s class is alignment, value must be a power of 2 less than 232.

      Note: User agents should consider issuing developer-visible warnings when key is not recognized, even when value is undefined.

    If any are unmet, issue the following steps on contentTimeline and return:

    Content timeline steps:
    1. Reject promise with an OperationError.

  3. If adapter.[[state]] is "expired" or the user agent otherwise cannot fulfill the request:

    1. Let device be a new device.

    2. Lose the device(device, "unknown").

    3. Assert adapter.[[state]] is "expired".

      Note: User agents should consider issuing developer-visible warnings in most or all cases when this occurs. Applications should perform reinitialization logic starting with requestAdapter().

    Otherwise:

    1. Let device be a new device with the capabilities described by descriptor.

    2. Expire adapter.

  4. Issue the subsequent steps on contentTimeline.

Content timeline steps:
  1. Let gpuDevice be a new GPUDevice instance.

  2. Set gpuDevice.[[device]] to device.

  3. Set device.[[content device]] to gpuDevice.

  4. Set gpuDevice.label to descriptor.label.

  5. Resolve promise with gpuDevice.

    Note: If the device is already lost because the adapter could not fulfill the request, device.lost has already resolved before promise resolves.

Requesting a GPUDevice with default features and limits:
const gpuAdapter = await navigator.gpu.requestAdapter();
const gpuDevice = await gpuAdapter.requestDevice();

4.3.1. GPUDeviceDescriptor

GPUDeviceDescriptor describes a device request.

dictionary GPUDeviceDescriptor
         : GPUObjectDescriptorBase {
    sequence<GPUFeatureName> requiredFeatures = [];
    record<DOMString, (GPUSize64 or undefined)> requiredLimits = {};
    GPUQueueDescriptor defaultQueue = {};
};

GPUDeviceDescriptor has the following members:

requiredFeatures, of type sequence<GPUFeatureName>, defaulting to []

Specifies the features that are required by the device request. The request will fail if the adapter cannot provide these features.

Exactly the specified set of features, and no more or less, will be allowed in validation of API calls on the resulting device.

requiredLimits, of type record<DOMString, (GPUSize64 or undefined)>, defaulting to {}

Specifies the limits that are required by the device request. The request will fail if the adapter cannot provide these limits.

Each key with a non-undefined value must be the name of a member of supported limits.

API calls on the resulting device perform validation according to the exact limits of the device (not the adapter; see § 3.6.2 Limits).

defaultQueue, of type GPUQueueDescriptor, defaulting to {}

The descriptor for the default GPUQueue.

Requesting a GPUDevice with the "texture-compression-astc" feature if supported:
const gpuAdapter = await navigator.gpu.requestAdapter();

const requiredFeatures = [];
if (gpuAdapter.features.has('texture-compression-astc')) {
    requiredFeatures.push('texture-compression-astc')
}

const gpuDevice = await gpuAdapter.requestDevice({
    requiredFeatures
});
Requesting a GPUDevice with a higher maxColorAttachmentBytesPerSample limit:
const gpuAdapter = await navigator.gpu.requestAdapter();

if (gpuAdapter.limits.maxColorAttachmentBytesPerSample < 64) {
    // When the desired limit isn’t supported, take action to either fall back to a code
    // path that does not require the higher limit or notify the user that their device
    // does not meet minimum requirements.
}

// Request higher limit of max color attachments bytes per sample.
const gpuDevice = await gpuAdapter.requestDevice({
    requiredLimits: { maxColorAttachmentBytesPerSample: 64 },
});
4.3.1.1. GPUFeatureName

Each GPUFeatureName identifies a set of functionality which, if available, allows additional usages of WebGPU that would have otherwise been invalid.

enum GPUFeatureName {
    "core-features-and-limits",
    "depth-clip-control",
    "depth32float-stencil8",
    "texture-compression-bc",
    "texture-compression-bc-sliced-3d",
    "texture-compression-etc2",
    "texture-compression-astc",
    "texture-compression-astc-sliced-3d",
    "timestamp-query",
    "indirect-first-instance",
    "shader-f16",
    "rg11b10ufloat-renderable",
    "bgra8unorm-storage",
    "float32-filterable",
    "float32-blendable",
    "clip-distances",
    "dual-source-blending",
    "subgroups",
    "texture-formats-tier1",
    "texture-formats-tier2",
    "primitive-index",
};

4.4. GPUDevice

A GPUDevice encapsulates a device and exposes the functionality of that device.

GPUDevice is the top-level interface through which WebGPU interfaces are created.

To get a GPUDevice, use requestDevice().

[Exposed=(Window, Worker), SecureContext]
interface GPUDevice : EventTarget {
    [SameObject] readonly attribute GPUSupportedFeatures features;
    [SameObject] readonly attribute GPUSupportedLimits limits;
    [SameObject] readonly attribute GPUAdapterInfo adapterInfo;

    [SameObject] readonly attribute GPUQueue queue;

    undefined destroy();

    GPUBuffer createBuffer(GPUBufferDescriptor descriptor);
    GPUTexture createTexture(GPUTextureDescriptor descriptor);
    GPUSampler createSampler(optional GPUSamplerDescriptor descriptor = {});
    GPUExternalTexture importExternalTexture(GPUExternalTextureDescriptor descriptor);

    GPUBindGroupLayout createBindGroupLayout(GPUBindGroupLayoutDescriptor descriptor);
    GPUPipelineLayout createPipelineLayout(GPUPipelineLayoutDescriptor descriptor);
    GPUBindGroup createBindGroup(GPUBindGroupDescriptor descriptor);

    GPUShaderModule createShaderModule(GPUShaderModuleDescriptor descriptor);
    GPUComputePipeline createComputePipeline(GPUComputePipelineDescriptor descriptor);
    GPURenderPipeline createRenderPipeline(GPURenderPipelineDescriptor descriptor);
    Promise<GPUComputePipeline> createComputePipelineAsync(GPUComputePipelineDescriptor descriptor);
    Promise<GPURenderPipeline> createRenderPipelineAsync(GPURenderPipelineDescriptor descriptor);

    GPUCommandEncoder createCommandEncoder(optional GPUCommandEncoderDescriptor descriptor = {});
    GPURenderBundleEncoder createRenderBundleEncoder(GPURenderBundleEncoderDescriptor descriptor);

    GPUQuerySet createQuerySet(GPUQuerySetDescriptor descriptor);
};
GPUDevice includes GPUObjectBase;

GPUDevice has the following immutable properties:

features, of type GPUSupportedFeatures, readonly

A set containing the GPUFeatureName values of the features supported by the device ([[device]].[[features]]).

limits, of type GPUSupportedLimits, readonly

The limits supported by the device ([[device]].[[limits]]).

queue, of type GPUQueue, readonly

The primary GPUQueue for this device.

adapterInfo, of type GPUAdapterInfo, readonly

Information about the physical adapter which created the device that this GPUDevice refers to.

For a given GPUDevice, the GPUAdapterInfo values exposed are constant over time.

The same object is returned each time. To create that object for the first time:

Called on: GPUDevice this.

Returns: GPUAdapterInfo

Content timeline steps:

  1. Return a new adapter info for this.[[device]].[[adapter]].

The [[device]] for a GPUDevice is the device that the GPUDevice refers to.

GPUDevice has the following methods:

destroy()

Destroys the device, preventing further operations on it. Outstanding asynchronous operations will fail.

Note: It is valid to destroy a device multiple times.

Called on: GPUDevice this.

Content timeline steps:

  1. unmap() all GPUBuffers from this device.

  2. Issue the subsequent steps on the Device timeline of this.

  1. Lose the device(this.[[device]], "destroyed").

Note: Since no further operations can be enqueued on this device, implementations can abort outstanding asynchronous operations immediately and free resource allocations, including mapped memory that was just unmapped.

A GPUDevice’s allowed buffer usages are:
A GPUDevice’s allowed texture usages are:

4.5. Example

A more robust example of requesting a GPUAdapter and GPUDevice with error handling:
let gpuDevice = null;

async function initializeWebGPU() {
    // Check to ensure the user agent supports WebGPU.
    if (!('gpu' in navigator)) {
        console.error("User agent doesn’t support WebGPU.");
        return false;
    }

    // Request an adapter.
    const gpuAdapter = await navigator.gpu.requestAdapter();

    // requestAdapter may resolve with null if no suitable adapters are found.
    if (!gpuAdapter) {
        console.error('No WebGPU adapters found.');
        return false;
    }

    // Request a device.
    // Note that the promise will reject if invalid options are passed to the optional
    // dictionary. To avoid the promise rejecting always check any features and limits
    // against the adapters features and limits prior to calling requestDevice().
    gpuDevice = await gpuAdapter.requestDevice();

    // requestDevice will never return null, but if a valid device request can’t be
    // fulfilled for some reason it may resolve to a device which has already been lost.
    // Additionally, devices can be lost at any time after creation for a variety of reasons
    // (ie: browser resource management, driver updates), so it’s a good idea to always
    // handle lost devices gracefully.
    gpuDevice.lost.then((info) => {
        console.error(`WebGPU device was lost: ${info.message}`);

        gpuDevice = null;

        // Many causes for lost devices are transient, so applications should try getting a
        // new device once a previous one has been lost unless the loss was caused by the
        // application intentionally destroying the device. Note that any WebGPU resources
        // created with the previous device (buffers, textures, etc) will need to be
        // re-created with the new one.
        if (info.reason != 'destroyed') {
            initializeWebGPU();
        }
    });

    onWebGPUInitialized();

    return true;
}

function onWebGPUInitialized() {
    // Begin creating WebGPU resources here...
}

initializeWebGPU();

5. Buffers

5.1. GPUBuffer

A GPUBuffer represents a block of memory that can be used in GPU operations. Data is stored in linear layout, meaning that each byte of the allocation can be addressed by its offset from the start of the GPUBuffer, subject to alignment restrictions depending on the operation. Some GPUBuffers can be mapped which makes the block of memory accessible via an ArrayBuffer called its mapping.

GPUBuffers are created via createBuffer(). Buffers may be mappedAtCreation.

[Exposed=(Window, Worker), SecureContext]
interface GPUBuffer {
    readonly attribute GPUSize64Out size;
    readonly attribute GPUFlagsConstant usage;

    readonly attribute GPUBufferMapState mapState;

    Promise<undefined> mapAsync(GPUMapModeFlags mode, optional GPUSize64 offset = 0, optional GPUSize64 size);
    ArrayBuffer getMappedRange(optional GPUSize64 offset = 0, optional GPUSize64 size);
    undefined unmap();

    undefined destroy();
};
GPUBuffer includes GPUObjectBase;

enum GPUBufferMapState {
    "unmapped",
    "pending",
    "mapped",
};

GPUBuffer has the following immutable properties:

size, of type GPUSize64Out, readonly

The length of the GPUBuffer allocation in bytes.

usage, of type GPUFlagsConstant, readonly

The allowed usages for this GPUBuffer.

GPUBuffer has the following content timeline properties:

mapState, of type GPUBufferMapState, readonly

The current GPUBufferMapState of the buffer:

"unmapped"

The buffer is not mapped for use by this.getMappedRange().

"pending"

A mapping of the buffer has been requested, but is pending. It may succeed, or fail validation in mapAsync().

"mapped"

The buffer is mapped and this.getMappedRange() may be used.

The getter steps are:

Content timeline steps:
  1. If this.[[mapping]] is not null, return "mapped".

  2. If this.[[pending_map]] is not null, return "pending".

  3. Return "unmapped".

[[pending_map]], of type Promise<void> or null, initially null

The Promise returned by the currently-pending mapAsync() call.

There is never more than one pending map, because mapAsync() will refuse immediately if a request is already in flight.

[[mapping]], of type active buffer mapping or null, initially null

Set if and only if the buffer is currently mapped for use by getMappedRange(). Null otherwise (even if there is a [[pending_map]]).

An active buffer mapping is a structure with the following fields:

data, of type Data Block

The mapping for this GPUBuffer. This data is accessed through ArrayBuffers which are views onto this data, returned by getMappedRange() and stored in views.

mode, of type GPUMapModeFlags

The GPUMapModeFlags of the map, as specified in the corresponding call to mapAsync() or createBuffer().

range, of type tuple [unsigned long long, unsigned long long]

The range of this GPUBuffer that is mapped.

views, of type list<ArrayBuffer>

The ArrayBuffers returned via getMappedRange() to the application. They are tracked so they can be detached when unmap() is called.

To initialize an active buffer mapping with mode mode and range range, run the following content timeline steps:
  1. Let size be range[1] - range[0].

  2. Let data be ? CreateByteDataBlock(size).

    NOTE:
    This may result in a RangeError being thrown. For consistency and predictability:
    • For any size at which new ArrayBuffer() would succeed at a given moment, this allocation should succeed at that moment.

    • For any size at which new ArrayBuffer() deterministically throws a RangeError, this allocation should as well.

  3. Return an active buffer mapping with:

Mapping and unmapping a buffer.
Failing to map a buffer.

GPUBuffer has the following device timeline properties:

[[internal state]]

The current internal state of the buffer:

"available"

The buffer may be used in queue operations (unless it is invalid).

"unavailable"

The buffer may not be used in queue operations due to being mapped.

"destroyed"

The buffer may not be used in any operations due to being destroy()ed.

5.1.1. GPUBufferDescriptor

dictionary GPUBufferDescriptor
         : GPUObjectDescriptorBase {
    required GPUSize64 size;
    required GPUBufferUsageFlags usage;
    boolean mappedAtCreation = false;
};

GPUBufferDescriptor has the following members:

size, of type GPUSize64

The size of the buffer in bytes.

usage, of type GPUBufferUsageFlags

The allowed usages for the buffer.

mappedAtCreation, of type boolean, defaulting to false

If true creates the buffer in an already mapped state, allowing getMappedRange() to be called immediately. It is valid to set mappedAtCreation to true even if usage does not contain MAP_READ or MAP_WRITE. This can be used to set the buffer’s initial data.

Guarantees that even if the buffer creation eventually fails, it will still appear as if the mapped range can be written/read to until it is unmapped.

5.1.2. Buffer Usages

typedef [EnforceRange] unsigned long GPUBufferUsageFlags;
[Exposed=(Window, Worker), SecureContext]
namespace GPUBufferUsage {
    const GPUFlagsConstant MAP_READ      = 0x0001;
    const GPUFlagsConstant MAP_WRITE     = 0x0002;
    const GPUFlagsConstant COPY_SRC      = 0x0004;
    const GPUFlagsConstant COPY_DST      = 0x0008;
    const GPUFlagsConstant INDEX         = 0x0010;
    const GPUFlagsConstant VERTEX        = 0x0020;
    const GPUFlagsConstant UNIFORM       = 0x0040;
    const GPUFlagsConstant STORAGE       = 0x0080;
    const GPUFlagsConstant INDIRECT      = 0x0100;
    const GPUFlagsConstant QUERY_RESOLVE = 0x0200;
};

The GPUBufferUsage flags determine how a GPUBuffer may be used after its creation:

MAP_READ

The buffer can be mapped for reading. (Example: calling mapAsync() with GPUMapMode.READ)

May only be combined with COPY_DST.

MAP_WRITE

The buffer can be mapped for writing. (Example: calling mapAsync() with GPUMapMode.WRITE)

May only be combined with COPY_SRC.

COPY_SRC

The buffer can be used as the source of a copy operation. (Examples: as the source argument of a copyBufferToBuffer() or copyBufferToTexture() call.)

COPY_DST

The buffer can be used as the destination of a copy or write operation. (Examples: as the destination argument of a copyBufferToBuffer() or copyTextureToBuffer() call, or as the target of a writeBuffer() call.)

INDEX

The buffer can be used as an index buffer. (Example: passed to setIndexBuffer().)

VERTEX

The buffer can be used as a vertex buffer. (Example: passed to setVertexBuffer().)

UNIFORM

The buffer can be used as a uniform buffer. (Example: as a bind group entry for a GPUBufferBindingLayout with a buffer.type of "uniform".)

STORAGE

The buffer can be used as a storage buffer. (Example: as a bind group entry for a GPUBufferBindingLayout with a buffer.type of "storage" or "read-only-storage".)

INDIRECT

The buffer can be used as to store indirect command arguments. (Examples: as the indirectBuffer argument of a drawIndirect() or dispatchWorkgroupsIndirect() call.)

QUERY_RESOLVE

The buffer can be used to capture query results. (Example: as the destination argument of a resolveQuerySet() call.)

5.1.3. Buffer Creation

createBuffer(descriptor)

Creates a GPUBuffer.

Called on: GPUDevice this.

Arguments:

Arguments for the GPUDevice.createBuffer(descriptor) method.
Parameter Type Nullable Optional Description
descriptor GPUBufferDescriptor Description of the GPUBuffer to create.

Returns: GPUBuffer

Content timeline steps:

  1. Let b be ! create a new WebGPU object(this, GPUBuffer, descriptor).

  2. Set b.size to descriptor.size.

  3. Set b.usage to descriptor.usage.

  4. If descriptor.mappedAtCreation is true:

    1. If descriptor.size is not a multiple of 4, throw a RangeError.

    2. Set b.[[mapping]] to ? initialize an active buffer mapping with mode WRITE and range [0, descriptor.size].

  5. Issue the initialization steps on the Device timeline of this.

  6. Return b.

Device timeline initialization steps:
  1. If any of the following requirements are unmet, generate a validation error, invalidate b and return.

Note: If buffer creation fails, and descriptor.mappedAtCreation is false, any calls to mapAsync() will reject, so any resources allocated to enable mapping can and may be discarded or recycled.

  1. If descriptor.mappedAtCreation is true:

    1. Set b.[[internal state]] to "unavailable".

    Otherwise:

    1. Set b.[[internal state]] to "available".

  2. Create a device allocation for b where each byte is zero.

    If the allocation fails without side-effects, generate an out-of-memory error, invalidate b, and return.

Creating a 128 byte uniform buffer that can be written into:
const buffer = gpuDevice.createBuffer({
    size: 128,
    usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST
});

5.1.4. Buffer Destruction

An application that no longer requires a GPUBuffer can choose to lose access to it before garbage collection by calling destroy(). Destroying a buffer also unmaps it, freeing any memory allocated for the mapping.

Note: This allows the user agent to reclaim the GPU memory associated with the GPUBuffer once all previously submitted operations using it are complete.

GPUBuffer has the following methods:

destroy()

Destroys the GPUBuffer.

Note: It is valid to destroy a buffer multiple times.

Called on: GPUBuffer this.

Returns: undefined

Content timeline steps:

  1. Call this.unmap().

  2. Issue the subsequent steps on the Device timeline of this.[[device]].

Device timeline steps:
  1. Set this.[[internal state]] to "destroyed".

Note: Since no further operations can be enqueued using this buffer, implementations can free resource allocations, including mapped memory that was just unmapped.

5.2. Buffer Mapping

An application can request to map a GPUBuffer so that they can access its content via ArrayBuffers that represent part of the GPUBuffer’s allocations. Mapping a GPUBuffer is requested asynchronously with mapAsync() so that the user agent can ensure the GPU finished using the GPUBuffer before the application can access its content. A mapped GPUBuffer cannot be used by the GPU and must be unmapped using unmap() before work using it can be submitted to the Queue timeline.

Once the GPUBuffer is mapped, the application can synchronously ask for access to ranges of its content with getMappedRange(). The returned ArrayBuffer can only be detached by unmap() (directly, or via GPUBuffer.destroy() or GPUDevice.destroy()), and cannot be transferred. A TypeError is thrown by any other operation that attempts to do so.

typedef [EnforceRange] unsigned long GPUMapModeFlags;
[Exposed=(Window, Worker), SecureContext]
namespace GPUMapMode {
    const GPUFlagsConstant READ  = 0x0001;
    const GPUFlagsConstant WRITE = 0x0002;
};

The GPUMapMode flags determine how a GPUBuffer is mapped when calling mapAsync():

READ

Only valid with buffers created with the MAP_READ usage.

Once the buffer is mapped, calls to getMappedRange() will return an ArrayBuffer containing the buffer’s current values. Changes to the returned ArrayBuffer will be discarded after unmap() is called.

WRITE

Only valid with buffers created with the MAP_WRITE usage.

Once the buffer is mapped, calls to getMappedRange() will return an ArrayBuffer containing the buffer’s current values. Changes to the returned ArrayBuffer will be stored in the GPUBuffer after unmap() is called.

Note: Since the MAP_WRITE buffer usage may only be combined with the COPY_SRC buffer usage, mapping for writing can never return values produced by the GPU, and the returned ArrayBuffer will only ever contain the default initialized data (zeros) or data written by the webpage during a previous mapping.