Skip to content

Support inlining small constants into dispatch regions #4897

Closed

Description

@benvanik

Today we only inline splat constants (constant dense<5> : tensor<4xi32>), via the logic here:
https://github.com/google/iree/blob/main/iree/compiler/Dialect/Flow/Transforms/RematerializeDispatchConstants.cpp#L41-L57

This excludes things like like constant dense<[0,1,2,3]> : tensor<4xi32> or constant dense<[1.0, 2.0]> : tensor<2xf32>. As part of buffer allocation I'm noticing a large number of small constants that then aren't getting inlined and thus need to be planned for externally and passed in. We're talking specifically about reasonable constants to inline, not MB-sized things. Think more like 16-element lookup tables, initialization vectors, channel masks, etc.

Since SPIR-V and LLVM both support constants this may just be a missing conversion or two between what we are taking in (mhlo on the old path, linalg on the new path) and those targets.

Mahesh says:
We should be able to use tensor_to_memref here to wire things together and finally SPIRV and LLVM should handle the constant

This can be tested by changing the isSplatConstant to return true if the DenseElementsAttr logic is changed to:

  } else if (auto value = constantOp.getValue().dyn_cast<DenseElementsAttr>()) {
    auto shapedType = constantOp.getType().cast<ShapedType>();
    uint64_t estimatedByteLength =
        (shapedType.getNumElements() * shapedType.getElementTypeBitWidth()) / 8;
    return denseAttr.isSplat() ||
           estimatedByteLength <= 256;  // or whatever
  } else {

That should cause the constants to end up in the dispatch regions. Here's an example dispatch region that fails today (masking from a clamp or something) with the above change:

func @test() -> tensor<5xi32> {
  %c5 = constant 5 : index
  %3 = iree.unfoldable_constant dense<4.0> : tensor<f32>
  %4 = flow.dispatch.region[%c5 : index](%arg2 = %3 : tensor<5xf32>) -> (tensor<5xi32>) {
    %cst_4 = constant dense<0.000000e+00> : tensor<5xf32>
    %49 = "mhlo.compare"(%arg2, %cst_4) {comparison_direction = "EQ"} : (tensor<5xf32>, tensor<5xf32>) -> tensor<5xi1>
    %50 = "mhlo.convert"(%49) : (tensor<5xi1>) -> tensor<5xi32>
    %cst_5 = constant dense<[1, 2, 3, 4, 5]> : tensor<5xi32>
    %51 = mhlo.multiply %50, %cst_5 : tensor<5xi32>
    flow.return %51 : tensor<5xi32>
  }
  return %4 : tensor<5xi32>
}

Activity

  1. added
    codegen
    performance ⚡
    on Feb 20, 2021
  2. MaheshRavishankar commented on Feb 20, 2021

    @MaheshRavishankar
    Collaborator

    @hanhanW temporarily passing this to you (ill pick it up later in the week if you dont get to it by then). Adding support on the existing codegen path (i.e. not linalg on tensors) would require two steps

    1. Adding a patter to convert std.constant to std.constant -> tensor_to_memref in HLOToLinalgOnBuffers
    2. Handling tensor_to_memref in SPIR-V lowering (basicall iy is a no-op but needs to have the pattern for it.

    Ill add the support on the linalg on tensors path

  3. hanhanW commented on Feb 21, 2021

    @hanhanW
    Contributor

    Is the idea to convert below snippet

    module {
      func @small_cst() {
        %c0 = constant 0 : index
        %0 = hal.interface.load.tensor @legacy_io::@arg0, offset = %c0 : tensor<5xi32>
        %1 = constant dense<[1, 2, 3, 4, 5]> : tensor<5xi32>
        %2 = mhlo.add%0, %1 : tensor<5xi32>
        hal.interface.store.tensor %2, @legacy_io::@ret0, offset = %c0 : tensor<5xi32>
        return
      }
      hal.interface @legacy_io attributes {sym_visibility = "private"} {
        hal.interface.binding @arg0, set=0, binding=0, type="StorageBuffer", access="Read"
        hal.interface.binding @ret0, set=0, binding=1, type="StorageBuffer", access="Write"
      }
    }

    to

    #map = affine_map<(d0) -> (d0)>
    module  {
      func @small_cst() {
        %0 = iree.placeholder for "interface buffer" {binding = @legacy_io::@ret0} : memref<5xi32>
        %c0 = constant 0 : index
        %1 = iree.placeholder for "interface buffer" {binding = @legacy_io::@arg0} : memref<5xi32>
        %2 = constant dense<[1, 2, 3, 4, 5]> : tensor<5xi32>
        %3 = tensor_to_memref %2 : memref<5xi32>
        linalg.generic {indexing_maps = [#map, #map, #map], iterator_types = ["parallel"]} ins(%1, %3 : memref<5xi32>, memref<5xi32>) outs(%0 : memref<5xi32>) {
        ^bb0(%arg0: i32, %arg1: i32, %arg2: i32):  // no predecessors
          %4 = addi %arg0, %arg1 : i32
          linalg.yield %4 : i32
        }
        return
      }
      hal.interface @legacy_io attributes {sym_visibility = "private"} {
        hal.interface.binding @arg0, set=0, binding=0, type="StorageBuffer", access="Read"
        hal.interface.binding @ret0, set=0, binding=1, type="StorageBuffer", access="Write"
      }
    }

    And drop TensorToMerefOp in ConvertToSPIRVPass (like linalg::TensorReshapeOp)?

  4. MaheshRavishankar commented on Feb 21, 2021

    @MaheshRavishankar
    Collaborator

    I guess by drop it you mean just forward the !spv.array. Yes, thats what I mean. We can just add this pattern to core..

  5. MaheshRavishankar commented on Feb 22, 2021

    @MaheshRavishankar
    Collaborator

    Right!

  6. MaheshRavishankar commented on Feb 23, 2021

    @MaheshRavishankar
    Collaborator

    @hanhanW did you already get to this. I am hitting this on some unrelated change but might as well fix it. Just looking to fix it on the linalg on tensors path though for now. Let me know.

  7. hanhanW commented on Feb 23, 2021

    @hanhanW
    Contributor

    No, I haven't started the work yet.

  8. MaheshRavishankar commented on Feb 23, 2021

    @MaheshRavishankar
    Collaborator

    Ok, ill update here if I get this working on the linalg on tensors path.

  9. MaheshRavishankar commented on Mar 5, 2021

    @MaheshRavishankar
    Collaborator

    Started looking into this on the linalg on tensors path briefly (WIP commit here MaheshRavishankar@489d97c).

    It stumped right now cause a canonicalizer in core takes a constant -> tensor_to_memref -> load and converts it into constant -> tensor.extract. Which might be OK. It means tensor.extract needs to be supported now in Standard/Tensor SPIR-V now. See dump IR after all here

    On the LLVM side it looks there is a tensor-constant-bufferize pass (here) that we might need to use, but that might work out of the box.

    Leaving notes here if someone else has time to pick this up and finish. I am going to be switching to some higher priority tasks for a bit.

  10. antiagainst commented on Mar 5, 2021

    @antiagainst
    Member

    I see we are extracting from constant using dynamic indices. Then for SPIR-V we need to create local variables to hold the constant and then use access chain, which supports dynamic indices. I can throw in a pattern for it.

  11. 25 remaining items

  12. ScottTodd commented on Mar 17, 2021

    @ScottTodd
    Member

    Ah... yeah. We could check for equality with these functions: https://github.com/google/iree/blob/a6a827784b0726c5a9e702d1af1a51379cd8f975/iree/compiler/Dialect/Flow/Transforms/DeduplicateExecutables.cpp#L47-L50
    (which could be upstreamed, see #3996)

    That gist has multiple constants named __constant_2x2xf32 with different values:

            llvm.mlir.global private constant @__constant_2x2xf32(dense<[[1.000000e+00, 2.000000e+00], [3.000000e+00, 4.000000e+00]]> : tensor<2x2xf32>) : !llvm.array<2 x array<2 x f32>>
    
            llvm.mlir.global private constant @__constant_2x2xf32(dense<[[4.000000e+00, 5.000000e+00], [6.000000e+00, 7.000000e+00]]> : tensor<2x2xf32>) : !llvm.array<2 x array<2 x f32>>
    
  13. asaadaldien commented on Mar 17, 2021

    @asaadaldien
    Contributor

    We can also use the renaming utils as Ben mentioned and CSE after the linking which will remove globas with the same values.

  14. MaheshRavishankar commented on Mar 17, 2021

    @MaheshRavishankar
    Collaborator

    Awesome! Seems like we have options. Lets chat in a more group setting to come to a consensus on way forward.

  15. benvanik commented on Mar 17, 2021

    @benvanik
    CollaboratorAuthor

    We can also use the renaming utils as Ben mentioned and CSE after the linking which will remove globas with the same values.

    does CSE handle LLVM globals? I think it needs a dedicated pass that doesn't exist - that's one of the reasons we have DeduplicateExecutables. If we can prevent the duplicates from being inserted in the first place that'd be best.

  16. MaheshRavishankar commented on Mar 19, 2021

    @MaheshRavishankar
    Collaborator

    Tried this out here. Unfortunately it turns out this is a bit more complex than I thought it was. The "private" you see on the symbols before LinkExecutablesPass in the gist posted above is actually the symbol in LLVM dialect and not the MLIR symbol visibility. So that makes things more involved cause it seems like those are actually not marked as "Private" symbols in MLIR. There needs to be some way of mapping the LLVM symbol visibility to MLIR symbol visibility, which probably requires some discussion and cant be done as a quick fix.

    So wondering if we should disable this linking of executables (like it is done on the SPIR-V side) till this can be resolved. Note that this is the issue possibly happening in #5152.

  17. removed their assignment
    on Mar 19, 2021
  18. asaadaldien commented on Mar 19, 2021

    @asaadaldien
    Contributor

    Thanks @MaheshRavishankar for giving this a shot, linking executables is very important for perf and its analysis and we would like to keep it enabled for LLVM. Another short term fix is to add pass after TensorConstantBufferize to alter global_memref sym_name and append func names so we will have __constant_2x2xf32_foo_dispatch_1, __constant_2x2xf32_foo_dispatch_2.

  19. MaheshRavishankar commented on Mar 19, 2021

    @MaheshRavishankar
    Collaborator

    Ok, I'll see if I can add this to the upstream pass, though there might be push back against it (Which would be valid, but it is a small change). I'll take a stab at it.

  20. asaadaldien commented on Mar 19, 2021

    @asaadaldien
    Contributor

    Thanks @MaheshRavishankar , If there is a push back for sym_names in upstream we can add another Module pass here that does rename memref_global symbol names.
    IMO the real long term fix is to get the symbol_table rename you [linked]((MaheshRavishankar@7d3baeb) working.

  21. benvanik commented on Mar 19, 2021

    @benvanik
    CollaboratorAuthor

    It'd be nice if private LLVM-dialect symbols responded to the same symbol trait queries as any other dialect - may call for an interface (if one doesn't exist already) so that dialects can map things. That said, the linking phase is HAL target-specific and we could perform whatever logic we wanted as part of that - such as a cleanup of duplicated global_memref symbols post-linking (as we could run prior to verification and handle the name conflicts ourselves).

  22. MaheshRavishankar commented on Mar 19, 2021

    @MaheshRavishankar
    Collaborator

    Thanks for the pointer. I am just going to try to do that there now, cause that is the cleanest solution I can see.

  23. added a commit that references this issue on Mar 19, 2021
    52f02af
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

codegenperformance ⚡

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions