| 1 | # SPDX-License-Identifier: Apache-2.0 |
| 2 | # SPDX-FileCopyrightText: Copyright contributors to the vLLM project |
| 3 | """End-to-end JIT monitor tests: real Triton kernel, real GPU, real hook.""" |
| 4 | |
| 5 | from unittest import mock |
| 6 | |
| 7 | import pytest |
| 8 | |
| 9 | from vllm.utils import jit_monitor |
| 10 | |
| 11 | try: |
| 12 | import torch |
| 13 | |
| 14 | _HAS_CUDA = torch.cuda.is_available() |
| 15 | except ImportError: |
| 16 | _HAS_CUDA = False |
| 17 | |
| 18 | try: |
| 19 | import triton |
| 20 | import triton.language as tl |
| 21 | |
| 22 | _HAS_TRITON = True |
| 23 | except ImportError: |
| 24 | _HAS_TRITON = False |
| 25 | |
| 26 | pytestmark = pytest.mark.skipif( |
| 27 | not (_HAS_CUDA and _HAS_TRITON), |
| 28 | reason="Requires CUDA GPU and Triton", |
| 29 | ) |
| 30 | |
| 31 | |
| 32 | if _HAS_TRITON: |
| 33 | |
| 34 | @triton.jit |
| 35 | def _add_kernel(x_ptr, y_ptr, out_ptr, n, BLOCK: tl.constexpr): |
| 36 | pid = tl.program_id(0) |
| 37 | offs = pid * BLOCK + tl.arange(0, BLOCK) |
| 38 | mask = offs < n |
| 39 | x = tl.load(x_ptr + offs, mask=mask) |
| 40 | y = tl.load(y_ptr + offs, mask=mask) |
| 41 | tl.store(out_ptr + offs, x + y, mask=mask) |
| 42 | |
| 43 | |
| 44 | def _run_add_kernel(n: int, block: int = 256, offset: int = 0) -> None: |
| 45 | """Launch ``_add_kernel`` with vectors of length *n*.""" |
| 46 | x = torch.randn(n + offset, device="cuda")[offset:] # affect alignment |
| 47 | y = torch.randn(n, device="cuda") |
| 48 | out = torch.empty(n, device="cuda") |
| 49 | grid = ((n + block - 1) // block,) |
| 50 | _add_kernel[grid](x, y, out, n, BLOCK=block) |
| 51 | torch.accelerator.synchronize() |
| 52 | |
| 53 | |
| 54 | def test_no_warning_on_cached_shape(): |
| 55 | _run_add_kernel(1024) |
| 56 | |
| 57 | jit_monitor.activate() |
| 58 | with mock.patch.object(jit_monitor.logger, "warning_once") as w: |
| 59 | _run_add_kernel(1024) |
| 60 | w.assert_not_called() |
| 61 | |
| 62 | |
| 63 | def test_warning_on_new_constexpr(): |
| 64 | _run_add_kernel(1024, block=256) |
| 65 | |
| 66 | jit_monitor.activate() |
| 67 | with mock.patch.object(jit_monitor.logger, "warning_once") as w: |
| 68 | # Different BLOCK (a tl.constexpr) forces recompilation. |
| 69 | _run_add_kernel(1024, block=512) |
| 70 | w.assert_called() |
| 71 | msg = w.call_args[0][0] % w.call_args[0][1:] |
| 72 | assert "_add_kernel" in msg |
| 73 | |
| 74 | |
| 75 | def test_verbose_warning_on_each_new_pointer_alignment(): |
| 76 | _run_add_kernel(1024) |
| 77 | |
| 78 | jit_monitor.activate(verbose=True) |
| 79 | with ( |
| 80 | mock.patch.object(jit_monitor.logger, "warning") as w, |
| 81 | mock.patch.object(jit_monitor.logger, "warning_once") as w_once, |
| 82 | ): |
| 83 | _run_add_kernel(1024, offset=1) |
| 84 | assert w.called |
| 85 | w_once.assert_not_called() |