test_dropout_layer_norm.py 49 KB
Newer Older
1
2
import math

Tri Dao's avatar
Tri Dao committed
3
import pytest
4
5
import torch
import torch.nn.functional as F
6
from einops import rearrange, repeat
Tri Dao's avatar
Tri Dao committed
7
8
9
10
11
12
13
14
15
16
17
18
from flash_attn.ops.layer_norm import (
    DropoutAddLayerNorm,
    dropout_add_layer_norm,
    dropout_add_layer_norm_parallel_residual,
    dropout_add_layer_norm_subset,
)
from flash_attn.ops.rms_norm import (
    DropoutAddRMSNorm,
    dropout_add_rms_norm,
    dropout_add_rms_norm_parallel_residual,
    dropout_add_rms_norm_subset,
)
Tri Dao's avatar
Tri Dao committed
19
20
21

try:
    from apex.normalization import FusedRMSNorm
22
    from apex.normalization.fused_layer_norm import fused_rms_norm_affine
Tri Dao's avatar
Tri Dao committed
23
except:
24
    FusedRMSNorm, fused_rms_norm_affine = None, None
25
26


Tri Dao's avatar
Tri Dao committed
27
is_sm8x = torch.cuda.get_device_capability("cuda")[0] >= 8
28

Tri Dao's avatar
Tri Dao committed
29
30
31

@pytest.mark.parametrize("is_rms_norm", [False, True])
@pytest.mark.parametrize("has_colscale", [True, False])
Tri Dao's avatar
Tri Dao committed
32
# @pytest.mark.parametrize('has_colscale', [False])
Tri Dao's avatar
Tri Dao committed
33
@pytest.mark.parametrize("has_rowscale", [True, False])
34
# @pytest.mark.parametrize('has_rowscale', [True])
Tri Dao's avatar
Tri Dao committed
35
@pytest.mark.parametrize("has_residual", [True, False])
36
# @pytest.mark.parametrize('has_residual', [False])
Tri Dao's avatar
Tri Dao committed
37
@pytest.mark.parametrize("dropout_p", [0.37, 0.0])
38
# @pytest.mark.parametrize('dropout_p', [0.0])
Tri Dao's avatar
Tri Dao committed
39
@pytest.mark.parametrize("weight_dtype", [torch.float32, torch.float16])
40
# @pytest.mark.parametrize('weight_dtype', [torch.float32])
Tri Dao's avatar
Tri Dao committed
41
42
43
44
45
@pytest.mark.parametrize(
    "input_dtype,residual_dtype",
    [(torch.float16, torch.float16), (torch.float16, torch.float32), (torch.float32, torch.float32)]
    + ([(torch.bfloat16, torch.bfloat16), (torch.bfloat16, torch.float32)] if is_sm8x else []),
)
46
# @pytest.mark.parametrize('input_dtype,residual_dtype', [(torch.float16, torch.float32)])
Tri Dao's avatar
Tri Dao committed
47
48
49
50
@pytest.mark.parametrize(
    "hidden_size",
    [192, 256, 384, 768, 1024, 1280, 1536, 1600, 2048, 2560, 3000, 3072, 4096, 5120, 6144],
)
51
# @pytest.mark.parametrize('hidden_size', [256])
Tri Dao's avatar
Tri Dao committed
52
53
54
55
56
57
58
59
60
61
62
def test_dropout_layer_norm_training(
    hidden_size,
    input_dtype,
    residual_dtype,
    weight_dtype,
    dropout_p,
    has_residual,
    has_rowscale,
    has_colscale,
    is_rms_norm,
):
63
64
    if weight_dtype == torch.float16 and input_dtype == torch.bfloat16:
        pytest.skip()  # Not supported
Tri Dao's avatar
Tri Dao committed
65
66
67
68
69
    if is_rms_norm and FusedRMSNorm is None:
        pytest.skip()  # We need Apex's FusedRMSNorm to test
    layer_norm_cls = torch.nn.LayerNorm if not is_rms_norm else FusedRMSNorm
    our_layer_norm_cls = DropoutAddLayerNorm if not is_rms_norm else DropoutAddRMSNorm
    our_layer_norm_func = dropout_add_layer_norm if not is_rms_norm else dropout_add_rms_norm
Tri Dao's avatar
Tri Dao committed
70
    device = "cuda"
71
72
73
74
75
76
    # rtol, atol = (1e-5, 1e-6) if input_dtype == torch.float32 else (1e-3, 1e-4)
    rtol, atol = (1e-3, 1e-4)
    # set seed
    torch.random.manual_seed(0)
    batch_size = 8
    seqlen = 512
Tri Dao's avatar
Tri Dao committed
77
78
79
    x0_pt = torch.randn(
        batch_size, seqlen, hidden_size, device=device, dtype=input_dtype, requires_grad=True
    )
80
81
    x0 = x0_pt.detach().clone().requires_grad_()
    x0_ref = x0_pt.detach().clone().float().requires_grad_()
Tri Dao's avatar
Tri Dao committed
82
83
84
85
86
87
    if has_colscale:
        colscale = torch.randn(hidden_size, device=device, dtype=weight_dtype, requires_grad=True)
        colscale_pt = colscale.detach().clone().requires_grad_()
        colscale_ref = colscale.detach().clone().float().requires_grad_()
    else:
        colscale = None
88
    if has_residual:
89
90
91
        res_pt = torch.randn_like(x0, dtype=residual_dtype, requires_grad=True)
        res = res_pt.detach().clone().requires_grad_()
        res_ref = res_pt.detach().clone().float().requires_grad_()
92
    else:
93
        res = None
94
95
96
97
    if has_rowscale:
        rowscale = torch.empty(batch_size, seqlen, device=device, dtype=input_dtype)
        survival_rate = 0.87
        rowscale = rowscale.bernoulli_(survival_rate) / survival_rate
Tri Dao's avatar
Tri Dao committed
98
99
        x0_scaled_pt = x0_pt * rearrange(rowscale, "... -> ... 1")
        x0_scaled_ref = x0_ref * rearrange(rowscale, "... -> ... 1")
100
101
102
103
    else:
        rowscale = None
        x0_scaled_pt = x0_pt
        x0_scaled_ref = x0_ref
Tri Dao's avatar
Tri Dao committed
104
105
106
    if has_colscale:
        x0_scaled_pt = x0_scaled_pt * colscale_pt
        x0_scaled_ref = x0_scaled_ref * colscale_ref
Tri Dao's avatar
Tri Dao committed
107
    model_pt = layer_norm_cls(hidden_size).to(device=device, dtype=weight_dtype)
108
    torch.nn.init.normal_(model_pt.weight)
Tri Dao's avatar
Tri Dao committed
109
110
111
112
    if not is_rms_norm:
        torch.nn.init.normal_(model_pt.bias)
    model_ref = layer_norm_cls(hidden_size).to(device=device, dtype=torch.float32)
    model = our_layer_norm_cls(hidden_size, p=dropout_p, device=device, dtype=weight_dtype)
113
114
115
    with torch.no_grad():
        model.weight.copy_(model_pt.weight)
        model_ref.weight.copy_(model_pt.weight)
Tri Dao's avatar
Tri Dao committed
116
117
118
        if not is_rms_norm:
            model.bias.copy_(model_pt.bias)
            model_ref.bias.copy_(model_pt.bias)
119
    residual_in_fp32 = (not has_residual) and residual_dtype == torch.float32
Tri Dao's avatar
Tri Dao committed
120
121
122
123
124
125
126
127
128
129
130
131
    out, dmask = our_layer_norm_func(
        x0,
        res,
        model.weight,
        model.bias,
        model.p,
        model.eps,
        rowscale=rowscale,
        layerscale=colscale,
        residual_in_fp32=residual_in_fp32,
        return_dropout_mask=True,
    )
132
    assert out.dtype == input_dtype
Tri Dao's avatar
Tri Dao committed
133
    print(f"Actual dropout fraction: {1 - dmask.float().mean().item()}")
134
    if has_residual:
Tri Dao's avatar
Tri Dao committed
135
136
137
        residual_pt = (
            (x0_scaled_pt.float() * dmask.float()) / (1 - dropout_p) + res_pt.float()
        ).to(dtype=residual_dtype)
138
        residual_ref = (x0_scaled_ref * dmask.float()) / (1 - dropout_p) + res_ref
139
    else:
Tri Dao's avatar
Tri Dao committed
140
141
142
        residual_pt = ((x0_scaled_pt.float() * dmask.float()) / (1 - dropout_p)).to(
            dtype=residual_dtype
        )
143
144
145
146
147
148
149
150
151
152
153
        residual_ref = (x0_scaled_ref * dmask.float()) / (1 - dropout_p)
    out_pt = model_pt(residual_pt.to(dtype=weight_dtype)).to(dtype=input_dtype)
    out_ref = model_ref(residual_ref)
    assert (out - out_ref).abs().max() <= 4 * (out_pt - out_ref).abs().max() + 1e-4

    g = torch.randn_like(out) / batch_size
    out_pt.backward(g)
    out.backward(g)
    out_ref.backward(g)
    assert (x0.grad - x0_ref.grad).abs().max() <= 4 * (x0_pt.grad - x0_ref.grad).abs().max() + 1e-4
    if has_residual:
Tri Dao's avatar
Tri Dao committed
154
155
156
157
158
159
        assert (res.grad - res_ref.grad).abs().max() <= 4 * (
            res_pt.grad - res_ref.grad
        ).abs().max() + 1e-4
    assert (model.weight.grad - model_ref.weight.grad).abs().max() <= 3 * (
        model_pt.weight.grad - model_ref.weight.grad
    ).abs().max() + 3e-5
Tri Dao's avatar
Tri Dao committed
160
    if not is_rms_norm:
Tri Dao's avatar
Tri Dao committed
161
162
163
        assert (model.bias.grad - model_ref.bias.grad).abs().max() <= 2 * (
            model_pt.bias.grad - model_ref.bias.grad
        ).abs().max() + 3e-5
Tri Dao's avatar
Tri Dao committed
164
    if has_colscale:
Tri Dao's avatar
Tri Dao committed
165
166
167
        assert (colscale.grad - colscale_ref.grad).abs().max() <= 2 * (
            colscale_pt.grad - colscale_ref.grad
        ).abs().max() + 2e-4
168
169


Tri Dao's avatar
Tri Dao committed
170
171
172
173
174
175
176
@pytest.mark.parametrize("weight_dtype", [torch.float32, torch.float16])
@pytest.mark.parametrize(
    "input_dtype,residual_dtype",
    [(torch.float16, torch.float16), (torch.float16, torch.float32), (torch.float32, torch.float32)]
    + ([(torch.bfloat16, torch.bfloat16), (torch.bfloat16, torch.float32)] if is_sm8x else []),
)
@pytest.mark.parametrize("hidden_size", [768, 1024, 1280, 1536, 1600, 2048, 2560, 3072, 4096, 5120])
177
178
179
def test_dropout_layer_norm_eval(hidden_size, input_dtype, residual_dtype, weight_dtype):
    if weight_dtype == torch.float16 and input_dtype == torch.bfloat16:
        pytest.skip()  # Not supported
Tri Dao's avatar
Tri Dao committed
180
    device = "cuda"
181
182
183
184
185
186
187
    # rtol, atol = (1e-5, 1e-6) if dtype == torch.float32 else (1e-3, 1e-4)
    rtol, atol = (1e-3, 1e-4)
    dropout_p = 0.37
    # set seed
    torch.random.manual_seed(0)
    batch_size = 32
    seqlen = 512
Tri Dao's avatar
Tri Dao committed
188
189
190
    x0_pt = torch.randn(
        batch_size, seqlen, hidden_size, device=device, dtype=input_dtype, requires_grad=True
    )
191
192
    x0 = x0_pt.detach().clone().requires_grad_()
    x0_ref = x0_pt.detach().clone().float().requires_grad_()
193
194
195
    res_pt = torch.randn_like(x0, dtype=residual_dtype, requires_grad=True)
    res = res_pt.detach().clone().requires_grad_()
    res_ref = res_pt.detach().clone().float().requires_grad_()
196
    model_pt = torch.nn.LayerNorm(hidden_size, device=device, dtype=weight_dtype)
197
198
    torch.nn.init.normal_(model_pt.weight)
    torch.nn.init.normal_(model_pt.bias)
199
200
201
202
203
204
205
206
207
208
    model = DropoutAddLayerNorm(hidden_size, p=dropout_p, device=device, dtype=weight_dtype)
    model_ref = torch.nn.LayerNorm(hidden_size, device=device, dtype=torch.float32)
    with torch.no_grad():
        model.weight.copy_(model_pt.weight)
        model.bias.copy_(model_pt.bias)
        model_ref.weight.copy_(model_pt.weight)
        model_ref.bias.copy_(model_pt.bias)
    model_pt.eval()
    model.eval()
    model_ref.eval()
209
210
211
    out = model(x0, res)
    residual_pt = (x0_pt.float() + res_pt.float()).to(dtype=residual_dtype)
    residual_ref = x0_ref + res_ref
212
213
214
215
216
    out_pt = model_pt(residual_pt.to(dtype=weight_dtype)).to(input_dtype)
    out_ref = model_ref(residual_ref)
    assert (out - out_ref).abs().max() <= 4 * (out_pt - out_ref).abs().max() + 1e-4


Tri Dao's avatar
Tri Dao committed
217
218
219
220
221
222
223
224
225
226
227
@pytest.mark.parametrize("is_rms_norm", [False, True])
@pytest.mark.parametrize("has_colscale", [True, False])
@pytest.mark.parametrize("has_rowscale", [True, False])
@pytest.mark.parametrize("has_residual", [True, False])
@pytest.mark.parametrize("dropout_p", [0.37, 0.0])
@pytest.mark.parametrize("weight_dtype", [torch.float32, torch.float16])
@pytest.mark.parametrize(
    "input_dtype,residual_dtype",
    [(torch.float16, torch.float16), (torch.float16, torch.float32), (torch.float32, torch.float32)]
    + ([(torch.bfloat16, torch.bfloat16), (torch.bfloat16, torch.float32)] if is_sm8x else []),
)
Tri Dao's avatar
Tri Dao committed
228
229
230
231
232
233
# @pytest.mark.parametrize('has_colscale', [True])
# @pytest.mark.parametrize('has_rowscale', [False])
# @pytest.mark.parametrize('has_residual', [True])
# @pytest.mark.parametrize('dropout_p', [0.0])
# @pytest.mark.parametrize('weight_dtype', [torch.float32])
# @pytest.mark.parametrize('input_dtype,residual_dtype', [(torch.float32, torch.float32)])
Tri Dao's avatar
Tri Dao committed
234
235
236
237
@pytest.mark.parametrize(
    "hidden_size",
    [192, 256, 384, 768, 1024, 1280, 1536, 1600, 2048, 2560, 3000, 3072, 4096, 5120, 6144],
)
Tri Dao's avatar
Tri Dao committed
238
# @pytest.mark.parametrize('hidden_size', [256])
Tri Dao's avatar
Tri Dao committed
239
240
241
242
243
244
245
246
247
248
249
def test_dropout_layer_norm_prenorm_training(
    hidden_size,
    input_dtype,
    residual_dtype,
    weight_dtype,
    dropout_p,
    has_residual,
    has_rowscale,
    has_colscale,
    is_rms_norm,
):
250
251
    if weight_dtype == torch.float16 and input_dtype == torch.bfloat16:
        pytest.skip()  # Not supported
Tri Dao's avatar
Tri Dao committed
252
253
254
255
256
    if is_rms_norm and FusedRMSNorm is None:
        pytest.skip()  # We need Apex's FusedRMSNorm to test
    layer_norm_cls = torch.nn.LayerNorm if not is_rms_norm else FusedRMSNorm
    our_layer_norm_cls = DropoutAddLayerNorm if not is_rms_norm else DropoutAddRMSNorm
    our_layer_norm_func = dropout_add_layer_norm if not is_rms_norm else dropout_add_rms_norm
Tri Dao's avatar
Tri Dao committed
257
    device = "cuda"
258
259
260
261
262
263
    # rtol, atol = (1e-5, 1e-6) if input_dtype == torch.float32 else (1e-3, 1e-4)
    rtol, atol = (1e-3, 2e-4)
    # set seed
    torch.random.manual_seed(0)
    batch_size = 8
    seqlen = 512
Tri Dao's avatar
Tri Dao committed
264
265
266
    x0_pt = torch.randn(
        batch_size, seqlen, hidden_size, device=device, dtype=input_dtype, requires_grad=True
    )
267
268
    x0 = x0_pt.detach().clone().requires_grad_()
    x0_ref = x0_pt.detach().clone().float().requires_grad_()
Tri Dao's avatar
Tri Dao committed
269
270
271
272
273
274
    if has_colscale:
        colscale = torch.randn(hidden_size, device=device, dtype=weight_dtype, requires_grad=True)
        colscale_pt = colscale.detach().clone().requires_grad_()
        colscale_ref = colscale.detach().clone().float().requires_grad_()
    else:
        colscale = None
275
    if has_residual:
276
277
278
        res_pt = torch.randn_like(x0, dtype=residual_dtype, requires_grad=True)
        res = res_pt.detach().clone().requires_grad_()
        res_ref = res_pt.detach().clone().float().requires_grad_()
279
    else:
280
        res = None
281
282
283
284
    if has_rowscale:
        rowscale = torch.empty(batch_size, seqlen, device=device, dtype=input_dtype)
        survival_rate = 0.87
        rowscale = rowscale.bernoulli_(survival_rate) / survival_rate
Tri Dao's avatar
Tri Dao committed
285
286
        x0_scaled_pt = x0_pt * rearrange(rowscale, "... -> ... 1")
        x0_scaled_ref = x0_ref * rearrange(rowscale, "... -> ... 1")
287
288
289
290
    else:
        rowscale = None
        x0_scaled_pt = x0_pt
        x0_scaled_ref = x0_ref
Tri Dao's avatar
Tri Dao committed
291
292
293
    if has_colscale:
        x0_scaled_pt = x0_scaled_pt * colscale_pt
        x0_scaled_ref = x0_scaled_ref * colscale_ref
Tri Dao's avatar
Tri Dao committed
294
    model_pt = layer_norm_cls(hidden_size).to(device=device, dtype=weight_dtype)
295
    torch.nn.init.normal_(model_pt.weight)
Tri Dao's avatar
Tri Dao committed
296
297
298
    if not is_rms_norm:
        torch.nn.init.normal_(model_pt.bias)
    model_ref = layer_norm_cls(hidden_size).to(device=device, dtype=torch.float32)
Tri Dao's avatar
Tri Dao committed
299
300
301
    model = our_layer_norm_cls(
        hidden_size, prenorm=True, p=dropout_p, device=device, dtype=weight_dtype
    )
302
303
304
    with torch.no_grad():
        model.weight.copy_(model_pt.weight)
        model_ref.weight.copy_(model_pt.weight)
Tri Dao's avatar
Tri Dao committed
305
306
307
        if not is_rms_norm:
            model.bias.copy_(model_pt.bias)
            model_ref.bias.copy_(model_pt.bias)
308
    residual_in_fp32 = (not has_residual) and residual_dtype == torch.float32
Tri Dao's avatar
Tri Dao committed
309
310
311
312
313
314
315
316
317
318
319
320
321
322
    out, residual, dmask = our_layer_norm_func(
        x0,
        res,
        model.weight,
        model.bias,
        model.p,
        model.eps,
        rowscale=rowscale,
        layerscale=colscale,
        prenorm=True,
        residual_in_fp32=residual_in_fp32,
        return_dropout_mask=True,
    )
    print(f"Actual dropout fraction: {1 - dmask.float().mean().item()}")
323
    if has_residual:
Tri Dao's avatar
Tri Dao committed
324
325
326
        residual_pt = (
            (x0_scaled_pt.float() * dmask.float()) / (1 - dropout_p) + res_pt.float()
        ).to(dtype=residual_dtype)
327
        residual_ref = (x0_scaled_ref * dmask.float()) / (1 - dropout_p) + res_ref
328
    else:
Tri Dao's avatar
Tri Dao committed
329
330
331
        residual_pt = ((x0_scaled_pt.float() * dmask.float()) / (1 - dropout_p)).to(
            dtype=residual_dtype
        )
332
333
334
335
336
337
        residual_ref = (x0_scaled_ref * dmask.float()) / (1 - dropout_p)
    out_pt = model_pt(residual_pt.to(dtype=weight_dtype)).to(dtype=input_dtype)
    out_ref = model_ref(residual_ref)
    assert out.dtype == input_dtype
    assert residual.dtype == residual_dtype
    assert (out - out_ref).abs().max() <= 4 * (out_pt - out_ref).abs().max() + 1e-4
Tri Dao's avatar
Tri Dao committed
338
339
340
    assert (residual - residual_ref).abs().max() <= 4 * (
        residual_pt - residual_ref
    ).abs().max() + 1e-4
341
342
343
344
345
346
347

    g = torch.randn_like(out) / batch_size
    (out_pt * F.sigmoid(residual_pt)).backward(g)
    (out * F.sigmoid(residual)).backward(g)
    (out_ref * F.sigmoid(residual_ref.to(dtype=residual_dtype))).backward(g)
    assert (x0.grad - x0_ref.grad).abs().max() <= 4 * (x0_pt.grad - x0_ref.grad).abs().max() + 1e-4
    if has_residual:
Tri Dao's avatar
Tri Dao committed
348
349
350
351
352
353
        assert (res.grad - res_ref.grad).abs().max() <= 4 * (
            res_pt.grad - res_ref.grad
        ).abs().max() + 1e-4
    assert (model.weight.grad - model_ref.weight.grad).abs().max() <= 2 * (
        model_pt.weight.grad - model_ref.weight.grad
    ).abs().max() + 2e-4
Tri Dao's avatar
Tri Dao committed
354
    if not is_rms_norm:
Tri Dao's avatar
Tri Dao committed
355
356
357
        assert (model.bias.grad - model_ref.bias.grad).abs().max() <= 2 * (
            model_pt.bias.grad - model_ref.bias.grad
        ).abs().max() + 2e-4
Tri Dao's avatar
Tri Dao committed
358
    if has_colscale:
Tri Dao's avatar
Tri Dao committed
359
360
361
        assert (colscale.grad - colscale_ref.grad).abs().max() <= 2 * (
            colscale_pt.grad - colscale_ref.grad
        ).abs().max() + 2e-4
362
363


Tri Dao's avatar
Tri Dao committed
364
365
366
367
368
369
370
@pytest.mark.parametrize("weight_dtype", [torch.float32, torch.float16])
@pytest.mark.parametrize(
    "input_dtype,residual_dtype",
    [(torch.float16, torch.float16), (torch.float16, torch.float32), (torch.float32, torch.float32)]
    + ([(torch.bfloat16, torch.bfloat16), (torch.bfloat16, torch.float32)] if is_sm8x else []),
)
@pytest.mark.parametrize("hidden_size", [768, 1024, 1280, 1536, 1600, 2048, 2560, 3072, 4096, 5120])
371
372
373
def test_dropout_layer_norm_prenorm_eval(hidden_size, input_dtype, residual_dtype, weight_dtype):
    if weight_dtype == torch.float16 and input_dtype == torch.bfloat16:
        pytest.skip()  # Not supported
Tri Dao's avatar
Tri Dao committed
374
    device = "cuda"
375
376
377
378
379
380
381
    # rtol, atol = (1e-5, 1e-6) if dtype == torch.float32 else (1e-3, 1e-4)
    rtol, atol = (1e-3, 1e-4)
    dropout_p = 0.37
    # set seed
    torch.random.manual_seed(0)
    batch_size = 32
    seqlen = 512
Tri Dao's avatar
Tri Dao committed
382
383
384
    x0_pt = torch.randn(
        batch_size, seqlen, hidden_size, device=device, dtype=input_dtype, requires_grad=True
    )
385
386
    x0 = x0_pt.detach().clone().requires_grad_()
    x0_ref = x0_pt.detach().clone().float().requires_grad_()
387
388
389
    res_pt = torch.randn_like(x0, dtype=residual_dtype, requires_grad=True)
    res = res_pt.detach().clone().requires_grad_()
    res_ref = res_pt.detach().clone().float().requires_grad_()
390
    model_pt = torch.nn.LayerNorm(hidden_size, device=device, dtype=weight_dtype)
391
392
    torch.nn.init.normal_(model_pt.weight)
    torch.nn.init.normal_(model_pt.bias)
Tri Dao's avatar
Tri Dao committed
393
394
395
    model = DropoutAddLayerNorm(
        hidden_size, prenorm=True, p=dropout_p, device=device, dtype=weight_dtype
    )
396
397
398
399
400
401
402
403
404
    model_ref = torch.nn.LayerNorm(hidden_size, device=device, dtype=torch.float32)
    with torch.no_grad():
        model.weight.copy_(model_pt.weight)
        model.bias.copy_(model_pt.bias)
        model_ref.weight.copy_(model_pt.weight)
        model_ref.bias.copy_(model_pt.bias)
    model_pt.eval()
    model.eval()
    model_ref.eval()
405
406
407
    out, residual = model(x0, res)
    residual_pt = (x0_pt.float() + res_pt.float()).to(dtype=residual_dtype)
    residual_ref = x0_ref + res_ref
408
409
410
    out_pt = model_pt(residual_pt.to(dtype=weight_dtype)).to(input_dtype)
    out_ref = model_ref(residual_ref)
    assert (out - out_ref).abs().max() <= 4 * (out_pt - out_ref).abs().max() + 1e-4
Tri Dao's avatar
Tri Dao committed
411
412
413
    assert (residual - residual_ref).abs().max() <= 4 * (
        residual_pt - residual_ref
    ).abs().max() + 1e-4
414
415


Tri Dao's avatar
Tri Dao committed
416
417
418
419
420
421
422
423
424
@pytest.mark.parametrize("has_colscale", [True, False])
@pytest.mark.parametrize("has_residual", [True, False])
@pytest.mark.parametrize("dropout_p", [0.37, 0.0])
@pytest.mark.parametrize("weight_dtype", [torch.float32, torch.float16])
@pytest.mark.parametrize(
    "input_dtype,residual_dtype",
    [(torch.float16, torch.float16), (torch.float16, torch.float32), (torch.float32, torch.float32)]
    + ([(torch.bfloat16, torch.bfloat16), (torch.bfloat16, torch.float32)] if is_sm8x else []),
)
425
426
427
428
429
# @pytest.mark.parametrize('has_colscale', [True])
# @pytest.mark.parametrize('has_residual', [True])
# @pytest.mark.parametrize('dropout_p', [0.0])
# @pytest.mark.parametrize('weight_dtype', [torch.float32])
# @pytest.mark.parametrize('input_dtype,residual_dtype', [(torch.float32, torch.float32)])
Tri Dao's avatar
Tri Dao committed
430
431
432
433
@pytest.mark.parametrize(
    "hidden_size",
    [192, 256, 384, 768, 1024, 1280, 1536, 1600, 2048, 2560, 3000, 3072, 4096, 5120, 6144],
)
434
435
# @pytest.mark.parametrize('hidden_size', [256])
def test_dropout_layer_norm_subset_training(
Tri Dao's avatar
Tri Dao committed
436
437
    hidden_size, input_dtype, residual_dtype, weight_dtype, dropout_p, has_residual, has_colscale
):
438
439
    if weight_dtype == torch.float16 and input_dtype == torch.bfloat16:
        pytest.skip()  # Not supported
Tri Dao's avatar
Tri Dao committed
440
    device = "cuda"
441
442
443
444
445
446
447
448
    # rtol, atol = (1e-5, 1e-6) if input_dtype == torch.float32 else (1e-3, 1e-4)
    rtol, atol = (1e-3, 2e-4)
    # set seed
    torch.random.manual_seed(0)
    batch_size = 8
    seqlen = 512
    drop_path_rate = 0.4
    drop_path_scale = 1 / (1 - drop_path_rate)
Tri Dao's avatar
Tri Dao committed
449

450
451
452
453
454
    def generate_droppath_masks(batch_size, seqlen, drop_path_rate, device):
        # Do it on CPU so we can get the numrows (with .item()) without GPU-CPU sync
        mask_batch = torch.rand(batch_size) < 1 - drop_path_rate
        numrows = (mask_batch).sum().item() * seqlen
        mask_batch = mask_batch.to(device=device, non_blocking=True)
Tri Dao's avatar
Tri Dao committed
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
        mask_batch_seqlen = repeat(mask_batch, "b -> (b s)", s=seqlen)
        subset = torch.cumsum(mask_batch_seqlen, dim=0, dtype=torch.int32).masked_fill_(
            ~mask_batch_seqlen, 0
        )
        return mask_batch, numrows, rearrange(subset, "(b s) -> b s", b=batch_size)

    x0_mask_batch, x0_numrows, x0_subset = generate_droppath_masks(
        batch_size, seqlen, drop_path_rate, device
    )
    out_mask_batch, out_numrows, out_subset = generate_droppath_masks(
        batch_size, seqlen, drop_path_rate, device
    )

    x0_pt = torch.randn(
        batch_size, seqlen, hidden_size, device=device, dtype=input_dtype, requires_grad=True
    )
471
472
473
474
475
476
477
478
479
    x0 = x0_pt.detach().clone()[x0_mask_batch].requires_grad_()
    x0_ref = x0_pt.detach().clone().float().requires_grad_()
    if has_colscale:
        colscale = torch.randn(hidden_size, device=device, dtype=weight_dtype, requires_grad=True)
        colscale_pt = colscale.detach().clone().requires_grad_()
        colscale_ref = colscale.detach().clone().float().requires_grad_()
    else:
        colscale = None
    if has_residual:
480
481
482
        res_pt = torch.randn_like(x0_pt, dtype=residual_dtype, requires_grad=True)
        res = res_pt.detach().clone().requires_grad_()
        res_ref = res_pt.detach().clone().float().requires_grad_()
483
    else:
484
        res = None
485
486
487
488
489
490
491
492
493
494
495
496

    if has_colscale:
        x0_scaled_pt = x0_pt * colscale_pt
        x0_scaled_ref = x0_ref * colscale_ref
    else:
        x0_scaled_pt = x0_pt
        x0_scaled_ref = x0_ref

    model_pt = torch.nn.LayerNorm(hidden_size, device=device, dtype=weight_dtype)
    torch.nn.init.normal_(model_pt.weight)
    torch.nn.init.normal_(model_pt.bias)
    model_ref = torch.nn.LayerNorm(hidden_size, device=device, dtype=torch.float32)
Tri Dao's avatar
Tri Dao committed
497
498
499
    model = DropoutAddLayerNorm(
        hidden_size, prenorm=False, p=dropout_p, device=device, dtype=weight_dtype
    )
500
501
502
503
504
505
506
507
    with torch.no_grad():
        model.weight.copy_(model_pt.weight)
        model.bias.copy_(model_pt.bias)
        model_ref.weight.copy_(model_pt.weight)
        model_ref.bias.copy_(model_pt.bias)

    residual_in_fp32 = (not has_residual) and residual_dtype == torch.float32
    out, dmask = dropout_add_layer_norm_subset(
Tri Dao's avatar
Tri Dao committed
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
        x0,
        res,
        model.weight,
        model.bias,
        model.p,
        model.eps,
        layerscale=colscale,
        x0_subset=x0_subset,
        out_subset=out_subset,
        rowscale_const=drop_path_scale,
        out_numrows=out_numrows,
        prenorm=False,
        residual_in_fp32=residual_in_fp32,
        return_dropout_mask=True,
    )
    print(f"Actual dropout fraction: {1 - dmask.float().mean().item()}")

    x0_scaled_pt = (
        x0_scaled_pt.masked_fill(repeat(~x0_mask_batch, "b -> b s d", s=seqlen, d=hidden_size), 0)
        * drop_path_scale
    )
    x0_scaled_ref = (
        x0_scaled_ref.masked_fill(repeat(~x0_mask_batch, "b -> b s d", s=seqlen, d=hidden_size), 0)
        * drop_path_scale
    )
533
534
535
    dmask_expanded = torch.zeros_like(x0_pt, dtype=torch.uint8)
    dmask_expanded[x0_mask_batch] = dmask
    if has_residual:
Tri Dao's avatar
Tri Dao committed
536
537
538
        residual_pt = (
            (x0_scaled_pt.float() * dmask_expanded.float()) / (1 - dropout_p) + res_pt.float()
        ).to(dtype=residual_dtype)
539
        residual_ref = (x0_scaled_ref * dmask_expanded.float()) / (1 - dropout_p) + res_ref
540
    else:
Tri Dao's avatar
Tri Dao committed
541
542
543
        residual_pt = ((x0_scaled_pt.float() * dmask_expanded.float()) / (1 - dropout_p)).to(
            dtype=residual_dtype
        )
544
545
546
547
548
549
550
551
552
553
        residual_ref = (x0_scaled_ref * dmask_expanded.float()) / (1 - dropout_p)
    out_pt = model_pt(residual_pt.to(dtype=weight_dtype)).to(dtype=input_dtype)[out_mask_batch]
    out_ref = model_ref(residual_ref)[out_mask_batch]
    assert out.dtype == input_dtype
    assert (out - out_ref).abs().max() <= 4 * (out_pt - out_ref).abs().max() + 1e-4

    g = torch.randn_like(out) / batch_size
    out_pt.backward(g)
    out.backward(g)
    out_ref.backward(g)
Tri Dao's avatar
Tri Dao committed
554
555
556
    assert (x0.grad - x0_ref.grad[x0_mask_batch]).abs().max() <= 4 * (x0_pt.grad - x0_ref.grad)[
        x0_mask_batch
    ].abs().max() + 1e-4
557
    if has_residual:
Tri Dao's avatar
Tri Dao committed
558
559
560
561
562
563
564
565
566
        assert (res.grad - res_ref.grad).abs().max() <= 4 * (
            res_pt.grad - res_ref.grad
        ).abs().max() + 1e-4
    assert (model.weight.grad - model_ref.weight.grad).abs().max() <= 2 * (
        model_pt.weight.grad - model_ref.weight.grad
    ).abs().max() + 2e-4
    assert (model.bias.grad - model_ref.bias.grad).abs().max() <= 2 * (
        model_pt.bias.grad - model_ref.bias.grad
    ).abs().max() + 2e-4
567
    if has_colscale:
Tri Dao's avatar
Tri Dao committed
568
569
570
        assert (colscale.grad - colscale_ref.grad).abs().max() <= 2 * (
            colscale_pt.grad - colscale_ref.grad
        ).abs().max() + 2e-4
571
572


Tri Dao's avatar
Tri Dao committed
573
574
575
576
577
578
579
580
581
@pytest.mark.parametrize("has_colscale", [True, False])
@pytest.mark.parametrize("has_residual", [True, False])
@pytest.mark.parametrize("dropout_p", [0.37, 0.0])
@pytest.mark.parametrize("weight_dtype", [torch.float32, torch.float16])
@pytest.mark.parametrize(
    "input_dtype,residual_dtype",
    [(torch.float16, torch.float16), (torch.float16, torch.float32), (torch.float32, torch.float32)]
    + ([(torch.bfloat16, torch.bfloat16), (torch.bfloat16, torch.float32)] if is_sm8x else []),
)
582
583
584
585
586
# @pytest.mark.parametrize('has_colscale', [True])
# @pytest.mark.parametrize('has_residual', [True])
# @pytest.mark.parametrize('dropout_p', [0.0])
# @pytest.mark.parametrize('weight_dtype', [torch.float32])
# @pytest.mark.parametrize('input_dtype,residual_dtype', [(torch.float32, torch.float32)])
Tri Dao's avatar
Tri Dao committed
587
588
589
590
@pytest.mark.parametrize(
    "hidden_size",
    [192, 256, 384, 768, 1024, 1280, 1536, 1600, 2048, 2560, 3000, 3072, 4096, 5120, 6144],
)
591
592
# @pytest.mark.parametrize('hidden_size', [256])
def test_dropout_layer_norm_subset_prenorm_training(
Tri Dao's avatar
Tri Dao committed
593
594
    hidden_size, input_dtype, residual_dtype, weight_dtype, dropout_p, has_residual, has_colscale
):
595
596
    if weight_dtype == torch.float16 and input_dtype == torch.bfloat16:
        pytest.skip()  # Not supported
Tri Dao's avatar
Tri Dao committed
597
    device = "cuda"
598
599
600
601
602
603
604
605
    # rtol, atol = (1e-5, 1e-6) if input_dtype == torch.float32 else (1e-3, 1e-4)
    rtol, atol = (1e-3, 2e-4)
    # set seed
    torch.random.manual_seed(0)
    batch_size = 8
    seqlen = 512
    drop_path_rate = 0.4
    drop_path_scale = 1 / (1 - drop_path_rate)
Tri Dao's avatar
Tri Dao committed
606

607
608
609
610
611
    def generate_droppath_masks(batch_size, seqlen, drop_path_rate, device):
        # Do it on CPU so we can get the numrows (with .item()) without GPU-CPU sync
        mask_batch = torch.rand(batch_size) < 1 - drop_path_rate
        numrows = (mask_batch).sum().item() * seqlen
        mask_batch = mask_batch.to(device=device, non_blocking=True)
Tri Dao's avatar
Tri Dao committed
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
        mask_batch_seqlen = repeat(mask_batch, "b -> (b s)", s=seqlen)
        subset = torch.cumsum(mask_batch_seqlen, dim=0, dtype=torch.int32).masked_fill_(
            ~mask_batch_seqlen, 0
        )
        return mask_batch, numrows, rearrange(subset, "(b s) -> b s", b=batch_size)

    x0_mask_batch, x0_numrows, x0_subset = generate_droppath_masks(
        batch_size, seqlen, drop_path_rate, device
    )
    out_mask_batch, out_numrows, out_subset = generate_droppath_masks(
        batch_size, seqlen, drop_path_rate, device
    )

    x0_pt = torch.randn(
        batch_size, seqlen, hidden_size, device=device, dtype=input_dtype, requires_grad=True
    )
628
629
630
631
632
633
634
635
636
    x0 = x0_pt.detach().clone()[x0_mask_batch].requires_grad_()
    x0_ref = x0_pt.detach().clone().float().requires_grad_()
    if has_colscale:
        colscale = torch.randn(hidden_size, device=device, dtype=weight_dtype, requires_grad=True)
        colscale_pt = colscale.detach().clone().requires_grad_()
        colscale_ref = colscale.detach().clone().float().requires_grad_()
    else:
        colscale = None
    if has_residual:
637
638
639
        res_pt = torch.randn_like(x0_pt, dtype=residual_dtype, requires_grad=True)
        res = res_pt.detach().clone().requires_grad_()
        res_ref = res_pt.detach().clone().float().requires_grad_()
640
    else:
641
        res = None
642
643
644
645
646
647
648
649
650
651
652
653

    if has_colscale:
        x0_scaled_pt = x0_pt * colscale_pt
        x0_scaled_ref = x0_ref * colscale_ref
    else:
        x0_scaled_pt = x0_pt
        x0_scaled_ref = x0_ref

    model_pt = torch.nn.LayerNorm(hidden_size, device=device, dtype=weight_dtype)
    torch.nn.init.normal_(model_pt.weight)
    torch.nn.init.normal_(model_pt.bias)
    model_ref = torch.nn.LayerNorm(hidden_size, device=device, dtype=torch.float32)
Tri Dao's avatar
Tri Dao committed
654
655
656
    model = DropoutAddLayerNorm(
        hidden_size, prenorm=True, p=dropout_p, device=device, dtype=weight_dtype
    )
657
658
659
660
661
662
663
664
    with torch.no_grad():
        model.weight.copy_(model_pt.weight)
        model.bias.copy_(model_pt.bias)
        model_ref.weight.copy_(model_pt.weight)
        model_ref.bias.copy_(model_pt.bias)

    residual_in_fp32 = (not has_residual) and residual_dtype == torch.float32
    out, residual, dmask = dropout_add_layer_norm_subset(
Tri Dao's avatar
Tri Dao committed
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
        x0,
        res,
        model.weight,
        model.bias,
        model.p,
        model.eps,
        layerscale=colscale,
        x0_subset=x0_subset,
        out_subset=out_subset,
        rowscale_const=drop_path_scale,
        out_numrows=out_numrows,
        prenorm=True,
        residual_in_fp32=residual_in_fp32,
        return_dropout_mask=True,
    )
    print(f"Actual dropout fraction: {1 - dmask.float().mean().item()}")

    x0_scaled_pt = (
        x0_scaled_pt.masked_fill(repeat(~x0_mask_batch, "b -> b s d", s=seqlen, d=hidden_size), 0)
        * drop_path_scale
    )
    x0_scaled_ref = (
        x0_scaled_ref.masked_fill(repeat(~x0_mask_batch, "b -> b s d", s=seqlen, d=hidden_size), 0)
        * drop_path_scale
    )
690
691
692
    dmask_expanded = torch.zeros_like(x0_pt, dtype=torch.uint8)
    dmask_expanded[x0_mask_batch] = dmask
    if has_residual:
Tri Dao's avatar
Tri Dao committed
693
694
695
        residual_pt = (
            (x0_scaled_pt.float() * dmask_expanded.float()) / (1 - dropout_p) + res_pt.float()
        ).to(dtype=residual_dtype)
696
        residual_ref = (x0_scaled_ref * dmask_expanded.float()) / (1 - dropout_p) + res_ref
697
    else:
Tri Dao's avatar
Tri Dao committed
698
699
700
        residual_pt = ((x0_scaled_pt.float() * dmask_expanded.float()) / (1 - dropout_p)).to(
            dtype=residual_dtype
        )
701
702
703
704
705
706
        residual_ref = (x0_scaled_ref * dmask_expanded.float()) / (1 - dropout_p)
    out_pt = model_pt(residual_pt.to(dtype=weight_dtype)).to(dtype=input_dtype)[out_mask_batch]
    out_ref = model_ref(residual_ref)[out_mask_batch]
    assert out.dtype == input_dtype
    assert residual.dtype == residual_dtype
    assert (out - out_ref).abs().max() <= 4 * (out_pt - out_ref).abs().max() + 1e-4
Tri Dao's avatar
Tri Dao committed
707
708
709
    assert (residual - residual_ref).abs().max() <= 4 * (
        residual_pt - residual_ref
    ).abs().max() + 1e-4
710
711

    g = torch.randn_like(out) / batch_size
Tri Dao's avatar
Tri Dao committed
712
713
714
    (out_pt * F.sigmoid(residual_pt[out_mask_batch]) + residual_pt.mean(0, keepdim=True)).backward(
        g
    )
715
    (out * F.sigmoid(residual[out_mask_batch]) + residual.mean(0, keepdim=True)).backward(g)
Tri Dao's avatar
Tri Dao committed
716
717
718
719
720
721
722
    (
        out_ref * F.sigmoid(residual_ref[out_mask_batch].to(dtype=residual_dtype))
        + residual_ref.mean(0, keepdim=True)
    ).backward(g)
    assert (x0.grad - x0_ref.grad[x0_mask_batch]).abs().max() <= 4 * (x0_pt.grad - x0_ref.grad)[
        x0_mask_batch
    ].abs().max() + 1e-4
723
    if has_residual:
Tri Dao's avatar
Tri Dao committed
724
725
726
727
728
729
730
731
732
        assert (res.grad - res_ref.grad).abs().max() <= 4 * (
            res_pt.grad - res_ref.grad
        ).abs().max() + 1e-4
    assert (model.weight.grad - model_ref.weight.grad).abs().max() <= 2 * (
        model_pt.weight.grad - model_ref.weight.grad
    ).abs().max() + 2e-4
    assert (model.bias.grad - model_ref.bias.grad).abs().max() <= 2 * (
        model_pt.bias.grad - model_ref.bias.grad
    ).abs().max() + 2e-4
733
    if has_colscale:
Tri Dao's avatar
Tri Dao committed
734
735
736
        assert (colscale.grad - colscale_ref.grad).abs().max() <= 2 * (
            colscale_pt.grad - colscale_ref.grad
        ).abs().max() + 2e-4
737
738


Tri Dao's avatar
Tri Dao committed
739
@pytest.mark.parametrize("is_rms_norm", [False, True])
740
# @pytest.mark.parametrize('is_rms_norm', [False])
Tri Dao's avatar
Tri Dao committed
741
@pytest.mark.parametrize("tied_norm", [False, True])
742
# @pytest.mark.parametrize('tied_norm', [False])
Tri Dao's avatar
Tri Dao committed
743
@pytest.mark.parametrize("has_residual", [True, False])
744
# @pytest.mark.parametrize('has_residual', [False])
Tri Dao's avatar
Tri Dao committed
745
@pytest.mark.parametrize("has_x1", [True, False])
746
# @pytest.mark.parametrize('has_x1', [True])
Tri Dao's avatar
Tri Dao committed
747
@pytest.mark.parametrize("dropout_p", [0.37, 0.0])
748
# @pytest.mark.parametrize('dropout_p', [0.0])
Tri Dao's avatar
Tri Dao committed
749
@pytest.mark.parametrize("weight_dtype", [torch.float32, torch.float16])
750
# @pytest.mark.parametrize('weight_dtype', [torch.float16])
Tri Dao's avatar
Tri Dao committed
751
752
753
754
755
@pytest.mark.parametrize(
    "input_dtype,residual_dtype",
    [(torch.float16, torch.float16), (torch.float16, torch.float32), (torch.float32, torch.float32)]
    + ([(torch.bfloat16, torch.bfloat16), (torch.bfloat16, torch.float32)] if is_sm8x else []),
)
756
# @pytest.mark.parametrize('input_dtype,residual_dtype', [(torch.float16, torch.float32)])
Tri Dao's avatar
Tri Dao committed
757
758
759
760
@pytest.mark.parametrize(
    "hidden_size",
    [192, 256, 384, 768, 1024, 1280, 1536, 1600, 2048, 2560, 3000, 3072, 4096, 5120, 6144],
)
761
762
# @pytest.mark.parametrize('hidden_size', [256])
def test_dropout_layer_norm_parallel_residual_training(
Tri Dao's avatar
Tri Dao committed
763
764
765
766
767
768
769
770
771
    hidden_size,
    input_dtype,
    residual_dtype,
    weight_dtype,
    dropout_p,
    has_x1,
    has_residual,
    tied_norm,
    is_rms_norm,
772
773
774
775
776
):
    if weight_dtype == torch.float16 and input_dtype == torch.bfloat16:
        pytest.skip()  # Not supported
    if is_rms_norm and fused_rms_norm_affine is None:
        pytest.skip()  # We need Apex's FusedRMSNorm to test
Tri Dao's avatar
Tri Dao committed
777
778
779
780
781
782
    our_layer_norm_func = (
        dropout_add_layer_norm_parallel_residual
        if not is_rms_norm
        else dropout_add_rms_norm_parallel_residual
    )
    device = "cuda"
783
784
785
786
787
788
    # rtol, atol = (1e-5, 1e-6) if input_dtype == torch.float32 else (1e-3, 1e-4)
    rtol, atol = (1e-3, 1e-4)
    # set seed
    torch.random.manual_seed(0)
    batch_size = 8
    seqlen = 512
Tri Dao's avatar
Tri Dao committed
789
790
791
    x0_pt = torch.randn(
        batch_size, seqlen, hidden_size, device=device, dtype=input_dtype, requires_grad=True
    )
792
793
794
    x0 = x0_pt.detach().clone().requires_grad_()
    x0_ref = x0_pt.detach().clone().float().requires_grad_()
    if has_x1:
Tri Dao's avatar
Tri Dao committed
795
796
797
        x1_pt = torch.randn(
            batch_size, seqlen, hidden_size, device=device, dtype=input_dtype, requires_grad=True
        )
798
799
800
801
802
803
804
805
806
807
808
        x1 = x1_pt.detach().clone().requires_grad_()
        x1_ref = x1_pt.detach().clone().float().requires_grad_()
    else:
        x1 = None
    if has_residual:
        res_pt = torch.randn_like(x0, dtype=residual_dtype, requires_grad=True)
        res = res_pt.detach().clone().requires_grad_()
        res_ref = res_pt.detach().clone().float().requires_grad_()
    else:
        res = None
    weight0 = torch.randn(hidden_size, device=device, dtype=weight_dtype, requires_grad=True)
Tri Dao's avatar
Tri Dao committed
809
810
811
812
813
    bias0 = (
        torch.randn(hidden_size, device=device, dtype=weight_dtype, requires_grad=True)
        if not is_rms_norm
        else None
    )
814
815
816
817
818
819
    weight0_pt = weight0.detach().clone().requires_grad_()
    weight0_ref = weight0.detach().clone().float().requires_grad_()
    bias0_pt = bias0.detach().clone().requires_grad_() if bias0 is not None else None
    bias0_ref = bias0.detach().clone().float().requires_grad_() if bias0 is not None else None
    if not tied_norm:
        weight1 = torch.randn(hidden_size, device=device, dtype=weight_dtype, requires_grad=True)
Tri Dao's avatar
Tri Dao committed
820
821
822
823
824
        bias1 = (
            torch.randn(hidden_size, device=device, dtype=weight_dtype, requires_grad=True)
            if not is_rms_norm
            else None
        )
825
826
827
828
829
830
831
832
833
834
        weight1_pt = weight1.detach().clone().requires_grad_()
        weight1_ref = weight1.detach().clone().float().requires_grad_()
        bias1_pt = bias1.detach().clone().requires_grad_() if bias1 is not None else None
        bias1_ref = bias1.detach().clone().float().requires_grad_() if bias1 is not None else None
    else:
        weight1, bias1 = None, None
    epsilon = 1e-5
    residual_in_fp32 = (not has_residual) and residual_dtype == torch.float32

    out0, out1, dmask0, dmask1 = our_layer_norm_func(
Tri Dao's avatar
Tri Dao committed
835
836
837
838
839
840
841
842
843
844
845
        x0,
        x1,
        res,
        weight0,
        bias0,
        weight1,
        bias1,
        dropout_p,
        epsilon,
        residual_in_fp32=residual_in_fp32,
        return_dropout_mask=True,
846
847
848
849
    )
    assert out0.dtype == input_dtype
    if not tied_norm:
        assert out1.dtype == input_dtype
Tri Dao's avatar
Tri Dao committed
850
    print(f"Actual dropout fraction: {1 - dmask0.float().mean().item()}")
851
852
    if has_residual:
        if has_x1:
Tri Dao's avatar
Tri Dao committed
853
854
855
856
857
858
859
860
861
            residual_pt = (
                (x0_pt.float() * dmask0.float()) / (1 - dropout_p)
                + (x1_pt.float() * dmask1.float()) / (1 - dropout_p)
                + res_pt.float()
            ).to(dtype=residual_dtype)
            residual_ref = (
                (x0_ref * dmask0.float()) / (1 - dropout_p)
                + (x1_ref * dmask1.float()) / (1 - dropout_p)
            ) + res_ref
862
        else:
Tri Dao's avatar
Tri Dao committed
863
864
865
            residual_pt = ((x0_pt.float() * dmask0.float()) / (1 - dropout_p) + res_pt.float()).to(
                dtype=residual_dtype
            )
866
867
868
            residual_ref = (x0_ref * dmask0.float()) / (1 - dropout_p) + res_ref
    else:
        if has_x1:
Tri Dao's avatar
Tri Dao committed
869
870
871
872
873
874
875
            residual_pt = (
                (x0_pt.float() * dmask0.float()) / (1 - dropout_p)
                + (x1_pt.float() * dmask1.float()) / (1 - dropout_p)
            ).to(dtype=residual_dtype)
            residual_ref = (x0_ref * dmask0.float()) / (1 - dropout_p) + (
                x1_ref * dmask1.float()
            ) / (1 - dropout_p)
876
        else:
Tri Dao's avatar
Tri Dao committed
877
878
879
            residual_pt = ((x0_pt.float() * dmask0.float()) / (1 - dropout_p)).to(
                dtype=residual_dtype
            )
880
881
            residual_ref = (x0_ref * dmask0.float()) / (1 - dropout_p)
    if not is_rms_norm:
Tri Dao's avatar
Tri Dao committed
882
883
884
        out0_pt = F.layer_norm(
            residual_pt.to(dtype=weight_dtype), (hidden_size,), weight0_pt, bias0_pt, eps=epsilon
        ).to(dtype=input_dtype)
885
886
        out0_ref = F.layer_norm(residual_ref, (hidden_size,), weight0_ref, bias0_ref, eps=epsilon)
        if not tied_norm:
Tri Dao's avatar
Tri Dao committed
887
888
889
890
891
892
893
894
895
896
            out1_pt = F.layer_norm(
                residual_pt.to(dtype=weight_dtype),
                (hidden_size,),
                weight1_pt,
                bias1_pt,
                eps=epsilon,
            ).to(dtype=input_dtype)
            out1_ref = F.layer_norm(
                residual_ref, (hidden_size,), weight1_ref, bias1_ref, eps=epsilon
            )
897
    else:
Tri Dao's avatar
Tri Dao committed
898
899
900
        out0_pt = fused_rms_norm_affine(
            residual_pt.to(dtype=weight_dtype), weight0_pt, (hidden_size,), eps=epsilon
        ).to(dtype=input_dtype)
901
902
        out0_ref = fused_rms_norm_affine(residual_ref, weight0_ref, (hidden_size,), eps=epsilon)
        if not tied_norm:
Tri Dao's avatar
Tri Dao committed
903
904
905
            out1_pt = fused_rms_norm_affine(
                residual_pt.to(dtype=weight_dtype), weight1_pt, (hidden_size,), eps=epsilon
            ).to(dtype=input_dtype)
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
            out1_ref = fused_rms_norm_affine(residual_ref, weight1_ref, (hidden_size,), eps=epsilon)

    assert (out0 - out0_ref).abs().max() <= 4 * (out0_pt - out0_ref).abs().max() + 1e-4
    if not tied_norm:
        assert (out1 - out1_ref).abs().max() <= 4 * (out1_pt - out1_ref).abs().max() + 1e-4

    g0 = torch.randn_like(out0) / batch_size
    if tied_norm:
        out0.backward(g0)
        out0_pt.backward(g0)
        out0_ref.backward(g0)
    else:
        g1 = torch.randn_like(out1) / batch_size
        (out0 * g0 + out1 * g1).sum().backward()
        (out0_pt * g0 + out1_pt * g1).sum().backward()
        (out0_ref * g0 + out1_ref * g1).sum().backward()
    assert (x0.grad - x0_ref.grad).abs().max() <= 4 * (x0_pt.grad - x0_ref.grad).abs().max() + 1e-4
    if has_x1:
Tri Dao's avatar
Tri Dao committed
924
925
926
        assert (x1.grad - x1_ref.grad).abs().max() <= 4 * (
            x1_pt.grad - x1_ref.grad
        ).abs().max() + 1e-4
927
    if has_residual:
Tri Dao's avatar
Tri Dao committed
928
929
930
931
932
933
        assert (res.grad - res_ref.grad).abs().max() <= 4 * (
            res_pt.grad - res_ref.grad
        ).abs().max() + 1e-4
    assert (weight0.grad - weight0_ref.grad).abs().max() <= 3 * (
        weight0_pt.grad - weight0_ref.grad
    ).abs().max() + 3e-5
934
    if not is_rms_norm:
Tri Dao's avatar
Tri Dao committed
935
936
937
        assert (bias0.grad - bias0_ref.grad).abs().max() <= 2 * (
            bias0_pt.grad - bias0_ref.grad
        ).abs().max() + 3e-5
938
    if not tied_norm:
Tri Dao's avatar
Tri Dao committed
939
940
941
        assert (weight1.grad - weight1_ref.grad).abs().max() <= 3 * (
            weight1_pt.grad - weight1_ref.grad
        ).abs().max() + 3e-5
942
        if not is_rms_norm:
Tri Dao's avatar
Tri Dao committed
943
944
945
            assert (bias1.grad - bias1_ref.grad).abs().max() <= 2 * (
                bias1_pt.grad - bias1_ref.grad
            ).abs().max() + 3e-5
946
947


Tri Dao's avatar
Tri Dao committed
948
@pytest.mark.parametrize("is_rms_norm", [False, True])
949
# @pytest.mark.parametrize('is_rms_norm', [False])
Tri Dao's avatar
Tri Dao committed
950
@pytest.mark.parametrize("tied_norm", [False, True])
951
# @pytest.mark.parametrize('tied_norm', [False])
Tri Dao's avatar
Tri Dao committed
952
@pytest.mark.parametrize("has_residual", [True, False])
953
# @pytest.mark.parametrize('has_residual', [False])
Tri Dao's avatar
Tri Dao committed
954
@pytest.mark.parametrize("has_x1", [True, False])
955
# @pytest.mark.parametrize('has_x1', [True])
Tri Dao's avatar
Tri Dao committed
956
@pytest.mark.parametrize("dropout_p", [0.37, 0.0])
957
# @pytest.mark.parametrize('dropout_p', [0.0])
Tri Dao's avatar
Tri Dao committed
958
@pytest.mark.parametrize("weight_dtype", [torch.float32, torch.float16])
959
# @pytest.mark.parametrize('weight_dtype', [torch.float16])
Tri Dao's avatar
Tri Dao committed
960
961
962
963
964
@pytest.mark.parametrize(
    "input_dtype,residual_dtype",
    [(torch.float16, torch.float16), (torch.float16, torch.float32), (torch.float32, torch.float32)]
    + ([(torch.bfloat16, torch.bfloat16), (torch.bfloat16, torch.float32)] if is_sm8x else []),
)
965
# @pytest.mark.parametrize('input_dtype,residual_dtype', [(torch.float16, torch.float32)])
Tri Dao's avatar
Tri Dao committed
966
967
968
969
@pytest.mark.parametrize(
    "hidden_size",
    [192, 256, 384, 768, 1024, 1280, 1536, 1600, 2048, 2560, 3000, 3072, 4096, 5120, 6144],
)
970
971
# @pytest.mark.parametrize('hidden_size', [256])
def test_dropout_layer_norm_parallel_residual_prenorm_training(
Tri Dao's avatar
Tri Dao committed
972
973
974
975
976
977
978
979
980
    hidden_size,
    input_dtype,
    residual_dtype,
    weight_dtype,
    dropout_p,
    has_x1,
    has_residual,
    tied_norm,
    is_rms_norm,
981
982
983
984
985
):
    if weight_dtype == torch.float16 and input_dtype == torch.bfloat16:
        pytest.skip()  # Not supported
    if is_rms_norm and fused_rms_norm_affine is None:
        pytest.skip()  # We need Apex's FusedRMSNorm to test
Tri Dao's avatar
Tri Dao committed
986
987
988
989
990
991
    our_layer_norm_func = (
        dropout_add_layer_norm_parallel_residual
        if not is_rms_norm
        else dropout_add_rms_norm_parallel_residual
    )
    device = "cuda"
992
993
994
995
996
997
    # rtol, atol = (1e-5, 1e-6) if input_dtype == torch.float32 else (1e-3, 1e-4)
    rtol, atol = (1e-3, 1e-4)
    # set seed
    torch.random.manual_seed(0)
    batch_size = 8
    seqlen = 512
Tri Dao's avatar
Tri Dao committed
998
999
1000
    x0_pt = torch.randn(
        batch_size, seqlen, hidden_size, device=device, dtype=input_dtype, requires_grad=True
    )
1001
1002
1003
    x0 = x0_pt.detach().clone().requires_grad_()
    x0_ref = x0_pt.detach().clone().float().requires_grad_()
    if has_x1:
Tri Dao's avatar
Tri Dao committed
1004
1005
1006
        x1_pt = torch.randn(
            batch_size, seqlen, hidden_size, device=device, dtype=input_dtype, requires_grad=True
        )
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
        x1 = x1_pt.detach().clone().requires_grad_()
        x1_ref = x1_pt.detach().clone().float().requires_grad_()
    else:
        x1 = None
    if has_residual:
        res_pt = torch.randn_like(x0, dtype=residual_dtype, requires_grad=True)
        res = res_pt.detach().clone().requires_grad_()
        res_ref = res_pt.detach().clone().float().requires_grad_()
    else:
        res = None
    weight0 = torch.randn(hidden_size, device=device, dtype=weight_dtype, requires_grad=True)
Tri Dao's avatar
Tri Dao committed
1018
1019
1020
1021
1022
    bias0 = (
        torch.randn(hidden_size, device=device, dtype=weight_dtype, requires_grad=True)
        if not is_rms_norm
        else None
    )
1023
1024
1025
1026
1027
1028
    weight0_pt = weight0.detach().clone().requires_grad_()
    weight0_ref = weight0.detach().clone().float().requires_grad_()
    bias0_pt = bias0.detach().clone().requires_grad_() if bias0 is not None else None
    bias0_ref = bias0.detach().clone().float().requires_grad_() if bias0 is not None else None
    if not tied_norm:
        weight1 = torch.randn(hidden_size, device=device, dtype=weight_dtype, requires_grad=True)
Tri Dao's avatar
Tri Dao committed
1029
1030
1031
1032
1033
        bias1 = (
            torch.randn(hidden_size, device=device, dtype=weight_dtype, requires_grad=True)
            if not is_rms_norm
            else None
        )
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
        weight1_pt = weight1.detach().clone().requires_grad_()
        weight1_ref = weight1.detach().clone().float().requires_grad_()
        bias1_pt = bias1.detach().clone().requires_grad_() if bias1 is not None else None
        bias1_ref = bias1.detach().clone().float().requires_grad_() if bias1 is not None else None
    else:
        weight1, bias1 = None, None
    epsilon = 1e-5
    residual_in_fp32 = (not has_residual) and residual_dtype == torch.float32

    out0, out1, residual, dmask0, dmask1 = our_layer_norm_func(
Tri Dao's avatar
Tri Dao committed
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
        x0,
        x1,
        res,
        weight0,
        bias0,
        weight1,
        bias1,
        dropout_p,
        epsilon,
        prenorm=True,
        residual_in_fp32=residual_in_fp32,
        return_dropout_mask=True,
1056
1057
1058
1059
    )
    assert out0.dtype == input_dtype
    if not tied_norm:
        assert out1.dtype == input_dtype
Tri Dao's avatar
Tri Dao committed
1060
    print(f"Actual dropout fraction: {1 - dmask0.float().mean().item()}")
1061
1062
    if has_residual:
        if has_x1:
Tri Dao's avatar
Tri Dao committed
1063
1064
1065
1066
1067
1068
1069
1070
1071
            residual_pt = (
                (x0_pt.float() * dmask0.float()) / (1 - dropout_p)
                + (x1_pt.float() * dmask1.float()) / (1 - dropout_p)
                + res_pt.float()
            ).to(dtype=residual_dtype)
            residual_ref = (
                (x0_ref * dmask0.float()) / (1 - dropout_p)
                + (x1_ref * dmask1.float()) / (1 - dropout_p)
            ) + res_ref
1072
        else:
Tri Dao's avatar
Tri Dao committed
1073
1074
1075
            residual_pt = ((x0_pt.float() * dmask0.float()) / (1 - dropout_p) + res_pt.float()).to(
                dtype=residual_dtype
            )
1076
1077
1078
            residual_ref = (x0_ref * dmask0.float()) / (1 - dropout_p) + res_ref
    else:
        if has_x1:
Tri Dao's avatar
Tri Dao committed
1079
1080
1081
1082
1083
1084
1085
            residual_pt = (
                (x0_pt.float() * dmask0.float()) / (1 - dropout_p)
                + (x1_pt.float() * dmask1.float()) / (1 - dropout_p)
            ).to(dtype=residual_dtype)
            residual_ref = (x0_ref * dmask0.float()) / (1 - dropout_p) + (
                x1_ref * dmask1.float()
            ) / (1 - dropout_p)
1086
        else:
Tri Dao's avatar
Tri Dao committed
1087
1088
1089
            residual_pt = ((x0_pt.float() * dmask0.float()) / (1 - dropout_p)).to(
                dtype=residual_dtype
            )
1090
1091
            residual_ref = (x0_ref * dmask0.float()) / (1 - dropout_p)
    if not is_rms_norm:
Tri Dao's avatar
Tri Dao committed
1092
1093
1094
        out0_pt = F.layer_norm(
            residual_pt.to(dtype=weight_dtype), (hidden_size,), weight0_pt, bias0_pt, eps=epsilon
        ).to(dtype=input_dtype)
1095
1096
        out0_ref = F.layer_norm(residual_ref, (hidden_size,), weight0_ref, bias0_ref, eps=epsilon)
        if not tied_norm:
Tri Dao's avatar
Tri Dao committed
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
            out1_pt = F.layer_norm(
                residual_pt.to(dtype=weight_dtype),
                (hidden_size,),
                weight1_pt,
                bias1_pt,
                eps=epsilon,
            ).to(dtype=input_dtype)
            out1_ref = F.layer_norm(
                residual_ref, (hidden_size,), weight1_ref, bias1_ref, eps=epsilon
            )
1107
    else:
Tri Dao's avatar
Tri Dao committed
1108
1109
1110
        out0_pt = fused_rms_norm_affine(
            residual_pt.to(dtype=weight_dtype), weight0_pt, (hidden_size,), eps=epsilon
        ).to(dtype=input_dtype)
1111
1112
        out0_ref = fused_rms_norm_affine(residual_ref, weight0_ref, (hidden_size,), eps=epsilon)
        if not tied_norm:
Tri Dao's avatar
Tri Dao committed
1113
1114
1115
            out1_pt = fused_rms_norm_affine(
                residual_pt.to(dtype=weight_dtype), weight1_pt, (hidden_size,), eps=epsilon
            ).to(dtype=input_dtype)
1116
1117
1118
1119
1120
            out1_ref = fused_rms_norm_affine(residual_ref, weight1_ref, (hidden_size,), eps=epsilon)

    assert (out0 - out0_ref).abs().max() <= 4 * (out0_pt - out0_ref).abs().max() + 1e-4
    if not tied_norm:
        assert (out1 - out1_ref).abs().max() <= 4 * (out1_pt - out1_ref).abs().max() + 1e-4
Tri Dao's avatar
Tri Dao committed
1121
1122
1123
    assert (residual - residual_ref).abs().max() <= 4 * (
        residual_pt - residual_ref
    ).abs().max() + 1e-4
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136

    g0 = torch.randn_like(out0) / batch_size
    if tied_norm:
        (out0 * F.sigmoid(residual)).backward(g0)
        (out0_pt * F.sigmoid(residual_pt)).backward(g0)
        (out0_ref * F.sigmoid(residual_ref)).backward(g0)
    else:
        g1 = torch.randn_like(out1) / batch_size
        (out0 * F.sigmoid(residual) * g0 + out1 * g1).sum().backward()
        (out0_pt * F.sigmoid(residual_pt) * g0 + out1_pt * g1).sum().backward()
        (out0_ref * F.sigmoid(residual_ref) * g0 + out1_ref * g1).sum().backward()
    assert (x0.grad - x0_ref.grad).abs().max() <= 4 * (x0_pt.grad - x0_ref.grad).abs().max() + 1e-4
    if has_x1:
Tri Dao's avatar
Tri Dao committed
1137
1138
1139
        assert (x1.grad - x1_ref.grad).abs().max() <= 4 * (
            x1_pt.grad - x1_ref.grad
        ).abs().max() + 1e-4
1140
    if has_residual:
Tri Dao's avatar
Tri Dao committed
1141
1142
1143
1144
1145
1146
        assert (res.grad - res_ref.grad).abs().max() <= 4 * (
            res_pt.grad - res_ref.grad
        ).abs().max() + 1e-4
    assert (weight0.grad - weight0_ref.grad).abs().max() <= 3 * (
        weight0_pt.grad - weight0_ref.grad
    ).abs().max() + 3e-5
1147
    if not is_rms_norm:
Tri Dao's avatar
Tri Dao committed
1148
1149
1150
        assert (bias0.grad - bias0_ref.grad).abs().max() <= 2 * (
            bias0_pt.grad - bias0_ref.grad
        ).abs().max() + 3e-5
1151
    if not tied_norm:
Tri Dao's avatar
Tri Dao committed
1152
1153
1154
        assert (weight1.grad - weight1_ref.grad).abs().max() <= 3 * (
            weight1_pt.grad - weight1_ref.grad
        ).abs().max() + 3e-5
1155
        if not is_rms_norm:
Tri Dao's avatar
Tri Dao committed
1156
1157
1158
            assert (bias1.grad - bias1_ref.grad).abs().max() <= 2 * (
                bias1_pt.grad - bias1_ref.grad
            ).abs().max() + 3e-5
Tri Dao's avatar
Tri Dao committed
1159
1160
1161
1162
1163
1164


def test_dropout_layer_norm_randomness():
    hidden_size = 256
    dtype = torch.float32
    dropout_p = 0.1
Tri Dao's avatar
Tri Dao committed
1165
    device = "cuda"
Tri Dao's avatar
Tri Dao committed
1166
1167
1168
1169
    # set seed
    torch.random.manual_seed(0)
    batch_size = 8
    seqlen = 512
Tri Dao's avatar
Tri Dao committed
1170
1171
1172
    x0 = torch.randn(
        batch_size, seqlen, hidden_size, device=device, dtype=dtype, requires_grad=True
    )
Tri Dao's avatar
Tri Dao committed
1173
1174
1175
    res = torch.randn_like(x0, dtype=dtype, requires_grad=True)
    model = DropoutAddLayerNorm(hidden_size, p=dropout_p, device=device, dtype=dtype)
    torch.random.manual_seed(42)
Tri Dao's avatar
Tri Dao committed
1176
1177
1178
    _, dmask0 = dropout_add_layer_norm(
        x0, res, model.weight, model.bias, model.p, model.eps, return_dropout_mask=True
    )
Tri Dao's avatar
Tri Dao committed
1179
    # Subsequent call should have a different dropout mask
Tri Dao's avatar
Tri Dao committed
1180
1181
1182
    _, dmask1 = dropout_add_layer_norm(
        x0, res, model.weight, model.bias, model.p, model.eps, return_dropout_mask=True
    )
Tri Dao's avatar
Tri Dao committed
1183
1184
    torch.random.manual_seed(42)
    # Resetting the seed, should get the same dropout mask
Tri Dao's avatar
Tri Dao committed
1185
1186
1187
    _, dmask2 = dropout_add_layer_norm(
        x0, res, model.weight, model.bias, model.p, model.eps, return_dropout_mask=True
    )
Tri Dao's avatar
Tri Dao committed
1188
1189
    assert not torch.equal(dmask0, dmask1)
    assert torch.equal(dmask0, dmask2)