Skip to content

timestamp-query is unimplementable on TBDR architectures #2046

Closed

Description

@litherum

The WebGPU spec says:

Timestamp query allows application to write timestamp values to a GPUQuerySet by calling writeTimestamp() on GPUComputePassEncoder or GPURenderPassEncoder or GPUCommandEncoder.

Metal is more complicated than this. Each MTLDevice has a function, supportsCounterSampling() which exposes the points at which the device is capable of writing timestamp values. It returns true/false in response to an enum value passed by the application:

  • atBlitBoundary: ... between blit commands ...
  • atDispatchBoundary: ... between kernel dispatches ...
  • atDrawBoundary: ... between draw commands ...
  • atStageBoundary ... at the start and end of a render pass’s vertex and fragment stages, and at the start and end of compute and blit passes ...
  • atTileDispatchBoundary: ... between tile dispatches ...

Therefore, in order for WebGPU's timestamp queries to be implementable on Metal, the device would need to report true for the atBlitBoundary, atDispatchBoundary, and atDrawBoundary enum values.

Apple Silicon devices do not return true for any of these values. Indeed, any TBDR renderer wouldn't be able to return true for atDrawBoundary because draw calls are not discrete items; all the vertex processing of all the draw calls in the render pass execute together, in parallel with all the fragment processing of all the draw calls in the render pass.

Apple Silicon devices only return true for atStageBoundary; all the other enum values return false. The way it's works is for the application to pass additional data into the render pass description. The additional data includes, for that render pass, which indices into which sample buffers that timestamps should be written into for the beginning and end of vertex and fragment processing. Indeed; there is no sampleCounters() call on any object which is available to Apple Silicon devices; the only way to get fine-grained timestamp data is using this declarative mechanism on the render pass descriptor.

One possible path forward here is to just say "well then I guess all TBDR renderers don't get to advertise the timestamp-query feature." This would be quite unfortunate, though, as I believe TBDR renderers represent a significant portion of the WebGPU group's target devices.

(Above, when I say "Apple Silicon devices", I'm referring to devices which support querying - I tested and verified iPhone 11, iPhone 12, and M1. Some older devices don't support querying at all - those shouldn't advertise support for timestamp-query feature.)

Activity

  1. kvark commented on Aug 18, 2021

    @kvark
    Contributor

    This is almost a dupe of #1956, but much more detailed (thank you for filing!).
    Timestamp queries were already a bit controversial with regard to reporting the actual time (have to derive the time/tick ratio, and it affects future execution on some Apple devices). And now we have this difference in how it's exposed and activated.
    Maybe it's time to go back to the drawing board and reconsider exposing this at all in WebGPU MVP?

  2. kainino0x commented on Aug 23, 2021

    @kainino0x
    Contributor

    Meeting: starting to converge on a direction. For render passes, change the API to declarative: ask for timestamps in beginRenderPass, instead of in commands.

  3. kainino0x commented on Aug 23, 2021

    @kainino0x
    Contributor
  4. kainino0x commented on Aug 23, 2021

    @kainino0x
    Contributor

    Vulkan links:

    vkCmdWriteTimestamp latches the value of the timer when all previous commands have completed executing as far as the specified pipeline stage, and writes the timestamp value to memory. When the timestamp value is written, the availability status of the query is set to available.
    https://www.khronos.org/registry/vulkan/specs/1.2/html/chap17.html#queries-timestamps
    https://www.khronos.org/registry/vulkan/specs/1.2/html/chap7.html#VkPipelineStageFlags

    I didn't find anything to control this in D3D12. I think this is still a gap where D3D12 doesn't represent TBDR well.

    The desktop architectures are also a good reason that Vulkan has this very complicated API with vkCmdWriteTimestamp that is a command, with very fine-grained control over how the implementation handles platform differences.

    I think it's OK if we don't expose that kind of control, and only give timing info for entire render passes, as I think that abstracts over backends and architectures more smoothly.

  5. kainino0x commented on Aug 23, 2021

    @kainino0x
    Contributor

    Unfortunately I think the Vulkan API can't tell us a "top of fragment stage" time, only a "bottom of vertex stage" time.

  6. mrshannon commented on Aug 23, 2021

    @mrshannon
    Contributor

    When using the current timestamp-query only draw calls show up, pipeline, bind group, and vertex buffer changes show 0. So whether this is because they are essentially free or the writeTimestamp calls are getting reordered around them I do not know.

    There is a difference between a timestamp written just before creating the render pass and one created as the first command on the render pass. In my testing this ranges from 2% to 40% depending on scene complexity, with the 40% rendering a single triangle and the 2% having 1000 draw calls. Therefore, I think it would be fine to make time queries run at the pass level, and not be able to run them within a pass.

    Though, I think we need to make it clear that the old charts of how much a given command costs is no longer valid, otherwise we will have people like me from the OpenGL and WebGL world thinking that sub pass timestamps are important.

  7. haoxli commented on Aug 24, 2021

    @haoxli
    Contributor

    On Metal, the ways of sampling counters at command boundaries and stage boundaries are different, sampling at stage boundaries needs to pass the sample buffer in render pass descriptor's sampleBufferAttachments. If we plan to only support timing entire render passes, the writeTimestamp will not be needed, we need set query set in render pass descriptor instead (same for non pass and compute pass).

  8. Kangz commented on Aug 24, 2021

    @Kangz
    Contributor

    Exactly! In the meeting @litherum said he would do a proposal shortly.

  9. kvark commented on Aug 24, 2021

    @kvark
    Contributor

    Hmm. If we want to support timestamps on render pass boundaries, does it still have to be a feature, or can we just have it for everybody? The metal implementation could split WebGPU command buffer into multiple Metal command buffers if it sees a render pass that needs to be timed, thus getting the time out of the command buffer.

  10. litherum commented on Aug 25, 2021

    @litherum
    ContributorAuthor

    The metal implementation could split WebGPU command buffer

    I think this would be novel, and the CG has stayed away from doing this until now. There is some (probably small, but still nonzero) cost with splitting command buffers, because the command buffer is the object which resource tracking operates on inside the Metal driver. More command buffers means more resource tracking.

    If you think it's worth investigating, I'm happy to gather some metrics / data to try to illustrate the costs of doing it.

    Unrelatedly, there's also the fact that Metal exposes command buffer execution duration via a getter on the CPU, so if we wanted to make it interact with GPUQuerySet, it would require its own upload to the GPU, which I'm not thrilled about. (Especially because this data came from the GPU originally; forcing WebGPU implementations to put it back on the GPU means it makes a full round-trip, when it could have just been kept there in the first place.)

  11. haoxli commented on Aug 25, 2021

    @haoxli
    Contributor

    there's also the fact that Metal exposes command buffer execution duration via a getter on the CPU

    Do you mean the GPUStartTime and GPUEndTime on MTLCommandBuffer, this is not related to GPUQuerySet, we have a separate executionTime on command buffer.

  12. litherum commented on Aug 25, 2021

    @litherum
    ContributorAuthor

    So I think the proposal would be:

    Part 1: Blits

    We already split blit command encoders arbitrarily, so GPUCommandEncoder.writeTimestamp() can probably stay. No change here.

    Part 2: Render passes

    Metal distinguishes between the start/end time of vertex processing and fragment processing, but desktop GPUs don't, so I think that means we have to just expose the beginning of the entire render pass and the end of the render pass. So, GPURenderPassEncoder.writeTimestamp() gets removed, and replaced with:

    enum RenderPassTimestampLocation {
        "beginning",
        "end",
        // Maybe more here in the future! Exciting!
    }
    
    dictionary RenderPassTimestampAttachments {
        required GPUQuerySet querySet;
        required GPUSize32 queryIndex;
        required RenderPassTimestampLocation location;
    }
    
    partial dictionary GPURenderPassDescriptor { // I don't think "partial dictionary" is actually a thing, but you get the idea anyway...
        sequence<RenderPassTimestampAttachments> timestampAttachments;
    }
    

    GPURenderPassDescriptor.timestampAttachments corresponds to:

    Part 3: Compute passes

    Metal's atStageBoundary field says:

    at the start and end of compute .. passes

    So I think the best we can do here is similar to render passes above. So, GPUComputePassEncoder.writeTimestamp() gets removed, and replaced with:

    enum ComputePassTimestampLocation { // Intentionally a distinct type from RenderPassTimestampAttachments
        "beginning",
        "end",
    }
    
    dictionary ComputePassTimestampAttachments {
        required GPUQuerySet querySet;
        required GPUSize32 queryIndex;
        required ComputePassTimestampLocation location;
    }
    
    partial dictionary GPUComputePassDescriptor {
        sequence<ComputePassTimestampAttachments> timestampAttachments;
    }
    

    GPUComputePassDescriptor is actually empty right now - this kind of proposal is exactly why it exists. So that was a neat bit of foresight.

    GPUComputePassDescriptor.timestampAttachments is parallel to GPURenderPassDescriptor.timestampAttachments, and therefore works similarly:

    This proposal intentionally differentiates between RenderPassTimestampLocation and ComputePassTimestampLocation because we may want to add "beginning of fragment processing" or "end of vertex processing" values to RenderPassTimestampLocation, but not ComputePassTimestampLocation.

  13. Kangz commented on Aug 25, 2021

    @Kangz
    Contributor

    Thank you for the detailed proposal! It looks great overall.

    Part 2: Render passes

    I think we can already add the distinction between vertex and fragment processing: many desktop GPUs are (soft-)tilers nowadays and Vulkan's vkCmdWriteTimestamp can measure the difference between the VS ending and the FS ending. However it can't measure the difference between VS and FS starting: implementations can just put the same timestamp twice. Likewise for D3D12 we could just write the same timestamps for VS and FS both for the beginning and the end. For both D3D12 and Vulkan we can then use a better API if one comes out in the future. WDYT? It might just be slightly confusing to developers that sometimes VS and FS are always in sync and sometimes not.

    nit: the "attachment" terminology is a bit weird for timestamp imho. What about timestampWrites: sequence<GPURenderPassTimestampWrite>

    Part 3: Compute passes

    Another option here is to keep writeTimestamp. Implementation on Metal devices without atDispatchBoundary would just split the compute pass in at this boundary. Like you said, this could have some cost because the state tracking is at pass boundary in Metal. However if we do what you suggested, then developers will have to manually split compute passes if they want to sample timestamps between dispatch, causing the same split of encoder, but on all Metal device, and with more work for the developer. So I think keeping GPUComputePassEncoder.writeTimestamp is marginally better.

  14. kvark commented on Aug 25, 2021

    @kvark
    Contributor

    Just for the record, I disagree with this.

    I think this would be novel, and the CG has stayed away from doing this until now.

    The CG stayed away from doing costy operations, like splitting a render pass because of the load/store ops.
    But splitting command buffers on the pass boundaries is not something we stay away from. In fact, we are already doing this unconditionally on Vulkan and D3D12 backends, because we have to inject the state transitions before the render pass, but we only know about them after we recorded the pass. I think any implementation that tries to do live recording of commands pretty much has to do this, and the group does want to support such kind of implementation, since it would be most efficient. So Metal would just follow the case in our eyes, not be an exception.

    In addition, I think Metal has ways to make resource tracking fully explicit with MTLResourceHazardTrackingModeUntracked, in addition to avoiding referencing resources with commandBufferWithUnretainedReferences. So the per-command-buffer overhead can be brought to a minimum, just like in other APIs.

  15. haoxli commented on Aug 27, 2021

    @haoxli
    Contributor

    Part 1: Blits

    I don't think we can keep the writeTimestamp. On Apple Silicon devices, [MTLBlitCommandEncoder sampleCountersInBuffer] (Metal implementation of writeTimestamp) is not supported, we only can sample counter at stage boundary on blit encoders by MTLBlitPassDescriptor.sampleBufferAttachments.

    Maybe we can just keep current writeTimestamp for desktop GPUs, and add another extension ('timestamp-attachments') for Apple Silicon to support sampling counters at stage bounary.

  16. 23 remaining items

  17. haoxli commented on Jul 25, 2022

    @haoxli
    Contributor

    Part 1: Blits
    We already split blit command encoders arbitrarily, so GPUCommandEncoder.writeTimestamp() can probably stay. No change here.

    Currently we use MTLBlitPassDescriptor.sampleBufferAttachments to implement writeTimestamp on command encoder on Metal backend for the devices support GPU counter sampling at stage boundary, but it cannot sample any counter values if there is no blit command on the blit encoder.

    commandEncoder.WriteTimestamp(querySet, queryIndex);
    

    We encode the command on Metal:

    MTLBlitPassDescriptor* descriptor = [[MTLBlitPassDescriptor alloc] init]
    descriptor.sampleBufferAttachments[0].sampleBuffer = querySet->GetCounterSampleBuffer();
    descriptor.sampleBufferAttachments[0].startOfEncoderSampleIndex = MTLCounterDontSample;
    descriptor.sampleBufferAttachments[0].endOfEncoderSampleIndex = NSUInteger(queryIndex);
    id<MTLBlitCommandEncoder> blit = [commandBuffer blitCommandEncoderWithDescriptor:descriptor];
    [blit endEncoding];
    

    The value at queryIndex is 0 which is expected to be GPU counter value. If we add a fill command [blit fillBuffer rang:NSMakeRange(0,1) value: 0] to the blit encoder, we can get correct value. If this is not a Metal bug, we need to remove WriteTimestamp API on command encoder and use timestampWrites instead, because we cannot add any blit commands to the blit encoder for implementing WriteTimestamp, which will eventually affect the correctness of the timestamp.

    @litherum Could you help to double check if this is a bug? I reported it to Apple Feedback Assistant, but no reply yet.

  18. reopened this on Jul 25, 2022
  19. litherum commented on Aug 4, 2022

    @litherum
    ContributorAuthor

    This is a bug in metal; I reported it back in April at rdar://91371767. Empty encoders never hit the GPU at all, and we aren’t counting the presence of timestampWrites as sufficient for non-emptiness.

    The workaround is just to encode some dummy blit command (but only in empty encoders which have timestampWrites specified).

  20. litherum commented on Aug 4, 2022

    @litherum
    ContributorAuthor

    I reported it to Apple Feedback Assistant

    What’s the FB number?

  21. Kangz commented on Aug 9, 2022

    @Kangz
    Contributor

    Closing again since it is confirmed to be a bug. @haoxli can you also provide the feedback number?

  22. haoxli commented on Aug 11, 2022

    @haoxli
    Contributor

    I reported it to Apple Feedback Assistant

    What’s the FB number?

    FB10510636

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions