WebGPU 开发者功能

François Beaufort
François Beaufort

发布时间:2025 年 6 月 3 日

Chrome 的 WebGPU API 实现包含仅用于开发和测试的功能。这些功能不在标准 WebGPU 规范的范围内。请勿在生产环境中使用这些功能。

本文档详细介绍了如何启用 WebGPU 开发者功能,并提供了一份完整列表。

前提条件

如需在 Chrome 中启用 WebGPU 开发者功能,请按以下步骤操作:

  1. chrome://flags/#enable-webgpu-developer-features 处启用“WebGPU 开发者功能”标志
  2. 重启 Chrome 浏览器。

停用时间戳查询量化

时间戳查询功能可让 WebGPU 应用在计算和渲染过程中准确测量(精确到纳秒)GPU 命令的执行时间。这些查询对于分析 GPU 工作负载性能和行为至关重要。如需了解详情,请参阅计算和渲染通道中的时间戳查询

出于对时序攻击的担忧,时间戳查询会以 100 微秒的分辨率进行量化,从而在精度和安全性之间取得良好的平衡。启用“WebGPU 开发者功能”标志后,此量化会自动停用。

扩展的适配器信息

为了更深入地了解所使用的适配器,GPUAdapterInfo 公开了以下属性:

  • device 属性(标准化)是特定于供应商的适配器标识符。
  • description 属性(标准化)是一个直观易懂的字符串,用于提供适配器详细信息。
  • driver 属性(非标准化)是用于描述驱动程序的直观易懂的字符串。
  • backend 属性(非标准化)用于指示图形后端,例如 "WebGPU""D3D11""D3D12""metal""vulkan""openGL""openGLES""null"
  • type 属性(非标准化)用于标识 GPU 类型:"discrete GPU""integrated GPU""CPU""unknown"
  • d3dShaderModel 属性(非标准化)用于指定支持的 D3D 着色器模型编号上限,例如,62 表示支持 HLSL SM 6.2。
  • vkDriverVersion 属性(非标准化)是供应商指定的 Vulkan 驱动程序版本。
  • powerPreference 属性(非标准化)为 "low-power""high-performance",具体取决于 GPURequestAdapterOptions 中的 GPUPowerPreference。

为了在应用开发期间分配大量内存时预先考虑到内存限制,GPUAdapterInfo 会公开 memoryHeaps 非标准化信息,例如适配器上可用的内存堆的大小和类型。

const adapter = await navigator.gpu.requestAdapter();

for (const { size, properties } of adapter.info.memoryHeaps) {
  console.log(size); // memory heap size in bytes
  if (properties & GPUHeapProperty.DEVICE_LOCAL)  { /* ... */ }
  if (properties & GPUHeapProperty.HOST_VISIBLE)  { /* ... */ }
  if (properties & GPUHeapProperty.HOST_COHERENT) { /* ... */ }
  if (properties & GPUHeapProperty.HOST_UNCACHED) { /* ... */ }
  if (properties & GPUHeapProperty.HOST_CACHED)   { /* ... */ }
}

着色器模块编译选项 strict math

GPUShaderModuleDescriptor 包含一个 strictMath 非标准化布尔值选项,用于在着色器模块编译期间启用或停用严格的数学精度。此选项在 Metal 和 Direct3D 上受支持。启用 strictMath 后,编译器会遵循精确的数学规则。相反,停用此功能可让编译器通过以下方式优化着色器:

  • 忽略 NaN 和 Infinity 值。
  • 将 -0 视为 +0。
  • 用更快的倒数相乘来替换除法。
  • 根据结合律和分配律重新排列运算。
const adapter = await navigator.gpu.requestAdapter();
const device = await adapter.requestDevice();

const code = `
  // Examines the bit pattern of the floating-point number to
  // determine if it represents a NaN according to the IEEE 754 standard.
  fn isNan(x : f32) -> bool {
    bool ones_exp = (bitcast<u32>(x) & 0x7f8) == 0x7f8;
    bool non_zero_sig = (bitcast<u32>(x) & 0x7ffff) != 0;
    return ones_exp && non_zero_sig;
  }
  // ...
`;

// Enable strict math during shader compilation.
const shaderModule = device.createShaderModule({ code, strictMath: true });

以零复制方式导入视频

GPUExternalTexture isZeroCopy 非标准化布尔值属性可让您了解使用 importExternalTexture() 导入的视频是否由 GPU 直接访问,而无需中间副本。

const adapter = await navigator.gpu.requestAdapter();
const device = await adapter.requestDevice();

const video = document.querySelector('video');
const externalTexture = device.importExternalTexture({ source: video });

if (externalTexture.isZeroCopy) {
  console.log('Video frame was accessed directly by the GPU');
}