|
| 1 | +# Copyright 2026 Arm Limited and/or its affiliates. |
| 2 | +# |
| 3 | +# This source code is licensed under the BSD-style license found in the |
| 4 | +# LICENSE file in the root directory of this source tree. |
| 5 | + |
| 6 | +import torch |
| 7 | +from executorch.backends.arm.test.common import parametrize |
| 8 | +from executorch.backends.cortex_m.test.tester import CortexMTester, McuTestCase |
| 9 | + |
| 10 | + |
| 11 | +class CortexMAttention(torch.nn.Module): |
| 12 | + ops_before_transforms = { |
| 13 | + "executorch_exir_dialects_edge__ops_aten_linear_default": 1, |
| 14 | + "executorch_exir_dialects_edge__ops_aten_bmm_default": 2, |
| 15 | + "executorch_exir_dialects_edge__ops_aten_mul_Tensor": 1, |
| 16 | + "executorch_exir_dialects_edge__ops_aten__softmax_default": 1, |
| 17 | + } |
| 18 | + |
| 19 | + ops_after_transforms = { |
| 20 | + "executorch_exir_dialects_edge__ops_cortex_m_quantized_linear_default": 1, |
| 21 | + "executorch_exir_dialects_edge__ops_cortex_m_quantized_batch_matmul_default": 2, |
| 22 | + "executorch_exir_dialects_edge__ops_cortex_m_softmax_default": 1, |
| 23 | + } |
| 24 | + |
| 25 | + def __init__(self): |
| 26 | + super().__init__() |
| 27 | + self.qkv = torch.nn.Linear(12, 36) |
| 28 | + |
| 29 | + def forward(self, x): |
| 30 | + qkv = self.qkv(x).reshape(1, 5, 3, 3, 4).permute(2, 0, 3, 1, 4) |
| 31 | + q, k, v = qkv.unbind(0) |
| 32 | + scores = (q * 0.5) @ k.transpose(-2, -1) |
| 33 | + return (scores.softmax(dim=-1) @ v).transpose(1, 2).reshape(1, 5, 12) |
| 34 | + |
| 35 | + |
| 36 | +test_cases = { |
| 37 | + "qkv_attention": McuTestCase(CortexMAttention(), (torch.randn(1, 5, 12),)), |
| 38 | +} |
| 39 | + |
| 40 | + |
| 41 | +@parametrize("test_case", test_cases) |
| 42 | +def test_dialect_attention(test_case, cortex_m_target): |
| 43 | + tester = CortexMTester( |
| 44 | + test_case.model, test_case.example_inputs, target_config=cortex_m_target |
| 45 | + ) |
| 46 | + tester.test_dialect( |
| 47 | + test_case.model.ops_before_transforms, |
| 48 | + test_case.model.ops_after_transforms, |
| 49 | + qtol=2, |
| 50 | + ) |
| 51 | + |
| 52 | + |
| 53 | +@parametrize("test_case", test_cases) |
| 54 | +def test_implementation_attention(test_case, cortex_m_target): |
| 55 | + tester = CortexMTester( |
| 56 | + test_case.model, test_case.example_inputs, target_config=cortex_m_target |
| 57 | + ) |
| 58 | + tester.test_implementation(qtol=2) |
0 commit comments