| 1 | # SPDX-License-Identifier: Apache-2.0 |
| 2 | # SPDX-FileCopyrightText: Copyright contributors to the vLLM project |
| 3 | """Shared PyTorch custom silly attention for compilation tests. |
| 4 | Centralizes custom operation definitions to avoid duplicate registrations. |
| 5 | """ |
| 6 | |
| 7 | import torch |
| 8 | from torch.library import Library |
| 9 | |
| 10 | from vllm.utils.torch_utils import direct_register_custom_op |
| 11 | |
| 12 | # Shared library for all compilation test operations |
| 13 | # Using "silly" namespace to match existing test expectations |
| 14 | # import this file will automatically register |
| 15 | # torch ops for testing (like silly.attention) |
| 16 | silly_lib = Library("silly", "FRAGMENT") |
| 17 | |
| 18 | # Global counter that counts the number of times attention is invoked |
| 19 | _global_counter = 0 |
| 20 | |
| 21 | |
| 22 | def get_global_counter(): |
| 23 | """Get the current global counter value.""" |
| 24 | return _global_counter |
| 25 | |
| 26 | |
| 27 | def reset_global_counter(): |
| 28 | """Reset the global counter to 0.""" |
| 29 | global _global_counter |
| 30 | _global_counter = 0 |
| 31 | |
| 32 | |
| 33 | def silly_attention( |
| 34 | q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, out: torch.Tensor |
| 35 | ) -> None: |
| 36 | """Unified attention implementation that depends on |
| 37 | all inputs and affects the output. |
| 38 | Always increments a global counter that tests can use or ignore. |
| 39 | """ |
| 40 | global _global_counter |
| 41 | |
| 42 | # Always increment the global counter |
| 43 | _global_counter += 1 |
| 44 | |
| 45 | # Unified implementation that depends on all inputs |
| 46 | out.copy_(q + k + v) |
| 47 | |
| 48 | |
| 49 | def silly_attention_fake( |
| 50 | q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, out: torch.Tensor |
| 51 | ) -> None: |
| 52 | """Fake implementation for testing.""" |
| 53 | return |
| 54 | |
| 55 | |
| 56 | # Register the unified attention operation |
| 57 | direct_register_custom_op( |
| 58 | op_name="attention", |
| 59 | op_func=silly_attention, |
| 60 | mutates_args=["out"], |
| 61 | fake_impl=silly_attention_fake, |
| 62 | target_lib=silly_lib, |
| 63 | ) |