|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import contextlib |
| 4 | +import io |
| 5 | +import unittest |
| 6 | + |
| 7 | +import pytest |
| 8 | +import torch |
| 9 | + |
| 10 | +import helion |
| 11 | +from helion import exc |
| 12 | +from helion._testing import TestCase |
| 13 | +import helion.language as hl |
| 14 | + |
| 15 | + |
| 16 | +class TestPrintOutputCode(TestCase): |
| 17 | + def test_ref_eager_mode_code_print_error(self): |
| 18 | + """Test that RefEagerModeCodePrintError is raised when using @helion.kernel with both settings""" |
| 19 | + |
| 20 | + with pytest.raises(exc.RefEagerModeCodePrintError): |
| 21 | + |
| 22 | + @helion.kernel( |
| 23 | + use_default_config=True, |
| 24 | + print_output_code=True, |
| 25 | + ref_mode=helion.RefMode.EAGER, |
| 26 | + ) |
| 27 | + def add(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor: |
| 28 | + x, y = torch.broadcast_tensors(x, y) |
| 29 | + out = torch.empty( |
| 30 | + x.shape, |
| 31 | + dtype=torch.promote_types(x.dtype, y.dtype), |
| 32 | + device=x.device, |
| 33 | + ) |
| 34 | + for tile in hl.tile(out.size()): |
| 35 | + out[tile] = x[tile] + y[tile] |
| 36 | + return out |
| 37 | + |
| 38 | + x = torch.randn([512, 512], device="cuda", dtype=torch.float16) |
| 39 | + y = torch.randn([512, 512], device="cuda", dtype=torch.float16) |
| 40 | + torch.testing.assert_close(add(x, y), torch.add(x, y)) |
| 41 | + |
| 42 | + def test_normal_mode_code_print(self): |
| 43 | + """Test that output code is in stderr when using @helion.kernel with normal mode""" |
| 44 | + |
| 45 | + f = io.StringIO() |
| 46 | + with contextlib.redirect_stderr(f): |
| 47 | + |
| 48 | + @helion.kernel( |
| 49 | + use_default_config=True, |
| 50 | + print_output_code=True, |
| 51 | + ref_mode=helion.RefMode.OFF, |
| 52 | + ) |
| 53 | + def add(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor: |
| 54 | + x, y = torch.broadcast_tensors(x, y) |
| 55 | + out = torch.empty( |
| 56 | + x.shape, |
| 57 | + dtype=torch.promote_types(x.dtype, y.dtype), |
| 58 | + device=x.device, |
| 59 | + ) |
| 60 | + for tile in hl.tile(out.size()): |
| 61 | + out[tile] = x[tile] + y[tile] |
| 62 | + return out |
| 63 | + |
| 64 | + x = torch.randn([512, 512], device="cuda", dtype=torch.float16) |
| 65 | + y = torch.randn([512, 512], device="cuda", dtype=torch.float16) |
| 66 | + torch.testing.assert_close(add(x, y), torch.add(x, y)) |
| 67 | + |
| 68 | + self.assertNotEqual( |
| 69 | + f.getvalue(), |
| 70 | + "", |
| 71 | + "Output code in stderr should not be empty at normal mode.", |
| 72 | + ) |
| 73 | + |
| 74 | + |
| 75 | +if __name__ == "__main__": |
| 76 | + unittest.main() |
0 commit comments