Skip to content

Add attention op to linalg_ext - #11928

Merged
MaheshRavishankar merged 5 commits into
iree-org:mainfrom
harsh-nod:attention
Jan 27, 2023
Merged

MaheshRavishankar merged 5 commits into
iree-org:mainfrom
harsh-nod:attention

Conversation

@harsh-nod

Copy link
Copy Markdown
Contributor

This patch adds the attention op to the linalg ext dialect. It also adds a lowering that decomposes the attention into a sequence of linalg generic ops (batch matmul + softmax + batch matmul). Finally, we add the pass into the CPU and CUDA pipeline along with an e2e test to validate functional accuracy.

@harsh-nod

Copy link
Copy Markdown
Contributor Author

Here is what the IR looks like when lowering this op

module {
  func.func @_attention_dispatch_0() {
    %cst = arith.constant -1.000000e+30 : f32
    %cst_0 = arith.constant 0.000000e+00 : f32
    %c2 = arith.constant 2 : index
    %c1024 = arith.constant 1024 : index
    %c0 = arith.constant 0 : index
    %0 = hal.interface.binding.subspan set(0) binding(0) type(storage_buffer) offset(%c0) alignment(64) flags(ReadOnly) : !flow.dispatch.tensor<readonly:tensor<2x1024x64xf32>>
    %1 = hal.interface.binding.subspan set(0) binding(1) type(storage_buffer) offset(%c0) alignment(64) flags(ReadOnly) : !flow.dispatch.tensor<readonly:tensor<2x1024x64xf32>>
    %2 = hal.interface.binding.subspan set(0) binding(2) type(storage_buffer) offset(%c0) alignment(64) flags(ReadOnly) : !flow.dispatch.tensor<readonly:tensor<2x1024x64xf32>>
    %3 = hal.interface.binding.subspan set(0) binding(3) type(storage_buffer) offset(%c0) alignment(64) : !flow.dispatch.tensor<writeonly:tensor<2x1024x64xf32>>
    %workgroup_id_x = hal.interface.workgroup.id[0] : index
    %workgroup_count_x = hal.interface.workgroup.count[0] : index
    %workgroup_id_y = hal.interface.workgroup.id[1] : index
    %workgroup_count_y = hal.interface.workgroup.count[1] : index
    %4 = affine.apply affine_map<()[s0] -> (s0 * 2)>()[%workgroup_id_y]
    %5 = affine.apply affine_map<()[s0] -> (s0 * 2)>()[%workgroup_count_y]
    scf.for %arg0 = %4 to %c2 step %5 {
      %6 = affine.apply affine_map<()[s0] -> (s0 * 64)>()[%workgroup_id_x]
      %7 = affine.apply affine_map<()[s0] -> (s0 * 64)>()[%workgroup_count_x]
      scf.for %arg1 = %6 to %c1024 step %7 {
        %8 = flow.dispatch.tensor.load %3, offsets = [%arg0, %arg1, 0], sizes = [2, 64, 64], strides = [1, 1, 1] : !flow.dispatch.tensor<writeonly:tensor<2x1024x64xf32>> -> tensor<2x64x64xf32>
        %9 = flow.dispatch.tensor.load %0, offsets = [%arg0, %arg1, 0], sizes = [2, 64, 64], strides = [1, 1, 1] : !flow.dispatch.tensor<readonly:tensor<2x1024x64xf32>> -> tensor<2x64x64xf32>
        %10 = flow.dispatch.tensor.load %1, offsets = [%arg0, 0, 0], sizes = [2, 1024, 64], strides = [1, 1, 1] : !flow.dispatch.tensor<readonly:tensor<2x1024x64xf32>> -> tensor<2x1024x64xf32>
        %11 = flow.dispatch.tensor.load %2, offsets = [%arg0, 0, 0], sizes = [2, 1024, 64], strides = [1, 1, 1] : !flow.dispatch.tensor<readonly:tensor<2x1024x64xf32>> -> tensor<2x1024x64xf32>
        %12 = tensor.empty() : tensor<2x64x1024xf32>
        %transposed = linalg.transpose ins(%10 : tensor<2x1024x64xf32>) outs(%12 : tensor<2x64x1024xf32>) permutation = [0, 2, 1]
        %13 = linalg.fill ins(%cst_0 : f32) outs(%12 : tensor<2x64x1024xf32>) -> tensor<2x64x1024xf32>
        %14 = linalg.batch_matmul ins(%9, %transposed : tensor<2x64x64xf32>, tensor<2x64x1024xf32>) outs(%13 : tensor<2x64x1024xf32>) -> tensor<2x64x1024xf32>
        %15 = tensor.empty() : tensor<2x64xf32>
        %16 = linalg.fill ins(%cst : f32) outs(%15 : tensor<2x64xf32>) -> tensor<2x64xf32>
        %17 = linalg.generic {indexing_maps = [affine_map<(d0, d1, d2) -> (d0, d1, d2)>, affine_map<(d0, d1, d2) -> (d0, d1)>], iterator_types = ["parallel", "parallel", "reduction"]} ins(%14 : tensor<2x64x1024xf32>) outs(%16 : tensor<2x64xf32>) {
        ^bb0(%in: f32, %out: f32):
          %24 = arith.maxf %in, %out : f32
          linalg.yield %24 : f32
        } -> tensor<2x64xf32>
        %18 = linalg.generic {indexing_maps = [affine_map<(d0, d1, d2) -> (d0, d1)>, affine_map<(d0, d1, d2) -> (d0, d1, d2)>], iterator_types = ["parallel", "parallel", "parallel"]} ins(%17 : tensor<2x64xf32>) outs(%14 : tensor<2x64x1024xf32>) {
        ^bb0(%in: f32, %out: f32):
          %24 = arith.subf %out, %in : f32
          %25 = math.exp %24 : f32
          linalg.yield %25 : f32
        } -> tensor<2x64x1024xf32>
        %19 = linalg.fill ins(%cst_0 : f32) outs(%15 : tensor<2x64xf32>) -> tensor<2x64xf32>
        %20 = linalg.generic {indexing_maps = [affine_map<(d0, d1, d2) -> (d0, d1, d2)>, affine_map<(d0, d1, d2) -> (d0, d1)>], iterator_types = ["parallel", "parallel", "reduction"]} ins(%18 : tensor<2x64x1024xf32>) outs(%19 : tensor<2x64xf32>) {
        ^bb0(%in: f32, %out: f32):
          %24 = arith.addf %in, %out : f32
          linalg.yield %24 : f32
        } -> tensor<2x64xf32>
        %21 = linalg.generic {indexing_maps = [affine_map<(d0, d1, d2) -> (d0, d1, d2)>, affine_map<(d0, d1, d2) -> (d0, d1)>, affine_map<(d0, d1, d2) -> (d0, d1, d2)>], iterator_types = ["parallel", "parallel", "parallel"]} ins(%18, %20 : tensor<2x64x1024xf32>, tensor<2x64xf32>) outs(%12 : tensor<2x64x1024xf32>) {
        ^bb0(%in: f32, %in_1: f32, %out: f32):
          %24 = arith.divf %in, %in_1 : f32
          linalg.yield %24 : f32
        } -> tensor<2x64x1024xf32>
        %22 = linalg.fill ins(%cst_0 : f32) outs(%8 : tensor<2x64x64xf32>) -> tensor<2x64x64xf32>
        %23 = linalg.batch_matmul ins(%21, %11 : tensor<2x64x1024xf32>, tensor<2x1024x64xf32>) outs(%22 : tensor<2x64x64xf32>) -> tensor<2x64x64xf32>
        flow.dispatch.tensor.store %23, %3, offsets = [%arg0, %arg1, 0], sizes = [2, 64, 64], strides = [1, 1, 1] : tensor<2x64x64xf32> -> !flow.dispatch.tensor<writeonly:tensor<2x1024x64xf32>>
      }
    }
    return
  }
}

OpPassManager &pm, bool useFuseTensorPadWithConsumerPass = true) {
pm.addPass(createTileAndDistributeToWorkgroupsPass());
auto &nestedModulePM = pm.nest<ModuleOp>();
nestedModulePM.addNestedPass<func::FuncOp>(

@MaheshRavishankar MaheshRavishankar Jan 23, 2023 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice! I have a suggestion here that is not necessary for this PR.

It seems like we can combine the "DecomposeAttentionPass" and "DecomposeSoftmaxPass" into a single pass with a new interface. A simple interface that just adds a single method, i.e. "decomposeOperation" that decomposes the operation into the required sequence. Then the pass is just walking over the IR and decomposing the ops as needed?

WDYT?

Also FYI @ftynse (since Alex seems to be interested)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sounds great! Where would I add such an interface?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

+1 for the interface. IMO, it can go to LinalgExtInterfaces.h/cpp. This sounds specific to Linalg at this point, at the ops it applies to are in LianlgExt.

@harsh-nod
harsh-nod force-pushed the attention branch 3 times, most recently from 07c3c22 to 9d49540 Compare January 24, 2023 18:45
OpPassManager &pm, bool useFuseTensorPadWithConsumerPass = true) {
pm.addPass(createTileAndDistributeToWorkgroupsPass());
auto &nestedModulePM = pm.nest<ModuleOp>();
nestedModulePM.addNestedPass<func::FuncOp>(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

+1 for the interface. IMO, it can go to LinalgExtInterfaces.h/cpp. This sounds specific to Linalg at this point, at the ops it applies to are in LianlgExt.

// Attention
//===----------------------------------------------------------------------===//

class CheckShapedOperandOfRank3<int i> : And<[

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Document this in English please :)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sure will add a line of documentation.

Comment on lines +1235 to +1247
Value query() {
return getInputOperand(0)->get();
}
Value key() {
return getInputOperand(1)->get();
}
Value value() {
return getInputOperand(2)->get();
}
Value output() {
return getOutputOperand(0)->get();
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Naming nit: these should be using the prefixed form, i.e. getQuery, getKey, etc.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sounds good, will change.

ArrayRef<int64_t> keyShape = keyType.getShape();
ArrayRef<int64_t> valueShape = valueType.getShape();
ArrayRef<int64_t> outputShape = outputType.getShape();
if (!areShapesCompatible(queryShape, keyShape)) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Annoying nit: MLIR (and thus external-projects/iree-dialects) elides braces around single-line bodies.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Will remove.

queryOutputOffsets, queryOutputSizes,
queryOutputStrides));

SmallVector<Type, 4> resultTypes;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: drop the explicit number of stack elements.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sure will remove.

@harsh-nod
harsh-nod force-pushed the attention branch 2 times, most recently from 4a99397 to 997a75c Compare January 26, 2023 03:40

@MaheshRavishankar MaheshRavishankar left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok, this looks fine to me. I think its fine to do the tiling and decomposition in a combined way for now. We probably need to refactor this into a generate reduction tiling algorithm, but that should just be a refactoring....


static Value computeSoftmax(Value qkTranspose, Value currentMax, Value output,
Location loc, OpBuilder &builder) {
AffineMap identityMap =

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cant we use the iree_linalg_ext.softmax here?

@harsh-nod harsh-nod Jan 26, 2023 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This computes a partial softmax, so just exp(x - max(x)), so that's why we cant use the iree_linalg_ext.softmax op. If you would like, I can rename this function?

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yeah renaming would be good.... Thats a bummer, you had to do all the work for adding softmax op, but wasnt really able to use it here.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I know but maybe in the future we can figure out how to leverage that here.

This patch adds the attention op to the linalg ext dialect. It also adds a
lowering that decomposes the attention into a sequence of linalg generic
ops (batch matmul + softmax + batch matmul). Finally, we add the pass into
the CPU and CUDA pipeline along with an e2e test to validate functional accuracy.
Rather than try to fit this into the PartialTileReductionInterface,
we do a special lowering of the attention op that tiles and
decomposes it to a sequence of linalg ops.
Also add further simplifications and bug fixes.
This patch fuses the last two generics into one, so now
we generate a total of 5 generics. Also adds additional
output to linalg generic for proper compute.
Also keep last two generics separate as their dimensions
may not always be the same.
@harsh-nod

Copy link
Copy Markdown
Contributor Author

I have made the changes. Please merge when you get a chance. Thanks!

@MaheshRavishankar
MaheshRavishankar merged commit 8773676 into iree-org:main Jan 27, 2023
NAME
check_llvm-cpu_local-task
SRCS
"attention.mlir"

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This test is failing on emscripten with --iree-llvm-target-triple=wasm32-unknown-emscripten (tested on post-submit only, best-effort to maintain): https://github.com/iree-org/iree/actions/runs/4026898563/jobs/6922078074

FAILED: tests/e2e/linalg_ext_ops/check_llvm-cpu_local-task_attention.mlir_module.vmfb /work/build-emscripten/tests/e2e/linalg_ext_ops/check_llvm-cpu_local-task_attention.mlir_module.vmfb 
cd /work/build-emscripten/tests/e2e/linalg_ext_ops && /work/full-build-dir/install/bin/iree-compile --output-format=vm-bytecode --mlir-print-op-on-diagnostic=false --iree-hal-target-backends=llvm-cpu /work/tests/e2e/linalg_ext_ops/attention.mlir -o check_llvm-cpu_local-task_attention.mlir_module.vmfb --iree-hal-executable-object-search-path=\"/work/build-emscripten\" --iree-llvm-target-triple=wasm32-unknown-emscripten
/work/tests/e2e/linalg_ext_ops/attention.mlir:6:8: error: 'memref.alloca' op all stack allocations need to be hoisted to the entry block of the function
  %1 = iree_linalg_ext.attention ins(%query, %key, %value : tensor<1x4x4xf32>,
       ^

Does that error make sense to you?

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this happening only in the wasm backend... or is it on all backends?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just the wasm compilation (which is just the CPU path but using --iree-llvm-target-triple=wasm32-unknown-emscripten). We might see similar errors with other target triples or LLVM/codegen options, but all of our other CI builds and tests are passing.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Surprising that this is happening on wasm, and not outside of it... This should be using the CPU compilation pipeline directly right? If so, then I can look into it.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

#11992 fixes this.

qedawkins pushed a commit to qedawkins/iree that referenced this pull request Apr 2, 2023
This patch adds the attention op to the linalg ext dialect. It also adds a lowering that decomposes the attention into a sequence of linalg generic ops (batch matmul + softmax + batch matmul). Finally, we add the pass into the CPU and CUDA pipeline along with an e2e test to validate functional accuracy.
jpienaar pushed a commit that referenced this pull request May 1, 2023
This patch adds the attention op to the linalg ext dialect. It also adds a lowering that decomposes the attention into a sequence of linalg generic ops (batch matmul + softmax + batch matmul). Finally, we add the pass into the CPU and CUDA pipeline along with an e2e test to validate functional accuracy.
rengolin pushed a commit to plaidml/iree that referenced this pull request May 2, 2023
This patch adds the attention op to the linalg ext dialect. It also adds a lowering that decomposes the attention into a sequence of linalg generic ops (batch matmul + softmax + batch matmul). Finally, we add the pass into the CPU and CUDA pipeline along with an e2e test to validate functional accuracy.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants