|
| 1 | +import pytest |
| 2 | +import torch |
| 3 | + |
| 4 | +import flag_gems |
| 5 | + |
| 6 | +from . import accuracy_utils as utils |
| 7 | +from . import conftest as cfg |
| 8 | + |
| 9 | +device = flag_gems.device |
| 10 | + |
| 11 | + |
| 12 | +@pytest.mark.one_hot |
| 13 | +def test_one_hot(): |
| 14 | + gems_one_hot = flag_gems.one_hot |
| 15 | + |
| 16 | + dev_type = torch.device(device).type |
| 17 | + expected_device = "cpu" if cfg.TO_CPU else device |
| 18 | + |
| 19 | + x = torch.tensor([3, 4, 1, 0], device=device, dtype=torch.int64) |
| 20 | + t = gems_one_hot(x) |
| 21 | + expected = torch.tensor( |
| 22 | + [[0, 0, 0, 1, 0], [0, 0, 0, 0, 1], [0, 1, 0, 0, 0], [1, 0, 0, 0, 0]], |
| 23 | + device=expected_device, |
| 24 | + ) |
| 25 | + utils.gems_assert_equal(t, expected) |
| 26 | + |
| 27 | + t = gems_one_hot(x, -1) |
| 28 | + expected = torch.tensor( |
| 29 | + [[0, 0, 0, 1, 0], [0, 0, 0, 0, 1], [0, 1, 0, 0, 0], [1, 0, 0, 0, 0]], |
| 30 | + device=expected_device, |
| 31 | + ) |
| 32 | + utils.gems_assert_equal(t, expected) |
| 33 | + |
| 34 | + t = gems_one_hot(x, 6) |
| 35 | + expected = torch.tensor( |
| 36 | + [ |
| 37 | + [0, 0, 0, 1, 0, 0], |
| 38 | + [0, 0, 0, 0, 1, 0], |
| 39 | + [0, 1, 0, 0, 0, 0], |
| 40 | + [1, 0, 0, 0, 0, 0], |
| 41 | + ], |
| 42 | + device=expected_device, |
| 43 | + ) |
| 44 | + utils.gems_assert_equal(t, expected) |
| 45 | + |
| 46 | + x2 = torch.tensor([[3, 4], [1, 0]], device=device, dtype=torch.int64) |
| 47 | + t = gems_one_hot(x2) |
| 48 | + expected = torch.tensor( |
| 49 | + [[[0, 0, 0, 1, 0], [0, 0, 0, 0, 1]], [[0, 1, 0, 0, 0], [1, 0, 0, 0, 0]]], |
| 50 | + device=expected_device, |
| 51 | + ) |
| 52 | + utils.gems_assert_equal(t, expected) |
| 53 | + |
| 54 | + x0 = torch.tensor(4, device=device, dtype=torch.int64) |
| 55 | + t = gems_one_hot(x0) |
| 56 | + expected = torch.tensor([0, 0, 0, 0, 1], device=expected_device) |
| 57 | + utils.gems_assert_equal(t, expected) |
| 58 | + |
| 59 | + x_empty = torch.empty([4, 0], dtype=torch.long, device=device) |
| 60 | + t = gems_one_hot(x_empty, 100) |
| 61 | + expected = torch.empty([4, 0, 100], dtype=torch.long, device=expected_device) |
| 62 | + utils.gems_assert_equal(t, expected) |
| 63 | + |
| 64 | + if dev_type not in ("cuda", "xla", "mps"): |
| 65 | + bad = torch.tensor([3, 4, -1, 0], dtype=torch.long) |
| 66 | + with pytest.raises(RuntimeError): |
| 67 | + gems_one_hot(bad.to(device), -1) |
| 68 | + |
| 69 | + bad = torch.tensor([3, 4, 1, 0], dtype=torch.long) |
| 70 | + with pytest.raises(RuntimeError): |
| 71 | + gems_one_hot(bad.to(device), 3) |
| 72 | + |
| 73 | + with pytest.raises(RuntimeError): |
| 74 | + gems_one_hot(torch.empty([4, 0], dtype=torch.long, device=device)) |
| 75 | + |
| 76 | + with pytest.raises(RuntimeError): |
| 77 | + gems_one_hot(torch.tensor([3, 4, 1, 0], dtype=torch.long, device=device), -2) |
0 commit comments