File size: 7,581 Bytes
c335050
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236


import pytest
import torch
import torch.nn.functional as F
from einops import rearrange

from fla.ops.generalized_delta_rule.iplr.chunk import chunk_iplr_delta_rule
from fla.ops.generalized_delta_rule.iplr.fused_recurrent import fused_recurrent_iplr_delta_rule
from fla.utils import assert_close, device


def chunk_iplr_delta_rule_ref(
    q: torch.Tensor,
    k: torch.Tensor,
    v: torch.Tensor,
    a: torch.Tensor,
    b: torch.Tensor,
    initial_state: torch.Tensor = None,
    output_final_state: bool = True,
    scale: float = None,
    chunk_size: int = 64,
):
    BT = chunk_size
    if scale is None:
        scale = 1 / (q.shape[-1] ** 0.5)

    q, k, v, a, b = map(lambda x: x.transpose(1, 2), (q, k, v, a, b))
    T = q.shape[-2]
    pad_len = (BT - (T % BT)) % BT
    if pad_len > 0:
        q = F.pad(q, (0, 0, 0, pad_len))
        k = F.pad(k, (0, 0, 0, pad_len))
        v = F.pad(v, (0, 0, 0, pad_len))
        a = F.pad(a, (0, 0, 0, pad_len))
        b = F.pad(b, (0, 0, 0, pad_len))
    q, k, v, a, b = map(lambda x: x.to(torch.float32), [q, k, v, a, b])

    B, H, L, DK = q.shape
    DV = v.shape[-1]
    q = q * scale

    S = k.new_zeros(B, H, DK, DV)
    if initial_state is not None:
        S += initial_state

    # note that diagonal is masked.
    mask = torch.triu(torch.ones(chunk_size, chunk_size, dtype=torch.bool, device=q.device), diagonal=0)
    q, k, v, a, b = map(lambda x: rearrange(x, 'b h (n c) d -> b h n c d', c=chunk_size), [q, k, v, a, b])

    v2 = (a @ k.transpose(-1, -2)).masked_fill_(mask, 0) @ v
    attn = (a @ b.transpose(-1, -2)).masked_fill(mask, 0)
    for i in range(1, chunk_size):
        attn[..., i, :i] = attn[..., i, :i] + (attn[..., i, :, None].clone() * attn[..., :, :i].clone()).sum(-2)
    attn = attn + torch.eye(chunk_size, dtype=torch.float, device=q.device)
    u = attn @ v2
    w = attn @ a
    o = torch.zeros_like(v)
    mask = torch.triu(torch.ones(chunk_size, chunk_size, dtype=torch.bool, device=q.device), diagonal=1)
    for i in range(0, L // chunk_size):
        current_chunk_size = min(chunk_size, L - i * chunk_size)  # to handle the last chunk with possibly padding
        q_i = q[:, :, i, :current_chunk_size]
        k_i = k[:, :, i, :current_chunk_size]
        v_i = v[:, :, i, :current_chunk_size]
        u_i = u[:, :, i, :current_chunk_size]
        w_i = w[:, :, i, :current_chunk_size]
        b_i = b[:, :, i, :current_chunk_size]
        o_1 = (q_i @ k_i.transpose(-1, -2)).masked_fill_(mask, 0) @ v_i
        v2_i = u_i + w_i @ S
        o_2 = (q_i @ b_i.transpose(-1, -2)).masked_fill_(mask, 0) @ v2_i
        o_3 = q_i @ S
        o[:, :, i, :current_chunk_size] = o_1 + o_2 + o_3
        S = S + k_i.transpose(-1, -2) @ v_i + b_i.transpose(-1, -2) @ v2_i
    S = None if output_final_state is False else S
    o = rearrange(o, 'b h n c d -> b h (n c) d')
    o = o[:, :, :T]
    o = o.transpose(1, 2)
    return o, S


def recurrence_iplr_delta_rule_ref(
    q,
    k,
    v,
    a,
    b,
    initial_state: torch.Tensor | None = None,
    output_final_state: bool = True,
    scale: float | None = None,
):
    orig_dtype = q.dtype
    if scale is None:
        scale = 1 / (q.shape[-1] ** 0.5)
    q, k, v, a, b = map(lambda x: x.transpose(1, 2).to(torch.float32), [q, k, v, a, b])
    q = q * scale
    B, H, L, DK = q.shape
    DV = v.shape[-1]
    o = torch.zeros_like(v)
    S = torch.zeros(B, H, DK, DV).to(v)
    if initial_state is not None:
        S += initial_state

    for i in range(q.shape[-2]):
        _k = k[:, :, i]
        _q = q[:, :, i]
        _v = v[:, :, i]
        _a = a[:, :, i]
        _b = b[:, :, i]
        _kv = _k[..., None] * _v[..., None, :] + (S.clone() * _a[..., None]).sum(-2, keepdim=True) * _b[..., None]
        S = S + _kv
        o[:, :, i] = torch.einsum('bhd,bhdm->bhm', _q, S)
    S = None if output_final_state is False else S
    o = o.transpose(1, 2)
    return o.to(orig_dtype), S


@pytest.mark.parametrize(
    ('B', 'T', 'H', 'D', 'scale', 'dtype'),
    [
        pytest.param(*test, id="B{}-T{}-H{}-D{}-scale{}-{}".format(*test))
        for test in [
            (1, 63, 1, 64, 1, torch.float),
            (2, 1024, 4, 60, 1, torch.float),
            (2, 1024, 8, 100, 1, torch.float),
            (2, 1024, 8, 128, 0.1, torch.float),
            (4, 2048, 8, 64, 0.1, torch.float),
        ]
    ],
)
def test_fused_recurrent(
    B: int,
    T: int,
    H: int,
    D: int,
    scale: float,
    dtype: torch.dtype,
):
    q = torch.randn(B, T, H, D, dtype=dtype)
    k = torch.randn(B, T, H, D, dtype=dtype)
    v = torch.randn(B, T, H, D, dtype=dtype)
    a = torch.rand(B, T, H, D, dtype=dtype)

    a = F.normalize(a, p=2, dim=-1)
    b = -a
    h0 = torch.zeros(B, H, D, D, dtype=torch.float32)
    q, k, v, a, b, h0 = map(lambda x: x.to(device).requires_grad_(True), (q, k, v, a, b, h0))
    ref, ref_ht = recurrence_iplr_delta_rule_ref(
        q=q.clone(),
        k=k.clone(),
        v=v.clone(),
        a=a.clone(),
        b=b.clone(),
        scale=scale,
        initial_state=h0.clone(),
        output_final_state=True,
    )
    dht = torch.rand_like(h0)
    do = torch.rand_like(ref)
    ((dht * ref_ht).sum() + (do * ref).sum()).backward()
    dq, dk, dv, da, db, dh0 = map(lambda x: x.grad, (q, k, v, a, b, h0))
    q.grad, k.grad, v.grad, a.grad, b.grad, h0.grad = None, None, None, None, None, None
    tri, tri_ht = fused_recurrent_iplr_delta_rule(
        q=q.clone(),
        k=k.clone(),
        v=v.clone(),
        a=a.clone(),
        b=b.clone(),
        scale=scale,
        initial_state=h0.clone(),
        output_final_state=True,
    )
    ((dht * tri_ht).sum() + (do * tri).sum()).backward()
    assert_close('o', ref, tri, 0.003)
    assert_close('ht', ref_ht, tri_ht, 0.003)
    assert_close('dq', dq, q.grad, 0.003)
    assert_close('dk', dk, k.grad, 0.003)
    assert_close('dv', dv, v.grad, 0.003)
    assert_close('da', da, a.grad, 0.003)
    assert_close('db', db, b.grad, 0.003)
    assert_close('dh0', dh0, h0.grad, 0.003)


@pytest.mark.parametrize(
    ('B', 'T', 'H', 'D', 'scale', 'dtype'),
    [
        pytest.param(*test, id="B{}-T{}-H{}-D{}-scale{}-{}".format(*test))
        for test in [
            (1, 63, 1, 64, 1, torch.float16),
            (2, 500, 3, 60, 1, torch.float16),
            (2, 1000, 3, 64, 0.1, torch.float16),
            (2, 1024, 4, 100, 1, torch.float16),
            (3, 1024, 4, 128, 0.1, torch.float16),
            (4, 2048, 8, 64, 0.1, torch.float16),
        ]
    ],
)
def test_chunk(
    B: int,
    T: int,
    H: int,
    D: int,
    scale: float,
    dtype: torch.dtype,
):
    q = torch.randn(B, T, H, D, dtype=dtype)
    k = torch.randn(B, T, H, D, dtype=dtype)
    v = torch.randn(B, T, H, D, dtype=dtype)
    a = torch.rand(B, T, H, D, dtype=dtype)

    a = F.normalize(a, p=2, dim=-1)
    b = -a
    h0 = torch.zeros(B, H, D, D, dtype=torch.float32)
    q, k, v, a, b, h0 = map(lambda x: x.to(device).requires_grad_(), (q, k, v, a, b, h0))
    ref, ref_ht = recurrence_iplr_delta_rule_ref(
        q=q.clone(),
        k=k.clone(),
        v=v.clone(),
        a=a.clone(),
        b=b.clone(),
        scale=scale,
        initial_state=h0.clone(),
        output_final_state=True,
    )
    tri, tri_ht = chunk_iplr_delta_rule(
        q=q.clone(),
        k=k.clone(),
        v=v.clone(),
        a=a.clone(),
        b=b.clone(),
        scale=scale,
        initial_state=h0.clone(),
        output_final_state=True,
    )
    assert_close('o', ref, tri, 0.007)
    assert_close('ht', ref_ht, tri_ht, 0.008)