|
| 1 | +import torch |
| 2 | +import pytest |
| 3 | +from xlstm.blocks.slstm.cell import sLSTMCellConfig, sLSTMCell |
| 4 | + |
| 5 | + |
| 6 | +def set_seed(seed): |
| 7 | + torch.use_deterministic_algorithms(True) |
| 8 | + torch.manual_seed(seed) |
| 9 | + torch.cuda.manual_seed_all(seed) |
| 10 | + |
| 11 | + |
| 12 | +def get_slstm_cell(backend, dtype="float32"): |
| 13 | + set_seed(42) |
| 14 | + |
| 15 | + config = sLSTMCellConfig( |
| 16 | + hidden_size=64, |
| 17 | + num_heads=4, |
| 18 | + num_states=4, |
| 19 | + backend=backend, |
| 20 | + dtype=dtype, |
| 21 | + ) |
| 22 | + |
| 23 | + return sLSTMCell(config) |
| 24 | + |
| 25 | + |
| 26 | +@pytest.mark.parametrize("with_in_state", [True, False]) |
| 27 | +def test_slstm_vanilla_vs_cuda(with_in_state): |
| 28 | + device_cuda = 'cuda' |
| 29 | + cell_vanilla = get_slstm_cell('vanilla') |
| 30 | + cell_cuda = get_slstm_cell('cuda').to(device_cuda) |
| 31 | + |
| 32 | + set_seed(42) |
| 33 | + current_input = torch.randn((1, 1, 256)) |
| 34 | + state = torch.randn((4, 1, 64)) if with_in_state else None |
| 35 | + |
| 36 | + output_vanilla, state_vanilla = cell_vanilla.forward(current_input, state) |
| 37 | + output_cuda, state_cuda = cell_cuda.forward(current_input.to(device_cuda), state.to(device_cuda) if state is not None else state) |
| 38 | + |
| 39 | + torch.testing.assert_close(output_vanilla, output_cuda.cpu()) |
| 40 | + torch.testing.assert_close(state_vanilla, state_cuda.cpu()) |
| 41 | + |
| 42 | + |
| 43 | +def test_slstm_vanilla_vs_cuda_fp16(): |
| 44 | + device_cuda = 'cuda' |
| 45 | + cell_vanilla = get_slstm_cell('vanilla') |
| 46 | + cell_cuda = get_slstm_cell('cuda', dtype="float16").to(device_cuda) |
| 47 | + |
| 48 | + set_seed(42) |
| 49 | + current_input = torch.randn((1, 1, 256)) |
| 50 | + state = torch.randn((4, 1, 64)) |
| 51 | + |
| 52 | + output_vanilla, state_vanilla = cell_vanilla.forward(current_input, state) |
| 53 | + output_cuda, state_cuda = cell_cuda.forward(current_input.to(device_cuda), state.to(device_cuda)) |
| 54 | + |
| 55 | + torch.testing.assert_close(output_vanilla, output_cuda.cpu(), rtol=1e-3, atol=1e-5) |
| 56 | + torch.testing.assert_close(state_vanilla, state_cuda.cpu(), rtol=1e-3, atol=1e-5) |
0 commit comments