Skip to content

Indirect draw/dispatch commands investigation #31

Closed

Description

@Kangz

Native APIs provide ways to emit draws and dispatches that take arguments from buffers on the GPU which is useful when some of the parameters are computed on the GPU.

Native APIs

Metal

In Metal indirect commands are done by passing an indirect buffer and an offset to commands instead of the parameters:

@protocol MTLRenderCommandEncoder <MTLCommandEncoder>
    - (void) drawPrimitives: (MTLPrimitiveType) primitiveType
             indirectBuffer: (id <MTLBuffer>) indirectBuffer
       indirectBufferOffset: (NSUInteger) indirectBufferOffset;

    - (void) drawIndexedPrimitives: (MTLPrimitiveType) primitiveType
                         indexType: (MTLIndexType) indexType
                       indexBuffer: (id <MTLBuffer>) indexBuffer
                 indexBufferOffset: (NSUInteger) indexBufferOffset
                    indirectBuffer: (id <MTLBuffer>) indirectBuffer
              indirectBufferOffset: (NSUInteger) indirectBufferOffset;
@end

@protocol MTLComputeCommandEncoder <MTLCommandEncoder>
    - (void) dispatchThreadgroupsWithIndirectBuffer: (id <MTLBuffer>) indirectBuffer
                               indirectBufferOffset: (NSUInteger) indirectBufferOffset
                              threadsPerThreadgroup: (MTLSize) threadsPerThreadgroup;
@end

The format of the indirect buffers is defined by:

typedef struct {
    uint32_t vertexCount;
    uint32_t instanceCount;
    uint32_t vertexStart;
    uint32_t baseInstance;
} MTLDrawPrimitivesIndirectArguments;

typedef struct {
    uint32_t indexCount;
    uint32_t instanceCount;
    uint32_t indexStart;
    int32_t  baseVertex;
    uint32_t baseInstance;
} MTLDrawIndexedPrimitivesIndirectArguments;

typedef struct {
    uint32_t threadgroupsPerGrid[3];
} MTLDispatchThreadgroupsIndirectArguments;

Vulkan

Vulkan is very similar to Metal except that:

  • the primitive type is taken from the last VkCmdBindPipeline
  • the index buffer / type and offset are taken from the last VkCmdBindIndexBuffer
  • the commands allow sending multiple draws at a fixed stride in the buffer; the maximum number for drawCount is a device limit that has to be at least 1.
  • baseInstance must be 0 unless the drawIndirectFirstInstance is enabled.
void vkCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset, uint32_t drawCount, uint32_t stride);
void vkCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset, uint32_t drawCount, uint32_t stride);
void vkCmdDispatchIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset);

The format of the indirect buffers is defined by:

typedef struct VkDrawIndirectCommand {
    uint32_t    vertexCount;
    uint32_t    instanceCount;
    uint32_t    firstVertex;
    uint32_t    firstInstance;
} VkDrawIndirectCommand;

typedef struct VkDrawIndexedIndirectCommand {
    uint32_t    indexCount;
    uint32_t    instanceCount;
    uint32_t    firstIndex;
    int32_t     vertexOffset;
    uint32_t    firstInstance;
} VkDrawIndexedIndirectCommand;

typedef struct VkDispatchIndirectCommand {
    uint32_t    x;
    uint32_t    y;
    uint32_t    z;
} VkDispatchIndirectCommand;

D3D12

In D3D12 executing commands indirectly is done through "command signature" that are a super-set of what's available in Metal and Vulkan. First a command signature is created that represents the order and layout of commands in the command buffer, then this signature is passed along with the indirect buffer to ID3D12GraphicsCommandList::ExecuteIndirect.

The interesting bits are:

  • That the layout of the D3D12_DRAW_ARGUMENTS, D3D12_DRAW_INDEXED_ARGUMENTS and D3D12_DISPATCH_ARGUMENTS structures match the respective structures in Metal and Vulkan.
  • A command signature has to be created against a root signature (because there are indirect commands to change root constants and descriptors).
  • Command signatures can take the maximum number of commands to process from a "count buffer" which makes command signatures a super-set of "MultiDrawIndirect".
typedef struct D3D12_DRAW_ARGUMENTS {
  UINT VertexCountPerInstance;
  UINT InstanceCount;
  UINT StartVertexLocation;
  UINT StartInstanceLocation;
} D3D12_DRAW_ARGUMENTS;

typedef struct D3D12_DRAW_INDEXED_ARGUMENTS {
  UINT IndexCountPerInstance;
  UINT InstanceCount;
  UINT StartIndexLocation;
  INT  BaseVertexLocation;
  UINT StartInstanceLocation;
} D3D12_DRAW_INDEXED_ARGUMENTS;

typedef struct D3D12_DISPATCH_ARGUMENTS {
  UINT ThreadGroupCountX;
  UINT ThreadGroupCountY;
  UINT ThreadGroupCountZ;
} D3D12_DISPATCH_ARGUMENTS;

Links to relevant parts of the D3D12 documentation:

Proposed API

All three APIs use the same layout for commands in the indirect buffer, which makes things easier. Because of restrictions of Metal and Vulkan, sending only a single DrawIndirect, DrawIndexedIndirect or DispatchIndirect command at a time should be supported.

The arguments for each of these should be an indirect buffer and offset, and that's it because the rest of the data will be present either in the last bound pipeline state, or in the last bound index buffer. Obviously graphics commands will have to be done in a render pass, and likewise the compute command should be done in a compute pass.

void CommandBuffer::DrawIndirect(Buffer* indirectBuffer, uint32_t indirectOffset);
void CommandBuffer::DrawIndexedIndirect(Buffer* indirectBuffer, uint32_t indirectOffset);
void CommandBuffer::DispatchIndirect(Buffer* indirectBuffer, uint32_t indirectOffset);

// Indirect buffer layout same as D3D12, Metal and Vulkan

Open question: Some Adreno 4XX and 5XX GPUs don't support drawIndirectFirstInstance. Should we require it anyways?

Activity

  1. dmikis commented on Oct 3, 2017

    @dmikis

    Am I right to say that we'll accept only data that's been validated on CPU side (somewhat like index buffers work in WebGL now) (UPD: read the investigation a bit closely and it seems like the answer is no)? If not, what about potential security problems like out-of-bounds accesses and such?

  2. Kangz commented on Oct 3, 2017

    @Kangz
    ContributorAuthor

    We can't really pre-validate the data on the CPU, or need to do a readback which would defeat the purpose. In most cases we should be able to rely on robust buffer access to avoid OOBs. If we can't do this, we might be able to insert a shader just before that clamps the values in the buffer, and another one after that resets the data in the buffer. It would be ugly though.

    Another alternative if we don't have robust buffer access it to do "programmable vertex pulling" in the vertex shaders and do the clamping there.

  3. litherum commented on Oct 4, 2017

    @litherum
    Contributor

    We should be careful and precise when discussing this topic. "Indirection" means different things to different people. There are (at least) 3 different related topics:

    1. Modifying the set of visible resources to a shader from the GPU
    2. Holding resources inside other resources. For example, holding a reference to a texture inside a buffer. (But constructing the contents of the buffer happens on the CPU)
    3. Specifying the counts/offsets of vertices/instances/indices from buffers instead of CPU-side arguments to draw calls

    I believe that topics 1 and 2 are not possible in Vulkan, so we shouldn't include them in our API. We should make sure to cover this in the group to make sure we all agree about this.

    Regarding topic 3: This feature is valuable because it enables things like particle effects where particles are generated and destroyed on the GPU, so the CPU never actually knows how many particles there are.

    However, this gets tricky because indices may access outside of the bounds of a vertex buffer (or the number of vertices is larger than the index/vertex buffer). WebGL solves this problem by requiring validation. There seems to be 5 different ways we could approach this problem:

    1. Don't have this feature
    2. Proceed as if no validation is necessary. This is almost certainly unacceptable because it could very easily lead to a WebGPU program able to read GPU data that it shouldn't have access to. (WebGPU should be available on devices which don't have any "Robustness" extension.)
    3. Roundtrip through the CPU. This is almost certainly unacceptable because it defeats the whole point of the feature.
    4. Perform the validation in a compute shader. We can use the fact that WebGPU programs are not allowed to have any data dependencies within a single pass, which means the draw parameters must have been generated by a previous pass. If we enforce the policy that every command buffer contains exactly one pass, we can then, at the time of the drawIndirect(), construct a new command buffer and pass, and when the draw command's command buffer gets committed, we commit our new compute buffer just before it. The compute shader would map the argument buffer read/write, and if the validation fails, it would fill the relevant section of the buffer with 0s so the subsequent drawIndirect command would have no effect. (Not sure if resetting the values in the buffer back to their original values is actually necessary; this might be the way to detect from user code whether or not you did anything wrong.)
    5. Perform the validation at the top of the vertex shader. We would have to compile every vertex shader with a check at the beginning that looks at builtins like gl_VertexID and some uniforms in order to determine if the shader should be running or not. If not, the vertex shader would return early filling in 0s for all output variables. This check would occur before any user-code executes, so the user has no chance to read any data they shouldn't have access to. We would have to add these checks to the beginning of every vertex shader because we don't know which shaders will be used for indirect rendering. If the shader isn't used for indirect rendering, we would have to pass INT_MAX into the uniform (or whatever is necessary to make sure the checks pass). If the input assembler actually copies the data into the shader rather than passing the shader a pointer to the data, we would have to rewrite the vertex shader not to use attributes but instead to pass the vertex buffer itself and have the vertex shader access it (to make sure the input assembler doesn't crash on reading data the MMU hasn't mapped).

    It seems like option 4 is the cleanest / safest / easiest option.

    @Kangz mentions "All three APIs use the same layout for commands in the indirect buffer." Are we sure this is true? vertexOffset in Vulkan sounds like a byte offset, where baseVertex in Metal sounds like an index of a vertex. If the different APIs actually have different meanings for these fields, we'll have to make the validation code also fixup the argument buffer so it has the correct values.

  4. litherum commented on Oct 4, 2017

    @litherum
    Contributor

    Whoops, pressed the wrong button by accident!

  5. changed the title [-]Indirect commands investigation[/-] [+]Indirect draw/dispatch commands investigation[/+] on Oct 4, 2017
  6. Kangz commented on Oct 4, 2017

    @Kangz
    ContributorAuthor

    We should be careful and precise when discussing this topic. "Indirection" means different things to different people. There are (at least) 3 different related topics

    Good point, like you pointed out only 3) is possible in Vulkan and baseline Metal, 1) and 2) are possible in some ways in D3D12 and Metal 2 but we shouldn't look at them. Updated the title to reflect this.

    vertexOffset in Vulkan sounds like a byte offset, where baseVertex in Metal sounds like an index of a vertex.

    Hadn't though about it, I double checked Vulkan and D3D12 and for both of these the offsets or start locations are in indices too. Things still match (phew 😌)

    Thanks for the robustness analysis, obviously 3) is not good, and I agree 1) would be sad for a v1 (would be ok for MVP).

    Solution 2) would actually work on all hardware on D3D12 and on Vulkan when the robustBufferAccess feature enabled. I would assume most hardware is capable of cheap robust buffer access for attributes and index given it is default in D3D12 (not sure about Apple's mobile GPUs though). @litherum do we have data whether index / attribute clamping is performed for free in Metal? I didn't find anything in the doc. If Metal has that behavior we could go for 2) and do expensive emulation on Vulkan when we don't have robustBufferAccess (the cost doesn't really matter).

    Solution 4) sounds good for cases where we don't have robust attributes / indices, but when 2) is possible it would be preferable to use it instead of 4). If there is both 2) and 4) being used, we should make sure they look equivalent to applications and replace buffers at the last moment as much as possible. For example the compute shader you mention could copy from the application provided indirect buffer into a scratch indirect buffer so that we don't need to modify the application's buffers.

    Solution 5) is also interesting if we are able to do 2) in most cases (only some Vulkan platforms requiring emulation) as it would put most of the complexity of the emulation in the shader and outside of the CPU rendering loop. We could make use of a bool usedIndirectly in the pipeline state for 5) too but it would be a bit constraining.

  7. litherum commented on Oct 4, 2017

    @litherum
    Contributor

    Sounds like we should define this in terms of semantics of what is visible to the programmer. That way, the browser can choose between options 2, 3, 4, and 5 depending on the capabilities of the current hardware (and any other signals it feels like considering).

    We may want to discuss requiring a Robustness extension during the call tomorrow.

  8. dmikis commented on Oct 4, 2017

    @dmikis

    we might be able to insert a shader just before that clamps the values in the buffer

    A thought on clamping buffer accesses: whereas it's a sensible decision to provide sufficient security level, that may either mask erroneous behaviours or produce hard to debug ones in non-malicious apps. I think we can assume that any out-of-bounds access is either an error or a malicious intent, and in both cases we're at liberty to do whatever we need to ensure we don't leak data or cause denial of service. However, that may complicate debugging process for developers with good intentions :). I suggest we introduce a debug layer that modifies clamped accesses with some kind of debug output, i.e.:

    vec4 u = us[i];
    
    // in "production mode" turns into
    
    vec4 u = us[clamp(i, 0, us.length)];
    
    // but in "debug mode":
    
    if (i < 0 || us.length <= i) {
        writeToDebugBufferUsefulInfo();
    }
    
    vec4 u = us[clamp(i, 0, us.length)];
    
    // then somewhere on CPU side:
    
    if (debugBufferWasWrittenTo) {
        throw new Error(readUsefulInfoFromFromDebugBuffer());
    }
    

    That will introduce performance penalties, but may be invaluable during app debugging.

  9. litherum commented on Oct 4, 2017

    @litherum
    Contributor

    I just heard back from the Metal team:

    There are no protections at all against reading off the end of a vertex array

    Also, Kirill's point during the meeting is particularly salient - not including indirect draws doesn't absolve us of doing validation on the GPU, because the GPU may populate an index buffer.

    Therefore, I think we have two options:

    1. Perform validation according to the ways I mentioned before.
    2. For all prior draw calls or dispatch calls, the system detects, either through shader inspection or through explicit annotation, which buffers are readable and which buffers are writable. The runtime would then forbid using any buffer from being used as an index buffer if it has ever been used in a writable manner by the GPU.
  10. Kangz commented on Oct 5, 2017

    @Kangz
    ContributorAuthor

    There are no protections at all against reading off the end of a vertex array

    That's unfortunate but with solution 4) or 5) in your previous comment I'm sure we can make indirect draws work efficiently.

    1. Perform validation according to the ways I mentioned before.

    Solution 5) where OOB attributes get detected in the vertex shader and replaced with zeros looks like it would work well and efficiently, the hardest part being giving the vertex shader the size of the attribute buffers.

    1. For all prior draw calls or dispatch calls, the system detects, either through shader inspection or through explicit annotation, which buffers are readable and which buffers are writable. The runtime would then forbid using any buffer from being used as an index buffer if it has ever been used in a writable manner by the GPU.

    This completely prevents the index data generation on the GPU which is a bit limiting. For D3D12 and Vulkan we'll have to declare what uses of the shader are possible when they are created, so we could forbid a combination of BufferUsage::Index with anything but BufferUsage::CPUWrite or something.

  11. dmikis commented on Oct 5, 2017

    @dmikis

    This completely prevents the index data generation on the GPU which is a bit limiting.

    IIUC, we include compute shaders to MVP. Limiting index buffers to be modifiable only from CPU may hurt pushing geometry processing to GPU (via compute shaders) which is a concern for us.

  12. kvark commented on Oct 5, 2017

    @kvark
    Contributor

    @Kangz

    the hardest part being giving the vertex shader the size of the attribute buffers.

    To clarify, we only need the shortest (one with that has less or equal number of elements than others) vertex buffer among the ones stepped with vertex frequency.

    My biggest concern here is whether or not we can only have that clamping in Metal. Other backends have the luxury of robustness guarantees, and providing this extra value in Metal would certainly be a bit easier (given no need for pipeline layouts/signatures and such). Thus, for me this comes down to a question if our portability guarantee includes the misbehaving code in its scope.

    I do agree that having the bad behavior handled consistently would help developers. I don't agree that we should make the good behavior suffer (in performance) because of it. So I'd prefer this to be handled:

    • by the (optional) GPU validation layer on all backends, possibly with extracting more info (index offset/value and such)
    • unconditionally on Metal only
  13. dmikis commented on Oct 5, 2017

    @dmikis

    I do agree that having the bad behavior handled consistently would help developers. I don't agree that we should make the good behavior suffer (in performance) because of it. So I'd prefer this to be handled:

    • by the (optional) GPU validation layer on all backends, possibly with extracting more info (index offset/value and such)
    • unconditionally on Metal only

    I agree. out-of-bounds accesses are either a malicious intent or an error, and well-formed apps should not suffer performance costs of portable validation and access clamping (i.e., ensuring that every implementation does the same thing on OOB access). I'm feeling comfortable leaving behaviour in case of OOB accesses as "implementation defined" and delegating catching and reporting such errors in a portable and consistent way to debug/validation layers or tools.

  14. devshgraphicsprogramming commented on Nov 14, 2018

    @devshgraphicsprogramming

    Because of restrictions of Metal and Vulkan, sending only a single DrawIndirect, DrawIndexedIndirect or DispatchIndirect command at a time should be supported.

    Vulkan supports MultiDrawIndirect through extensions.

    Open question: Some Adreno 4XX and 5XX GPUs don't support drawIndirectFirstInstance. Should we require it anyways?

    That is yet another Vulkan/OpenGL extensions called draw_parameter or something similar.
    If its not there you should let the user know its not there, then they can emulate with some well-documented hacks (such as using extra per-instance vertex data etc.).

    Limiting index buffers to be modifiable only from CPU may hurt pushing geometry processing to GPU (via compute shaders) which is a concern for us.

    Confer with #117 its my proposal to validating GPU sourced data on the GPU, you could also validate indirect draw parameters as well as index buffers with compute shaders (zero-out invalid indirect draw structs so nothing will get drawn).

  15. alecazam commented on Jun 17, 2021

    @alecazam

    The Metal API doesn't appear to take a drawCount. Considering these are meant to be dynamic buffers with culled elements in them, not being able to specify a count cpu-side seems rather limiting as is drawing the remains of a buffer that's all zero-ed out.

    An indirectBufferOffset specifier is not a range. Even calls that take instances specify an instanceCount, and the vb/ib are specified as offsets and ranges of data. This Metal API seems rather incomplete as a result, unless I'm missing a bind to limit the range. Even Metal ICB's have executeCommandsInBuffer which takes a range.

    It looks like Metal draws one indirect draw per drawIndexedPrimitive call. If you have 100 indirect draws, then you must call this 100 times each time with a different offset. In Vulkan, it could be called once with a count of 100. I've pinged Apple to add a drawCount, but won't hold my breath since they've moved onto ICB's.

    Even the D3D12 call has a MaxCommandCount, so Metal is the deficient API in this case.

    void ExecuteIndirect(
      ID3D12CommandSignature *pCommandSignature,
      UINT                   MaxCommandCount, <- 
      ID3D12Resource         *pArgumentBuffer,
      UINT64                 ArgumentBufferOffset,
      ID3D12Resource         *pCountBuffer,
      UINT64                 CountBufferOffset
    );
    
  16. alecazam commented on Jul 2, 2021

    @alecazam

    Metal lacks the stride argument that lets one write the material data to the same buffer from the GPU. And Metal also lacks drawCount/multitdraw which allows Vulkan to turn indirect draw into a single draw call.

    Seems that the same A9+ that support IndirectDraw also support IndirectCommandBuffer and that supports ranged submission. So that might be the better complement to the Vulkan calls.

  17. Kangz commented on Sep 2, 2021

    @Kangz
    ContributorAuthor

    Closing. The simple indirect commands have been added and there's additional proposals for drawIndirectCount and friends. DrawIndirectFirstInstance is not required and the validation rule added for that purpose in the spec.

  18. Try commented on Jun 21, 2023

    @Try

    Hello,
    I was looking into similar case for my engine lately... your DX12 maybe incorrect, base on sources from here:
    https://github.com/gfx-rs/gfx/blob/bc77309afdb0829605982370a3e17382c5968071/src/backend/dx12/src/command.rs#L2197

    Assuming you still aiming Vulkan-like execution:
    DX12 does not have gl_NumWorkGroups builtin (not 100% sure, if wgls support that)
    gl_InstanceIndex/gl_VertexIndex do behave differently:
    In DX12 they always start with zero, regardless of baseVertex/baseInstance; base* parameter do affect only fixed-function vertex pull.

  19. kainino0x commented on Jun 21, 2023

    @kainino0x
    Contributor

    @Try this is the WebGPU specification standardization repo. If you have a bug in the gfx-rs implementation please file a bug against the appropriate gfx-rs/* repository. Also please note that https://github.com/gfx-rs/gfx is in maintenance mode (or possibly unmaintained) in favor of https://github.com/gfx-rs/wgpu.

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