Skip to content

Investigation: Query API #614

Closed
Closed

Description

@haoxli

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 (GPUStartTime and GPUEndTime) 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.

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_OCC
LUSION
Pipeline Statistics D3D12_QUERY_HEAP_TYPE
_PIPELINE_STATISTICS
MTLCommonCounterSetStatistic VK_QUERY_TYPE_PIP
ELINE_STATISTICS
Timestamp D3D12_QUERY_HEAP_TYPE
_TIMESTAMP
MTLCommonCounterSetTimestamp VK_QUERY_TYPE_TIM
ESTAMP

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 setVisibiltyResultMode with Boolean/Disabled to begin/end binary occlusion query (Counting for precise occlusion query).
  • D3D12 and Vulkan have begin and end operations. D3D12 controls binary/precise queries when calling BeginQuery with query type of D3D12_QUERY_TYPE_BINARY_OCCLUSION or D3D12_QUERY_TYPE_OCCLUSION, Vulkan controls them via call vkCmdBeginQuery with control 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 where sampleCountersInBuffer is called.
  • To implement pipeline statistics query on Metal, we can call sampleCountersInBuffer twice (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 vkGetQueryPoolResults
vkCmdCopyQueryPoolResults
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_DEST on D3D12, MTLStorageModeShared or MTLStorageModePrivate on Metal, UNIFORM_BUFFER and TRANSFER_DST on 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 QuerySet instead of individual query objects because Query objects (or sample buffers on Metal) can be allocated in a continuous part of memory.
  • Create and destroy QuerySet on GPUDevice.
  • Set query set in GPURenderPassDescriptor for occlusion query due to Metal requires visibilityResultsBuffer in MTLRenderPassDescriptor at 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

  1. kvark commented on Mar 16, 2020

    @kvark
    Contributor

    That's very detailed, thank you!. See also #72 for prior investigation.

  2. litherum commented on Mar 16, 2020

    @litherum
    Contributor

    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.

  3. added 2 commits that reference this issue on Mar 17, 2020
  4. Kangz commented on Mar 17, 2020

    @Kangz
    Contributor

    @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 writeTimestamp method instead of begin/end. The proposal explains that we could return time deltas, but imho the application can do a subtraction themselves, and
    if 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 GPUQuerySet on beginRenderPass: if I remember correctly, all implementations of WebGPU on Metal will be recording the MTLCommandBuffer on GPUQueue.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-sized MTLBuffer that's set as visibilityResultBuffer (if needed at all). GPUQuerySet for occlusion queries would need to become virtual and resolving into buffers would instead copy from the MTLBuffer that was created at GPUQueue.submit time. This would remove GPURenderPassDescriptor. occlusionQuerySet.

    **Simplify end*Query**AFAIK occlusion and pipeline statistics queries cannot be nested, so we could remove the arguments from end*Query.

    So for example the GPURenderPass commands would be:

        void beginOcclusionQuery(GPUQuerySet querySet, GPUSize32 queryIndex, boolean preciseOcclusion);
        void endOcclusionQuery();
    
        void beginPipelineStatisticsQuery(GPUQuerySet querySet, GPUSize32 queryIndex);
        void endPipelineStatisticsQuery(GPUQuerySet querySet, GPUSize32 queryIndex);
    
        void writeTimestamp(GPUQuerySet querySet, GPUSize32 queryIndex);
    

    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

    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.

    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?

  5. kvark commented on Mar 17, 2020

    @kvark
    Contributor

    if I remember correctly, all implementations of WebGPU on Metal will be recording the MTLCommandBuffer on GPUQueue.submit

    That's not correct. Our implementation records on endPass today, and we strongly desire this to be an implementation detail. The spec should allow for an implementation that immediately records commands as they come.

  6. haoxli commented on Mar 19, 2020

    @haoxli
    ContributorAuthor

    This would also mean timestamp queries could have a single writeTimestamp method instead of begin/end. The proposal explains that we could return time deltas, but imho the application can do a subtraction themselves, and
    if we really need to, we normalize the timestamps so they don't leak device-specific information.

    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 writeTimestamp in 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:

    Actual Timestamps 10000 10002 10005 9999 10003
    Resolved into buffer 0 2 5 0 4
    If a timestamp is reset, we will store it as 0, the next timestamp will be computed based on the reset one.

    But there are also some problems, such as:

    1. We need to investigate if this can achieved by the compute shader.
    2. Users need to make sure that there is no zero value between the two timestamps when calculating the delta. For example, if we calculate the delta of the second value and fifth value in above table, even if the result is positive, it is invalid.
  7. haoxli commented on Mar 19, 2020

    @haoxli
    ContributorAuthor

    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.

    Maybe the timestamp query extension could be unsupported on iOS, or a different one designed to reflect the timestamp on the command buffer?

    GPUStartTime and GPUEndTime are 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 the waitUntilCompleted method. 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 to ID3D12Fence or vkQueueWaitIdle).

  8. Kangz commented on Mar 24, 2020

    @Kangz
    Contributor

    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 GPUStartTime and GPUEndTime that's not related to GPUQuerySet, 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.writeTimestamp is a good way to do it.

    To make progress I think the PR at #619 be split in the following way:

    1. Add GPUQuerySet with occlusion queries and the precise extension. If we can get away without having GPURenderPassDescriptor.occlusionQuerySet that would be ideal, but that's only a very small preference I have.
    2. Add a mechanism for getting a GPUCommandBuffer start and end time that's unrelated to queries.
    3. Add a pipeline statistics extension and entrypoints.
    4. Add a writeTimestamp extension and entrypoints.

    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.

  9. litherum commented on Mar 27, 2020

    @litherum
    Contributor

    There can be an optional feature that writes timestamps and personally I think a single GPU*Encoder.writeTimestamp is a good way to do it.

    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.

  10. Kangz commented on Mar 27, 2020

    @Kangz
    Contributor

    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.

  11. haoxli commented on Mar 30, 2020

    @haoxli
    ContributorAuthor

    I also checked that it seems only Vulkan support specifying a stage of the pipeline in vkCmdWriteTimestamp.

    Add a mechanism for getting a GPUCommandBuffer start and end time that's unrelated to queries.

    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.

  12. kainino0x commented on Mar 30, 2020

    @kainino0x
    Contributor

    Hm, since the result is async anyway, we could possibly use the presence of a callback as that flag....

  13. 10 remaining items

  14. Kangz commented on Jan 19, 2021

    @Kangz
    Contributor

    Sounds good, unless someone as an objection. Does the spec need to be changed?

  15. kvark commented on Jan 19, 2021

    @kvark
    Contributor

    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.

  16. kainino0x commented on Jan 19, 2021

    @kainino0x
    Contributor

    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.

  17. haoxli commented on Jan 20, 2021

    @haoxli
    ContributorAuthor

    it's possible for malicious users to inspect their results for fingerprinting, potentially identifying different HW or different driver versions.

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

  18. haoxli commented on Jan 20, 2021

    @haoxli
    ContributorAuthor

    Sounds good, unless someone as an objection. Does the spec need to be changed?

    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.

  19. Kangz commented on Jan 20, 2021

    @Kangz
    Contributor

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

  20. kvark commented on Jan 20, 2021

    @kvark
    Contributor

    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.

  21. Kangz commented on Jan 21, 2021

    @Kangz
    Contributor

    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.

  22. haoxli commented on Jan 21, 2021

    @haoxli
    ContributorAuthor

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

  23. kvark commented on Jan 21, 2021

    @kvark
    Contributor

    @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

    instead are more likely to write the whole indirect buffer from a compute shader by looking at the resolved occlusion queries

    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.

  24. kainino0x commented on Jan 22, 2021

    @kainino0x
    Contributor

    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.

  25. kainino0x commented on Aug 11, 2021

    @kainino0x
    Contributor

    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?

  26. Kangz commented on Sep 2, 2021

    @Kangz
    Contributor

    Closing as this spec for this investigation / proposal has been landed. Further discussions can be in new issues.

  27. deleted a comment from fwadnjar on Oct 26, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions