Skip to content

Proposal: Dynamic uniform and storage buffer offsets #116

Closed

Description

@Kangz

In a typical application, most draws will use different uniforms values for things like the world position and orientation. In the current state of WebGPU this means that a new bind group needs to be created for each draw (or reused from a cache) to set the right uniforms. Bind group creation is expected to be more expensive than recording draws because they incur an allocation. To reduce the number of bind groups that need to be created, WebGPU could introduce a concept of dynamic uniform/storage buffers. The proposal is at the bottom but the API would be somewhat similar to Vulkan.

Vulkan

Vulkan has a descriptor type called VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC that can be specified in VkDescriptorSetLayoutBinding::descriptorType that means this binding will be a dynamic uniform buffer binding. Then dynamic offsets are passed to vkCmdBindDescriptorSets via dynamicOffsetCount and pDynamicOffsets. This causes dynamic uniform buffers to be bound at an offset that is the base offset already present in the descriptor set plus the respective element of pDynamicOffsets (the ordering of pDynamicOffsets is the same ordering as dynamic buffers in the descriptor set layout).

Metal

In Metal, every time a buffer is bound, it gets passed an offset.

D3D12

The binding model here is the most flexible. Dynamic buffers can be implemented in a variety of ways:

  1. The dynamic offset can be stored as a root constant and added to every access to [RW]ByteAddressedBuffer. This wouldn't work for uniform buffers though.
  2. The virtual address of the offset can be computed and stored in a root UAV/CBV descriptor using ID3D12GraphicsCommandList::SetComputeRootConstantBufferView and ID3D12GraphicsCommandList::SetComputeRootUnorderedAccessView (or their SetGrahpics equivalents).
  3. The descriptor can be computed and stored in descriptor heap, kind of like a new copy of the bind group with a different offset.
  1. seems like the best choice, but root table space is limited so we'd have to aggressively limit the number of dynamic buffers per pipeline layout.

Proposal

The WebGPU version would look similar to the Vulkan model:

partial enum WebGPUBindingType {
    "dynamicUniformBuffer",
    "dynamicStorageBuffer",
};

partial interface WebGPUProgrammablePassEncoder {
    void setBindGroup(u32 index, WebGPUBindGroup bindGroup, sequence<u32>? dynamicOffsets);
}

Activity

  1. magcius commented on Nov 15, 2018

    @magcius

    Would there be any restriction on the alignment of dynamicOffsets? GL often has GL_UNIFORM_BUFFER_ALIGNMENT being 1024.

  2. devshgraphicsprogramming commented on Nov 15, 2018

    @devshgraphicsprogramming

    Yes all APIs have restrictions on the alignment of dynamic offsets, the exact offset varies at runtime and depends on the resource and GPU, but for UBOs it is usually at least 256

  3. devshgraphicsprogramming commented on Dec 6, 2018

    @devshgraphicsprogramming

    I have examined the Dec 3 meeting minutes, you seem to think that you're faced with a choice between dynamic buffer offsets and root constants.

    This is completely not the case, you NEED both, they are complementary.

  4. Kangz commented on Dec 6, 2018

    @Kangz
    ContributorAuthor

    I believe we said:

    • We need at least one of the two for the MVP
    • Having both causes more complication because they will fight for root table space so we might have to introduce a combined limit for pushConstantSize + N * DynamicBufferCount.
  5. devshgraphicsprogramming commented on Dec 6, 2018

    @devshgraphicsprogramming

    If your push-constant-size is the lowest common denominator across all APIs and vendors (128 bytes = 32 DWORDS ) then you should still have a lot of room left in the root-table (32 root signatures, 16 root descriptors).

    You can make the root/push constants even less (64 bytes, enough for a single 4x4 matrix or 16 IDs) for all I care.

  6. grorg commented on Dec 10, 2018

    @grorg
    Contributor

    This was discussed in the 10 Dec 2018 meeting

  7. litherum commented on Dec 14, 2018

    @litherum
    Contributor

    We just discovered that the binding model is compatible with argument buffers on Metal, where each WebGPUBindGroupLayout corresponds to two MTLArgumentEncoders and each WebGPUBindGroup is two MTLBuffers. Even better, argument buffers (not indirect argument buffers) are compatible with all Metal hardware, so there is no reason not to use them.

    In this design, there is no natural way to implement void setBindGroup(u32 index, WebGPUBindGroup bindGroup, sequence<u32>? dynamicOffsets);. The closest API we have would be MTLArgumentEncoder.setBuffer() which can't be used to implement this API.

    Instead, the generated Metal Shading Language code would accept an extra buffer, not represented in the Javascript program, which contain the offsets. Then, the shader's prologue would start with something like Foo* newValue = reinterpret_cast<Foo*>(reinterpret_cast<char*>(oldValue) + offset[offsetIndex]) for each dynamic buffer.

    Alternately, we could defer running MTLArgumentEncoder.setBuffer() until WebGPUProgrammablePassEncoder.setBindGroup().

  8. litherum commented on Dec 14, 2018

    @litherum
    Contributor

    For the Direct3D backend, I'm not sure the line of code above is representable in HLSL without making every dynamic buffer a ByteAddressBuffer and reconstituting every item in the buffer from its constituent bytes. Maybe DXIL can represent it?

  9. devshgraphicsprogramming commented on Dec 15, 2018

    @devshgraphicsprogramming

    Why don't you change it so you have to specify the buffer binding up-front but only the offset can be set dynamically?

    Even Vulkan doesn't allow for dynamically specifying the buffer and the offset, only the offset is dynamic.

    It's generally not a good idea to have state that is more mutable than the native APIs, because you'll have to do lots of hashing behind the scenes and runtime generation of descriptor sets+layouts or root signatures (that's where the shader compilation can happen).

  10. litherum commented on Dec 16, 2018

    @litherum
    Contributor

    Why don't you change it so you have to specify the buffer binding up-front but only the offset can be set dynamically?

    This is what I’m describing.

  11. litherum commented on Dec 16, 2018

    @litherum
    Contributor

    I guess we could also solve this problem by saying offset means “an integral number of items” where an “item” is the type of an element in the buffer in the shading language.

  12. devshgraphicsprogramming commented on Dec 16, 2018

    @devshgraphicsprogramming

    Why is there no mention of stride or bytestride in your vertex format spec?

  13. devshgraphicsprogramming commented on Dec 16, 2018

    @devshgraphicsprogramming

    I guess we could also solve this problem by saying offset means “an integral number of items” where an “item” is the type of an element in the buffer in the shading language.

    That's what baseVertex is for in usual Draw(Elements) calls, offset needs to be a byte offset (with occasional alignment requirements).

  14. Kangz commented on Dec 17, 2018

    @Kangz
    ContributorAuthor

    We just discovered that the binding model is compatible with argument buffers on Metal, where each WebGPUBindGroupLayout corresponds to two MTLArgumentEncoders and each WebGPUBindGroup is two MTLBuffers. Even better, argument buffers (not indirect argument buffers) are compatible with all Metal hardware, so there is no reason not to use them.

    Metal's argument buffer binding model is strictly more powerful than D3D12 so it makes sense that it would work. It should be possible to have each bindgroup be a single argument buffer, and have one extra argument buffer that contains data for each draw in the form of (bind group's argument buffers, dynamic offsets, push constants) (if we have push constants). An alternative would be to set all bind group argument buffers directly and have another argument buffer with per-draw data in (dynamic offsets, push constants).

    For the Direct3D backend, I'm not sure the line of code above is representable in HLSL without making every dynamic buffer a ByteAddressBuffer and reconstituting every item in the buffer from its constituent bytes. Maybe DXIL can represent it?

    The plan was indeed to use (RW)ByteAddressBuffer exclusively. That's also the way OpenGL ES compute shaders are being implemented in ANGLE's D3D11 backend (though the work is non-trivial because the code is not SSA form, but that's a different story).

    Why is there no mention of stride or bytestride in your vertex format spec?

    This is unrelated to this issue, please open another issue for this.

  15. devshgraphicsprogramming commented on Dec 17, 2018

    @devshgraphicsprogramming

    An alternative would be to set all bind group argument buffers directly and have another argument buffer with per-draw data in (dynamic offsets, push constants).

    That in my opinion is the best idea.

    seems like the best choice, but root table space is limited so we'd have to aggressively limit the number of dynamic buffers per pipeline layout.

    Vulkan limits those anyway, I think most commonly you get 24 non-dynamic UBO slots but only 4 or 8 dynamic.

    This is unrelated to this issue, please open another issue for this.

    I noticed that if https://github.com/gpuweb/gpuweb/blob/master/design/sketch.webidl#L395 's stride means a byte stride then all is good.

  16. litherum commented on Dec 17, 2018

    @litherum
    Contributor

    each bindgroup be a single argument buffer

    Nit: It has to be two argument buffers, because argument buffers in Metal are attached to the pipeline per-shader-stage. So one argument buffer is for the vertex stage and one is for the fragment stage. (But the difference between one/two buffers is not important for the general concept of the implementation.)

    The plan was indeed to use (RW)ByteAddressBuffer exclusively.

    I'm glad I don't have to implement that. Don't you have to worry about tearing across the multiple independent reads? Are there performance considerations for this approach? (But if Google, Mozilla, and Microsoft are willing to sign up for the task, then it's A-OK with me.)

    What's the downside of making offset mean “an integral number of items?” Seems like it would make everyone's life easier.

    Out of curiosity, what are the other reasons why Dawn opted to use ByteAddressBuffer for all resources? It's a curious conclusion.

  17. devshgraphicsprogramming commented on Dec 17, 2018

    @devshgraphicsprogramming

    What's the downside of making offset mean “an integral number of items?” Seems like it would make everyone's life easier.

    And the items are of what type?

  18. litherum commented on Dec 17, 2018

    @litherum
    Contributor

    The browser knows the type because it's in the pipeline state object. Creating the pipeline state object involves compiling the shader, so the browser knows the interface to the shader. The call to setBindGroup() tells you which item in the interface to the shader is relevant. So the browser knows the answer at the time setBindGroup() is called.

  19. devshgraphicsprogramming commented on Dec 17, 2018

    @devshgraphicsprogramming

    That would fail in the case I've outlined in today's call, where I pack all of my UBO data into one big buffer.

    NOTE: Lets for a moment forget the 256 byte alignment requirement on UBO offsets.

    Suppose I partition my UBO buffer into 3 sections for drawing torches, wheels and people.

    I use 3 different shaders, and they see the UBO as 3 different arrays of structs with different byte sizes for a single element (lets say 40 bytes, 16 bytes and 256 bytes).

    Suppose I have allocated a pool for 9 torches, 48 wheels and 4 people in the game level.

    That gives me 360 bytes of torch data, 48*16 bytes of wheel data and 1kB of people data.

    You can kind-of see where the problem would be in specifying my 360 byte offset as an integral number of 16 byte items, or a 1128 byte offset as an integral number of 1kB items.

    NOTE: Adding back the 256 byte alignment requirement, I could just as easily choose examples of larger item-sizes with padding that would satisfy 256 byte offset rule and still not divide evenly into items.

  20. kainino0x commented on Dec 17, 2018

    @kainino0x
    Contributor

    I think this is a really useful example. Thank you for sharing it on the call and detailing it here.

  21. litherum commented on Dec 21, 2018

    @litherum
    Contributor

    During the 2018-12-17 call:

    CW: looking at the high frequency operations in a frame, w/o push constants or dynamic buffers, have to bind things all the time and create a lot of them for every single region of uniforms you want to use. W/o either, this will be the single most perf critical thing - creating descriptors.

    I wanted to characterize the performance of creating descriptors. Here is my data: Bind Group Creation.zip and here is the benchmark: https://github.com/litherum/BindGroupBenchmark

    I measured the amount of time it takes to create a single bind group of varying sizes.

    Metal

    In Metal, I'm considering "making a bind group" as consisting of two things:

    1. Creating an argument buffer
    2. Populating the buffer via a MTLArgumentEncoder

    Here is the pseudocode for the benchmark:

    let argumentBuffer = device.makeBuffer(...)
    encoder.setArgumentBuffer(buffer, offset: 0)
    for j in 0 ..< i {
        encoder.setTexture(textures[j], index: j)
    }

    D3D12

    In D3D12, there isn't really a concept of a bind group. Instead, a bind group corresponds to a section of the descriptor heap. Unfortunately, there can only be one CBV_SRV_UAV descriptor heap active for a draw call, so you can't just assign each bind group its own heap. Therefore, the two stages of creating a bind group in D3D would be:

    1. Find an unused section of the descriptor heap
    2. Create a collection of descriptors in that section

    Performing stage 1 doesn't correspond to a particular API call. The browser would implement their own allocator to manage descriptors in the heap. Therefore, I didn't benchmark stage 1; I only benchmarked stage 2.

    Here's the pseudocode:

    for (int j = 0; j < i; ++j) {
        D3D12_SHADER_RESOURCE_VIEW_DESC desc;
        desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
        desc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D;
        ...
        d3dDevice->CreateShaderResourceView(textures[item].Get(), &desc, cbvCpuHandle);
    }

    (By the way, in D3D12, the descriptor heap only has a fixed size, so what would an implementation do when it runs out of space? Allocate a new heap and copy all the descriptors from the old heap to the new heap? Or maybe the implementation just makes a gigantic heap up front and if it runs out, kill the context or something?)

    Vulkan

    Each descriptor set can have its own pool, which is probably what WebGPU implementations would do because it provides the most flexibility. Therefore, there are 3 stages:

    1. Create a descriptor pool with the appropriate number of descriptors
    2. Create a descriptor set using all the descriptors from the pool
    3. Update the descriptor set with the resources

    Here's the pseudocode:

    vk::DescriptorPoolSize const poolSize = vk::DescriptorPoolSize().setType(vk::DescriptorType::eSampledImage).setDescriptorCount(i);
    auto const descriptorPoolInfo = vk::DescriptorPoolCreateInfo().setMaxSets(1).setPoolSizeCount(1).setPPoolSizes(&poolSize);
    vk::DescriptorPool descriptorPool;
    device.createDescriptorPool(&descriptorPoolInfo, nullptr, &descriptorPool);
    
    auto const alloc_info = vk::DescriptorSetAllocateInfo().setDescriptorPool(descriptorPool).setDescriptorSetCount(1).setPSetLayouts(&descriptorSetLayout);
    vk::DescriptorSet descriptorSet;
    device.allocateDescriptorSets(&alloc_info, &descriptorSet);
    
    std::vector<vk::DescriptorImageInfo> textureDescriptors(i);
    for (uint32_t j = 0; j < i; j++) {
        textureDescriptors[j].setImageView(imageViews[j]);
        ...
    }
    vk::WriteDescriptorSet write;
    write.setDstBinding(0);
    write.setDescriptorCount(i);
    ...
    write.setPImageInfo(textureDescriptors.data());
    write.setDstSet(descriptorSet);
    device.updateDescriptorSets(1, &write, 0, nullptr);

    Results

    The Y axis is the time it takes to create a bind group of N items, where N is the X axis. The units are milliseconds. Lower is better.

    screen shot 2018-12-20 at 7 50 50 pm

    Here is a chart of just the leftmost data points, showing how long it takes to create a bind group with a single element:
    screen shot 2018-12-20 at 8 13 04 pm

    In the above bar graph, the average time for Metal devices is 58.4 microseconds ( = 0.35% of a frame), the average time for D3D12 is 2.292 microseconds ( = 0.014% of a frame), and the average time for Vulkan is 897.9 nanoseconds ( = 0.0054% of a frame). This means, in a single frame, the Metal devices can create 285 bind groups, the D3D12 devices can create 7270 bind groups, and the Vulkan devices can create 18561 bind groups.

    It strikes me that we probably want to support more than 18561 draw calls in a single frame, and I would imagine most draw calls probably would want at least some updated data each frame, and we also don't want to spend our entire frame budget creating descriptors, so I think the data supports Corentin's thesis.

    Aside: Given the above performance numbers, we probably shouldn't use bind groups unconditionally in Metal. We probably should use MTLRenderCommandEncoder.setVertex/FragmentTextures() until we believe that the resource will be used often, and only then promote it to a bind group.

  22. Kangz commented on Sep 2, 2021

    @Kangz
    ContributorAuthor

    Closing. The spec has dynamic uniform and storage buffers in and they've been useful to early adopters.

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