Skip to content

Commit bf27527

Browse files
Slstm fp16 (#14)
Replay of NX-AI/xlstm-internal#10 after rebasing to current state of public repo.
1 parent 2df8066 commit bf27527

2 files changed

Lines changed: 58 additions & 0 deletions

File tree

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
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)

xlstm/blocks/slstm/src/util/support.h

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,8 @@ template <> torch::Dtype typeToTorchDtype<float>() { return torch::kFloat; }
6060

6161
template <> torch::Dtype typeToTorchDtype<at::Half>() { return torch::kHalf; }
6262

63+
template <> torch::Dtype typeToTorchDtype<__half>() { return torch::kHalf; }
64+
6365
template <> torch::Dtype typeToTorchDtype<at::BFloat16>() {
6466
return torch::kBFloat16;
6567
}

0 commit comments

Comments
 (0)