|
| 1 | +# Copyright (c) Meta Platforms, Inc. and affiliates. |
| 2 | +# All rights reserved. |
| 3 | +# |
| 4 | +# This source code is licensed under the BSD 3-Clause license found in the |
| 5 | +# LICENSE file in the root directory of this source tree. |
| 6 | + |
| 7 | +"""Tests for FP8 low-precision attention (FA3 backend on Hopper).""" |
| 8 | + |
| 9 | +import unittest |
| 10 | + |
| 11 | +import torch |
| 12 | +import torch.nn as nn |
| 13 | +import torch.nn.functional as F |
| 14 | +from torch.testing._internal import common_utils |
| 15 | +from torch.testing._internal.common_utils import TestCase, run_tests |
| 16 | + |
| 17 | +from torchao.quantization.utils import compute_error |
| 18 | +from torchao.utils import torch_version_at_least |
| 19 | + |
| 20 | +if torch_version_at_least("2.11.0"): |
| 21 | + from torchao.prototype.attention.utils import _is_fa3_available, _is_hopper |
| 22 | + |
| 23 | + if _is_hopper() and _is_fa3_available(): |
| 24 | + from torch.nn.attention import ( |
| 25 | + activate_flash_attention_impl, |
| 26 | + restore_flash_attention_impl, |
| 27 | + ) |
| 28 | + |
| 29 | + from torchao.prototype.attention import ( |
| 30 | + AttentionBackend, |
| 31 | + apply_low_precision_attention, |
| 32 | + ) |
| 33 | + from torchao.prototype.attention.fp8_fa3.attention import fp8_fa3_sdpa |
| 34 | + |
| 35 | + |
| 36 | +class SimpleAttentionModel(nn.Module): |
| 37 | + def __init__(self, embed_dim, num_heads): |
| 38 | + super().__init__() |
| 39 | + self.num_heads = num_heads |
| 40 | + self.head_dim = embed_dim // num_heads |
| 41 | + self.q_proj = nn.Linear(embed_dim, embed_dim, bias=False) |
| 42 | + self.k_proj = nn.Linear(embed_dim, embed_dim, bias=False) |
| 43 | + self.v_proj = nn.Linear(embed_dim, embed_dim, bias=False) |
| 44 | + self.out_proj = nn.Linear(embed_dim, embed_dim, bias=False) |
| 45 | + |
| 46 | + def forward(self, x): |
| 47 | + B, S, _ = x.shape |
| 48 | + q = self.q_proj(x).view(B, S, self.num_heads, self.head_dim).transpose(1, 2) |
| 49 | + k = self.k_proj(x).view(B, S, self.num_heads, self.head_dim).transpose(1, 2) |
| 50 | + v = self.v_proj(x).view(B, S, self.num_heads, self.head_dim).transpose(1, 2) |
| 51 | + attn_out = F.scaled_dot_product_attention(q, k, v, is_causal=True) |
| 52 | + return self.out_proj(attn_out.transpose(1, 2).contiguous().view(B, S, -1)) |
| 53 | + |
| 54 | + |
| 55 | +@common_utils.instantiate_parametrized_tests |
| 56 | +class TestFP8FA3Attention(TestCase): |
| 57 | + @unittest.skipUnless( |
| 58 | + torch_version_at_least("2.11.0") and _is_hopper() and _is_fa3_available(), |
| 59 | + "Requires PyTorch >= 2.11, Hopper GPU, and FA3", |
| 60 | + ) |
| 61 | + @common_utils.parametrize("shape", [(2, 8, 1024, 64), (1, 16, 1024, 128)]) |
| 62 | + @common_utils.parametrize("dtype", [torch.bfloat16, torch.float16]) |
| 63 | + def test_sdpa_accuracy(self, shape, dtype): |
| 64 | + B, H, S, D = shape |
| 65 | + q = torch.randn(B, H, S, D, device="cuda", dtype=dtype) |
| 66 | + k = torch.randn(B, H, S, D, device="cuda", dtype=dtype) |
| 67 | + v = torch.randn(B, H, S, D, device="cuda", dtype=dtype) |
| 68 | + |
| 69 | + with torch.no_grad(): |
| 70 | + out_ref = F.scaled_dot_product_attention(q, k, v, is_causal=False) |
| 71 | + |
| 72 | + activate_flash_attention_impl("FA3") |
| 73 | + try: |
| 74 | + with torch.no_grad(): |
| 75 | + out_fp8 = fp8_fa3_sdpa(q, k, v, is_causal=False) |
| 76 | + finally: |
| 77 | + restore_flash_attention_impl() |
| 78 | + |
| 79 | + sqnr = compute_error(out_ref, out_fp8) |
| 80 | + self.assertGreater( |
| 81 | + sqnr.item(), |
| 82 | + 25.0, |
| 83 | + f"SQNR {sqnr.item():.2f} dB below 25 dB for shape={shape}, dtype={dtype}", |
| 84 | + ) |
| 85 | + |
| 86 | + @unittest.skipUnless( |
| 87 | + torch_version_at_least("2.11.0") and _is_hopper() and _is_fa3_available(), |
| 88 | + "Requires PyTorch >= 2.11, Hopper GPU, and FA3", |
| 89 | + ) |
| 90 | + @common_utils.parametrize("dtype", [torch.bfloat16, torch.float16]) |
| 91 | + def test_monkey_patch_model(self, dtype): |
| 92 | + embed_dim, num_heads = 512, 8 |
| 93 | + model = ( |
| 94 | + SimpleAttentionModel(embed_dim, num_heads) |
| 95 | + .to(device="cuda", dtype=dtype) |
| 96 | + .eval() |
| 97 | + ) |
| 98 | + x = torch.randn(2, 128, embed_dim, device="cuda", dtype=dtype) |
| 99 | + |
| 100 | + with torch.no_grad(): |
| 101 | + out_ref = model(x) |
| 102 | + |
| 103 | + fp8_model = ( |
| 104 | + SimpleAttentionModel(embed_dim, num_heads) |
| 105 | + .to(device="cuda", dtype=dtype) |
| 106 | + .eval() |
| 107 | + ) |
| 108 | + fp8_model.load_state_dict(model.state_dict()) |
| 109 | + fp8_model = apply_low_precision_attention( |
| 110 | + fp8_model, |
| 111 | + backend=AttentionBackend.FP8_FA3, |
| 112 | + fuse_rope_using_torch_compile=False, |
| 113 | + ) |
| 114 | + |
| 115 | + with torch.no_grad(): |
| 116 | + out_fp8 = fp8_model(x) |
| 117 | + |
| 118 | + sqnr = compute_error(out_ref, out_fp8) |
| 119 | + self.assertGreater( |
| 120 | + sqnr.item(), |
| 121 | + 20.0, |
| 122 | + f"SQNR {sqnr.item():.2f} dB below 20 dB for dtype={dtype}", |
| 123 | + ) |
| 124 | + |
| 125 | + |
| 126 | +if __name__ == "__main__": |
| 127 | + run_tests() |
0 commit comments