Repository navigation
Description
Motivation
Modern graphics APIs have their query mechanism to get the information about the processing of a sequence of commands on GPU, and mainly support three types:
- Occlusion Query: Count the number of samples passed depth/stencil testing or whether samples passed the testing. This feature is used to determine visibility or even measure the area of geometry, such as predicated rendering (#551).
- Pipeline Statistics Query: Count various aspects of the operation of graphics or compute pipelines, such as the number of vertex shader invocations, the number of primitives processed by the clip stage, etc.. We can use these statistics informations to get a measure of relative complexity of different parts of application, which could help to find bottlenecks while performance tuning.
- Timestamp Query: Get timestamps generated by device. It can be used to measure the execution time of commands on GPU while performance tuning.
We expect to have such a mechanism to get these informations on WebGPU, here is the investigation about the support of these queries on D3D12, Metal and Vulkan.
Native APIs
Native APIs Support
| Query Types | D3D12 | Metal | Vulkan |
|---|---|---|---|
| Occlusion | Supported | macOS 10.11+ iOS 8+ |
Binary Occlusion: supported Precise Occlusion: VkPhysicalDeviceFeatures.occlusionQueryPrecise == true Device Coverage: 98.9% Windows, 97.3% Linux, 10.6% Android |
| Pipeline Statistics | Supported | macOS 10.15+ No iOS |
VkPhysicalDeviceFeatures.pipelineStatisticsQuery == true Device Coverage: 99.5% Windows, 99.5% Linux, 58.7% Android |
| Timestamp | Supported | macOS 10.15+ | VkQueueFamilyProperties.timestampValidBits != 0 |
- Binary occlusion query is supported in all native APIs, precise occlusion query and pipeline statistics query are optional features on Vulkan which need to be enabled at device creation time.
- Pipeline statistics and timestamp queries are not available on Metal until macOS 10.15+.
- On iOS 10.3+, it starts to support GPU time (
GPUStartTimeandGPUEndTime) but only for the whole command buffer. - So we can expose the binary occlusion query as a core feature, other queries as extensions.
Query Object
Query object is a collection of a specific number of queries of a particular type.
- On D3D12 and Vulkan, they manage all types of query objects in a similar way (
ID3D12QueryHeaporVkQueryPool). - On Metal, it stores occlusion query results using
visibilityResultBuffer. For pipeline statistics and timestamp queries, it usesMTLCounterSampleBuffer(available on macOS 10.15+) for storing their query results, like D3D12 and Vulkan.
The query objects on native APIs are created with descriptor (D3D12_QUERY_HEAP_DESC, MTLCounterSampleBufferDescriptor, VkQueryPoolCreateInfo) which specify query type and query count, expect for visibilityResultBuffer on Metal, which is a MTLBuffer and set in render pass descriptor when the render pass is creating.
The query objects are passed as an argument to query operations and need to be destroyed like Vulkan did.
Query Types
| Query Types | D3D12 | Metal | Vulkan |
|---|---|---|---|
| Occlusion | D3D12_QUERY_HEAP_TYPE_OCCLUSION |
MTLVisibilityResultMode |
VK_QUERY_TYPE_OCCLUSION |
| Pipeline Statistics | D3D12_QUERY_HEAP_TYPE_PIPELINE_STATISTICS |
MTLCommonCounterSetStatistic |
VK_QUERY_TYPE_PIPELINE_STATISTICS |
| Timestamp | D3D12_QUERY_HEAP_TYPE_TIMESTAMP |
MTLCommonCounterSetTimestamp |
VK_QUERY_TYPE_TIMESTAMP |
On Metal, it has no query type but uses MTLVisibilityResultMode for occlusion query, and stores query results in a MTLBuffer directly. Other queries have their types for creating query objects on each backend.
Query Operations
| Query Types | D3D12 | Metal | Vulkan | ||||
|---|---|---|---|---|---|---|---|
| Begin Query |
EndQ uery |
setVisib ilityResu ltMode |
sampleC ounters InBuffer |
vkCmdBe ginQuery |
vkCmdE ndQuery |
vkCmdW riteTimes tamp |
|
| Occlusion | √ | √ | √ | √ | √ | ||
| Pipeline Statistic |
√ | √ | √ | √ | √ | ||
| Timestamp | √ | √ | √ | ||||
Occlusion Query:
- On Metal, it calls a separate API named
setVisibiltyResultModewithBoolean/Disabledto begin/end binary occlusion query (Countingfor precise occlusion query). - D3D12 and Vulkan have begin and end operations. D3D12 controls binary/precise queries when calling
BeginQuerywith query type ofD3D12_QUERY_TYPE_BINARY_OCCLUSIONorD3D12_QUERY_TYPE_OCCLUSION, Vulkan controls them via callvkCmdBeginQuerywithcontrol flags.
Pipeline Statistics Query:
- On Metal, it performs pipeline statistics query by calling a new API on macOS 10.15+ named
sampleCountersInBuffer, it does NOT begin and end statistics in a range of commands like D3D12 and Vulkan, but does statistics from the beginning of render (or compute or blit) encoder to wheresampleCountersInBufferis called. - To implement pipeline statistics query on Metal, we can call
sampleCountersInBuffertwice (one for Begin() and other for End()) inside a render (or compute or blit) encoder, and stores the difference of the two query results in the result buffer.
Timestamp Query:
- Unlike occlusion and pipeline statistics queries, timestamp query does NOT operate over a range, but writes timestamps generated by device to query objects.
- The meanings of the timestamp results queried from native APIs are not clear. Timestamps are different on D3D12 (GPU ticks), Metal (nanoseconds) and Vulkan (nanoseconds), and not all timestamps can be converted to specific dates, which is platform dependent.
- So it’s better to have begin/end operations for timestamp query for exposing time delta instead of timestamp which may be more useful.
These operations on native APIs have different scopes:
| Query Types | D3D12 | Metal | Vulkan |
|---|---|---|---|
| Occlusion | Inside or outside render pass on Direct Command List | Inside render encoder | Inside or outside render pass on Graphics Queue |
| Pipeline Statistic |
Inside or outside render pass on Direct Command List | Inside render/compute/blit encoders | Inside or outside render pass on Graphics and Compute Queues |
| Timestamp | Inside or outside render pass on Direct nad Compute Command Lists | Inside render/compute/blit encoders | Inside or outside render pass on Graphics and Compute Queues |
Pipeline statistics query is only supported on Direct Command List on D3D12, but ID3D12GraphicsCommandList::Dispatch() can execute commands in a compute shader.
Resolve Query Results
| Query Types | D3D12 | Metal | Vulkan |
|---|---|---|---|
| Resolve APIs | ResolveQueryData |
resolveCounters |
vkGetQueryPoolResultsvkCmdCopyQueryPoolResults |
| Binary Occlusion Result | Binary 0/1 resolved into a buffer | Non-zero or zero integer stored in buffer | Non-zero or zero integer resolved into a buffer |
| Precise Occlusion Result | The number of samples passed depth and stencil tests | The number of samples passed depth and stencil tests | The number of samples passed scissor, exclusive scissor, sample mask, alpha to coverage, stencil, and depth tests |
| Pipeline Statistics Result | D3D12_QUERY_DATA_ PIPELINE_STATISTICS |
MTLCounterResult Statistic |
VkQueryPipelineStatistic FlagBits |
| Timestamp Result | GPU Ticks resolved into a buffer. Timestamp (in ns) = Timestamp(in ticks) * 109/ ID3D12CommandQueue:: GetTimestampFrequency() |
Nanoseconds resolved into a buffer | Nanoseconds resolved into a buffer |
- All native APIs support resolving the results from query objects to a buffer memory, the destination buffer can be accessed by following pipeline, such as using as conditional for the predicated rendering.
- Resolve operation must be outside render pass on D3D12 and Vulkan or render/compute encoder on Metal.
- The state or usage of the destination buffer must be
COPY_DESTon D3D12,MTLStorageModeSharedorMTLStorageModePrivateon Metal,UNIFORM_BUFFERandTRANSFER_DSTon Vulkan. - The offset in destination buffer must be a multiple of 8 bytes on D3D12 and Vulkan (if resolving results as 64-bit).
- For occlusion query, Vulkan specifies more tests in its spec, but these tests will also affect the occlusion results on D3D12 and Metal. If the depth/stencil tests are disabled, then the results is simply the area of the rasterized primitives.
- The query results are resolved as 32-bit or 64-bit unsigned integers with flag on Vulkan, and always resolved as 64-bit unsigned integers on D3D12 and Metal.
- We cannot return the results buffer directly because we need to perform post-processing by compute shader after getting the raw query results from the native APIs.
- Unify the results of binary occlusion queries.
- Compute the counters in pipeline statistics results which are different on three native APIs, we prefer to expose the common parts of them.
- Compute the difference of the two timestamp queries. The time delta may be negative due to the timestamp counter may be reset after a long time on some platforms. We can suggest users to skip the invalid time delta if it’s negative.
Proposal
Extensions
Add precise occlusion, pipeline statistics and timestamp queries in GPUExtensionName.
QuerySet
- Define
QuerySetinstead of individual query objects because Query objects (or sample buffers on Metal) can be allocated in a continuous part of memory. - Create and destroy
QuerySetonGPUDevice. - Set query set in
GPURenderPassDescriptorfor occlusion query due to Metal requiresvisibilityResultsBufferinMTLRenderPassDescriptorat render pass creation time.
Begin/End Query
- Occlusion query only supports begin/end on render pass encoder without passing query set which has been set in render pass descriptor.
- Pipeline statistics and timestamp queries support begin/end on both render pass encoder and compute pass encoder.
- We may need to perform different types of queries in the same render/compute pass encoder, so it’s better to pass a query set in beginQuery/endQuery for pipeline statistics and timestamp queries.
Resolve Query
Retrieve query results from query set, users can read the results from buffer memory or consume the result buffer directly.
- Queries results are resolved into GPU buffer:
| Query Types | Resolved Results |
|---|---|
| Binary Occlusion | 0/1 |
| Precise Occlusion | The number of samples passed depth/stencil tests. |
| Pipeline Statistics | The number of vertex shader invocations, primitives processed by the clip stage, primitives output by the clip stage, fragment shader invocations, compute shader invocations. |
| Timestamp | Time delta in nanoseconds. 0 for invalid results which need to be skipped. |
- All results in the GPU buffer are stored in a type of
GPUSize64. The offset must be a multiple of 8 bytes. - Add a new GPUBuffer usage for resolving queries, which avoid to expose more detailed information about buffer usage, and can be reused in predicated or conditional rendering.
Activity
kvark commentedon Mar 16, 2020
That's very detailed, thank you!. See also #72 for prior investigation.
litherum commentedon Mar 16, 2020
This looks very good!
One thing I'm worried about: it looks like this proposal requires timestamp queries on Metal to be implemented via MTLCounterSampleBuffer, which is only available on macOS 10.15+. I think having timestamp queries be unavailable on all iOS would be a mistake. In particular, timestamp (duration?) queries are likely the most important type of query, because the web developer doesn't know exactly which hardware their code will be running on, and so will need these queries to pick which code to use at runtime. In addition, iOS is a very important platform to Apple.
iOS has had GPUStartTime and GPUEndTime since iOS 10.3. I think we should modify the existing timestamp queries to be able to be implemented via these methods so WebGPU code would work out-of-the-box on iOS.
Add Query API
Add Query API
Kangz commentedon Mar 17, 2020
@haoxli
Thanks for the investigation and proposal, it looks great overall!
Splitting query methods (and making timestamp a single command): overall the three query types seem different enough that we could have different methods for each of them. (that's already the case but timestamp could be a different entrypoint). This would also mean timestamp queries could have a single
writeTimestampmethod instead of begin/end. The proposal explains that we could return time deltas, but imho the application can do a subtraction themselves, andif we really need to, we normalize the timestamps so they don't leak device-specific information. (or gate the extension on devtools, depending on browser choices).
Maybe removing Metal's constraint on giving the
GPUQuerySetonbeginRenderPass: if I remember correctly, all implementations of WebGPU on Metal will be recording theMTLCommandBufferonGPUQueue.submit. So it should be possible to count during WebGPU command recording time how many occlusion queries are used, then at submit time make a correctly-sizedMTLBufferthat's set asvisibilityResultBuffer(if needed at all).GPUQuerySetfor occlusion queries would need to become virtual and resolving into buffers would instead copy from theMTLBufferthat was created atGPUQueue.submittime. This would removeGPURenderPassDescriptor. occlusionQuerySet.**Simplify
end*Query**AFAIK occlusion and pipeline statistics queries cannot be nested, so we could remove the arguments fromend*Query.So for example the
GPURenderPasscommands would be:Here are some other changes that could be interesting:
Add timestamp queries on GPUCommandEncoder: It can be very interesting for applications to time their copy commands as well as other commands that we'll eventually put on the command encoder (and not in passes).
Allowing timing either the vertex part of the pipeline or the fragment part of the pipeline: with tiling architectures, the vertex and fragment stages for a single draw might not be run back to back and instead all vertex shaders can be processed before all fragment shaders. It would be interesting for timestamp queries to be used for timing only vertex work, or only fragment work.
Decide whether we should allow queries in render bundles.
@litherum
I'm worried about doing this: measuring performance of specific objects (say a character model) in a render pass is an extremely important usecase for timestamp queries. Putting timestamps on command buffer instead makes it almost impossible to do, or you would have to split a render pass which is inconvenient and would add noise to the measure. Maybe the timestamp query extension could be unsupported on iOS, or a different one designed to reflect the timestamp on the command buffer?
kvark commentedon Mar 17, 2020
That's not correct. Our implementation records on
endPasstoday, and we strongly desire this to be an implementation detail. The spec should allow for an implementation that immediately records commands as they come.haoxli commentedon Mar 19, 2020
In addition to eliminating the difference in timestamps across platforms, another reason to add begin/end for timestmaps is to make the three types of queries share the same set of interfaces as much as possible. We thought about using a single method like
writeTimestampin timestamp query, this has the advantage that the user can calculate the delta between any timestamp. We can nomalize the results by storing the difference of each timestamp with the first one, for example:But there are also some problems, such as:
haoxli commentedon Mar 19, 2020
GPUStartTimeandGPUEndTimeare very different from timestamp query. They are command buffer properties and does not need those query operations, and retrieved from CPU memory directly when the commands are completed.So it's better to have a separated interface on command buffer to get the timestamps. On Metal(iOS and macOS), they are queried in the
addCompletedHandler:callback, or after a call to thewaitUntilCompletedmethod. On D3D12 and Vulkan, we can insert timestamp queries at the beginning and end of command encoder, and read the timestamps back from resolved buffer when the commands are compeleted (after a call toID3D12FenceorvkQueueWaitIdle).Kangz commentedon Mar 24, 2020
The timestamp queries were discussed in the 2020-03-23 meeting.
The general consensus is that WebGPU without any of the optional features would allow timing at the GPUCommandBuffer level using a mechanism similar to Metal's
GPUStartTimeandGPUEndTimethat's not related toGPUQuerySet, since like you said they are retrieved in the CPU memory.There can be an optional feature that writes timestamps and personally I think a single
GPU*Encoder.writeTimestampis a good way to do it.To make progress I think the PR at #619 be split in the following way:
GPUQuerySetwith occlusion queries and the precise extension. If we can get away without havingGPURenderPassDescriptor.occlusionQuerySetthat would be ideal, but that's only a very small preference I have.GPUCommandBufferstart and end time that's unrelated to queries.I think 1) can be agreed upon rather quickly, and then 3) and 4) should be easy follow ups. 2) isn't very complicated conceptually but requires some more API design thoughts.
litherum commentedon Mar 27, 2020
I realized that this doesn’t actually work with tiling GPUs. On tiling GPUs, all the fragment processing for an entire pass is collapsed together to try to reduce overdraw. This means there there are no discrete points in time where one draw call ends and another one begins. Therefore, putting the
writeTimestamp()inside the encoders as individual commands doesn’t really work on tiling GPUs. Instead, it would have to be done at encoder boundaries.Kangz commentedon Mar 27, 2020
Oh, good point. My comment above asking for an additional stage mask was misguided since the tiling GPUs might break rendering in even more pieces than just vertex work and fragment work. I looked at GLES and Vulkan extensions and there doesn't seem to be a way to measure time taken per-tile :S.
haoxli commentedon Mar 30, 2020
I also checked that it seems only Vulkan support specifying a stage of the pipeline in
vkCmdWriteTimestamp.As mentioned above, on Metal, GPUStartTime and GPUEndTime are internal attributes in command buffer which always can be read when commands are completed. On D3D12 and Vulkan, we need to use timestamp query to get the timestamp at the beginning and end of command buffer. Maybe we also need a flag in encoders to turn the timing mechanism on, otherwise need enable the mechanism for all command buffers.
kainino0x commentedon Mar 30, 2020
Hm, since the result is async anyway, we could possibly use the presence of a callback as that flag....
10 remaining items
Kangz commentedon Jan 19, 2021
Sounds good, unless someone as an objection. Does the spec need to be changed?
kvark commentedon Jan 19, 2021
Removing the need for this 0/1 internal conversion would be nice! I have a concern about portability here. Unlike the timestamps, occlusion queries are in Core, so it's possible for malicious users to inspect their results for fingerprinting, potentially identifying different HW or different driver versions.
kainino0x commentedon Jan 19, 2021
If we're only concerned about fingerprinting, and not portability in general, then normalizing 0/1 is a decision that the user agent could make. I do have a minor concern about portability, but fixing this is probably not worth the dispatch cost.
haoxli commentedon Jan 20, 2021
It could identify that whether the client is Windows D3D12 or not. Tested on limited devices and platforms, we can get same non-zero value on Vulkan and Metal backend, it's like the number of samples passed occlusion testing (I'm not sure if it is true).
haoxli commentedon Jan 20, 2021
Yes, it does. We've documented that the non-precise occlusion query returns 0/1. When submitting the proposal, we thought that as a web standard, we should eliminate platform differences and return the same results, that's why we need internal compute shader.
Kangz commentedon Jan 20, 2021
Ok, let's make a PR that changes 0/1 to ==0 and >0 and start discussions. We accepted platforms differences for timestamps and I think we should accept them for non-precise occlusion queries too. (In the meantime for Dawn's implementation we can assume the group will accept the change).
kvark commentedon Jan 20, 2021
If the query result is used on GPU, would it be correct to assume that the users need 0/1 strictly? I.e. they'd follow with an indirect draw/dispatch command, as in the conditional rendering case we discussed in #551.
I assume this is one of the important cases we need to support. Do we then require the users to write their own compute pipeline that checks for zero and writes down 0/1 of these results? And after they get it, they'd end up wasting power on D3D12 backend, which already gives that for free.
Kangz commentedon Jan 21, 2021
I don't know how common the usage of occlusion queries for conditional rendering will be, but it's an advanced usage of WebGPU and I think developers can deal with adding the dispatch themselves. They are most likely to do a dispatch anyway because they aren't going to write 0/1 in the indirect buffer directly and instead are more likely to write the whole indirect buffer from a compute shader by looking at the resolved occlusion queries. Because this is very advanced usage, developers should be aware that the spec says ==0 and >0.
haoxli commentedon Jan 21, 2021
In conditional rendering, the native APIs just discard the commands if the passed condition value is not 0, not need 0/1 strictly (D3D12, Vulkan).
kvark commentedon Jan 21, 2021
@haoxli since we aren't exposing conditional rendering of the APIs, we concluded previously that they can do it themselves by doing indirect calls. These would require 0/1 and not 0/something.
@Kangz
I'd like to see this. I guess we don't have a clear understanding of how they are going to be doing the occlusion queries. My first thought was that the indirect buffers will be just uploaded from CPU, and the instance count will be copied into by the
resolveQuerySet. So there are no dispatches involved, it seems pretty simple, but only if the occlusion result is 0/1.kainino0x commentedon Jan 22, 2021
Note that would require an extra copyBufferToBuffer, because resolveQuerySet produces a 64 bit value but instanceCount is a 32 bit value. But the approach does seem tractable if occlusion produces 0/1.
kainino0x commentedon Aug 11, 2021
Dawn has found that on macOS <= 11.4 (fixed in 11.5.1, unsure about 11.5), on certain devices with intel gpus, calling sampleTimestamps just once permanently pins the GPU at max frequency until the process exits, making timestamps unusable.
Details here: https://crbug.com/1226078#c58
Known affected OSes/devices: https://crbug.com/1226078#c61
@litherum @grorg would it be possible for you to get a range of OSes/devices so we know what systems are affected?
Kangz commentedon Sep 2, 2021
Closing as this spec for this investigation / proposal has been landed. Further discussions can be in new issues.