Buckets:
| """Short real-GPU correctness/backward checks for the production FlashAttention path.""" | |
| import math | |
| import torch | |
| from flash_attn import flash_attn_func | |
| from .attention import reference_attention, segmented_flash_attention, update_rolling_state | |
| def clone(xs): | |
| return [x.detach().clone().requires_grad_() for x in xs] | |
| def check_length(length): | |
| torch.manual_seed(100 + length) | |
| xs = [torch.randn(length, 1, heads, 64, device="cuda", dtype=torch.float16) | |
| for heads in (8, 4, 4, 4, 4)] | |
| actual_inputs = clone(xs) | |
| reference_inputs = clone(xs) | |
| actual = segmented_flash_attention(*actual_inputs) | |
| expected = reference_attention(*reference_inputs) | |
| torch.testing.assert_close(actual, expected, atol=1.2e-2, rtol=1.2e-2) | |
| weight = torch.randn_like(actual) | |
| ga = torch.autograd.grad((actual * weight).sum(), actual_inputs, allow_unused=True) | |
| ge = torch.autograd.grad((expected * weight).sum(), reference_inputs) | |
| for a, e in zip(ga, ge): | |
| if a is None: | |
| a = torch.zeros_like(e) | |
| torch.testing.assert_close(a, e, atol=8e-2, rtol=8e-2) | |
| assert torch.isfinite(a).all() | |
| def check_r64_full_equivalence(): | |
| torch.manual_seed(64) | |
| xs = [torch.randn(137, 1, heads, 64, device="cuda", dtype=torch.float16) | |
| for heads in (8, 4, 4)] | |
| split_inputs = clone(xs) | |
| full_inputs = clone(xs) | |
| split = segmented_flash_attention(split_inputs[0], split_inputs[1], split_inputs[2], | |
| update_rolling_state(None, split_inputs[1], 64), | |
| update_rolling_state(None, split_inputs[2], 64)) | |
| q, k, v = (x.permute(1, 0, 2, 3).contiguous() for x in full_inputs) | |
| full = flash_attn_func(q, k, v, dropout_p=0.0, softmax_scale=1 / math.sqrt(64), | |
| causal=True).permute(1, 0, 2, 3) | |
| torch.testing.assert_close(split, full, atol=1.2e-2, rtol=1.2e-2) | |
| weight = torch.randn_like(split) | |
| ga = torch.autograd.grad((split * weight).sum(), split_inputs) | |
| gb = torch.autograd.grad((full * weight).sum(), full_inputs) | |
| for a, b in zip(ga, gb): | |
| relative_l2 = (a.float() - b.float()).norm() / b.float().norm().clamp_min(1e-12) | |
| cosine = torch.nn.functional.cosine_similarity(a.float().flatten(), b.float().flatten(), dim=0) | |
| assert relative_l2 < 0.02 and cosine > 0.999, (relative_l2.item(), cosine.item()) | |
| if __name__ == "__main__": | |
| for length in (127, 128, 129, 130): check_length(length) | |
| check_r64_full_equivalence() | |
| print("PASS: GPU segmented FlashAttention forward/backward and r64 full-GQA equivalence") | |
Xet Storage Details
- Size:
- 2.62 kB
- Xet hash:
- 270568d4d66c5f3b9567588853f470752c45b9a546fa1dd256810303da15dd5d
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.