|
| 1 | +# Copyright (c) Meta Platforms, Inc. and affiliates. |
| 2 | +# All rights reserved. |
| 3 | +# |
| 4 | +# This source code is licensed under the BSD-style license found in the |
| 5 | +# LICENSE file in the root directory of this source tree. |
| 6 | + |
| 7 | +import unittest |
| 8 | + |
| 9 | +import torch |
| 10 | +from executorch.backends.aoti.passes.replace_view_copy_with_view import ( |
| 11 | + ReplaceViewCopyWithViewPass, |
| 12 | +) |
| 13 | +from executorch.backends.cuda.cuda_backend import CudaBackend |
| 14 | +from executorch.backends.cuda.cuda_partitioner import CudaPartitioner |
| 15 | +from executorch.backends.cuda.passes.replace_fused_sdpa import ( |
| 16 | + ReplaceFusedSdpaWithSdpaPass, |
| 17 | +) |
| 18 | +from executorch.exir import EdgeCompileConfig, to_edge |
| 19 | +from executorch.exir.dialects._ops import ops as exir_ops |
| 20 | +from torch.export import export |
| 21 | + |
| 22 | + |
| 23 | +def _program_for_cuda_passes(model, inputs, dynamic_shapes=None): |
| 24 | + """The Edge program of ``model`` as the CUDA backend's passes get it: no |
| 25 | + op decomposed, as the CUDA partitioner asks, and views for copies.""" |
| 26 | + program = export(model, inputs, dynamic_shapes=dynamic_shapes, strict=True) |
| 27 | + # to_edge_transform_and_lower functionalizes the program before it asks |
| 28 | + # the partitioner which ops to keep. |
| 29 | + program = program.run_decompositions({}) |
| 30 | + ops, _ = CudaPartitioner([]).ops_to_not_decompose(program) |
| 31 | + program = to_edge( |
| 32 | + program, |
| 33 | + compile_config=EdgeCompileConfig(_check_ir_validity=False, preserve_ops=ops), |
| 34 | + ).exported_program() |
| 35 | + ReplaceViewCopyWithViewPass()(program.graph_module) |
| 36 | + return program |
| 37 | + |
| 38 | + |
| 39 | +class _Fn(torch.nn.Module): |
| 40 | + def __init__(self, fn): |
| 41 | + super().__init__() |
| 42 | + self.fn = fn |
| 43 | + |
| 44 | + def forward(self, *args): |
| 45 | + return self.fn(*args) |
| 46 | + |
| 47 | + |
| 48 | +class TestReplaceFusedSdpaWithSdpaPass(unittest.TestCase): |
| 49 | + def test_runs_before_triton_replacement(self): |
| 50 | + """The calls it rewrites must still reach the Triton SDPA kernels.""" |
| 51 | + names = [type(p).__name__ for p in CudaBackend.get_custom_passes([])] |
| 52 | + self.assertLess( |
| 53 | + names.index("ReplaceFusedSdpaWithSdpaPass"), |
| 54 | + names.index("ReplaceEdgeOpWithTritonOpPass"), |
| 55 | + ) |
| 56 | + |
| 57 | + def test_rewrite(self): |
| 58 | + """Fused attention becomes scaled_dot_product_attention only when that |
| 59 | + computes the same result.""" |
| 60 | + aten = torch.ops.aten |
| 61 | + |
| 62 | + def cudnn(q, k): |
| 63 | + return aten._scaled_dot_product_cudnn_attention(q, k, k, None, False)[0] |
| 64 | + |
| 65 | + def causal(q, k, bias=None): |
| 66 | + return aten._scaled_dot_product_efficient_attention( |
| 67 | + q, k, k, bias, False, is_causal=True |
| 68 | + )[0] |
| 69 | + |
| 70 | + def grouped(q, k): |
| 71 | + return aten._scaled_dot_product_flash_attention(q, k, k, scale=0.2)[0] |
| 72 | + |
| 73 | + def with_log_sum_exp(q, k): |
| 74 | + return aten._scaled_dot_product_efficient_attention(q, k, k, None, True)[:2] |
| 75 | + |
| 76 | + def flash(q, k): |
| 77 | + return aten._scaled_dot_product_flash_attention(q, k, k)[0] |
| 78 | + |
| 79 | + def in_branch(q, k): |
| 80 | + return torch.cond(q.sum() > 0, flash, lambda q, k: q * 2, (q, k)) |
| 81 | + |
| 82 | + q = torch.randn(1, 2, 16, 64) |
| 83 | + one_head = torch.randn(1, 1, 16, 64) |
| 84 | + decode = q[:, :, :1].clone() |
| 85 | + length = torch.export.Dim("length", min=2, max=64) |
| 86 | + keys = torch.export.Dim("keys", min=2, max=64) |
| 87 | + # The last item is the keyword arguments of the new call, or None when |
| 88 | + # the fused call has to stay. |
| 89 | + for fn, inputs, lengths, kwargs in ( |
| 90 | + (cudnn, (q, q), None, {}), |
| 91 | + (causal, (q, q), None, {}), |
| 92 | + (causal, (q, q.clone()), (length, length), {}), |
| 93 | + (grouped, (q, one_head), None, {"scale": 0.2, "enable_gqa": True}), |
| 94 | + (in_branch, (q, q), None, {}), |
| 95 | + # With different query and key lengths, the variants and the Triton |
| 96 | + # decode kernel place the causal mask differently. |
| 97 | + (causal, (decode, q), None, None), |
| 98 | + (causal, (q, q.clone()), (length, keys), None), |
| 99 | + (causal, (q, q, torch.randn(1, 2, 16, 16)), None, None), |
| 100 | + (with_log_sum_exp, (q, q), None, None), |
| 101 | + ): |
| 102 | + shapes = [t.shape for t in inputs] |
| 103 | + with self.subTest(fn=fn.__name__, shapes=shapes, lengths=lengths): |
| 104 | + dynamic_shapes = None |
| 105 | + if lengths: |
| 106 | + dynamic_shapes = {"args": tuple({2: n} for n in lengths)} |
| 107 | + program = _program_for_cuda_passes(_Fn(fn), inputs, dynamic_shapes) |
| 108 | + ReplaceFusedSdpaWithSdpaPass()(program) |
| 109 | + program.validate() |
| 110 | + nodes = [ |
| 111 | + node |
| 112 | + for module in program.graph_module.modules() |
| 113 | + if isinstance(module, torch.fx.GraphModule) |
| 114 | + for node in module.graph.nodes |
| 115 | + ] |
| 116 | + sdpa = exir_ops.edge.aten.scaled_dot_product_attention.default |
| 117 | + calls = [node.kwargs for node in nodes if node.target == sdpa] |
| 118 | + self.assertEqual(calls, [] if kwargs is None else [kwargs]) |
| 119 | + fused = [ |
| 120 | + node |
| 121 | + for node in nodes |
| 122 | + if "aten._scaled_dot_product_" in str(node.target) |
| 123 | + ] |
| 124 | + self.assertEqual(not fused, kwargs is not None) |
0 commit comments