Elffuss BraidHub

kikocis/llama-stack public

7b7b9b1ba243 · 2.6 KiBRawPermalink
1# Copyright (c) Meta Platforms, Inc. and affiliates.
2# All rights reserved.
3#
4# This source code is licensed under the terms described in the LICENSE file in
5# the root directory of this source tree.
6
7# Copyright (c) Meta Platforms, Inc. and affiliates.
8# This software may be used and distributed in accordance with the terms of the Llama 3 Community License Agreement.
9
10import unittest
11
12import torch
13
14from fp8_impls import ffn_swiglu_fp8_dynamic, FfnQuantizeMode, quantize_fp8
15from hypothesis import given, settings, strategies as st
16from torch import Tensor
17
18
19@unittest.skipIf(
20 not torch.cuda.is_available()
21 or torch.cuda.get_device_properties(torch.cuda.current_device()).major < 9,
22 "Skip when H100 is not available",
23)
24class FP8Tests(unittest.TestCase):
25 @settings(deadline=None)
26 @given(
27 D=st.sampled_from([4096, 8192]),
28 HD_L=st.sampled_from([1280, 2560]),
29 B=st.sampled_from([1, 2]),
30 T=st.sampled_from([2048, 4096]),
31 UB=st.sampled_from([1000, 10000]),
32 )
33 def test_fp8_ffn(
34 self,
35 D: int, # noqa
36 HD_L: int,
37 B: int,
38 T: int,
39 UB: float,
40 ) -> None:
41 x = torch.randn(size=(B, T, D), dtype=torch.bfloat16, device="cuda") * 0.1
42 w1 = torch.randn(size=(HD_L, D), dtype=torch.bfloat16, device="cuda") * 0.01
43 w3 = torch.randn(size=(HD_L, D), dtype=torch.bfloat16, device="cuda") * 0.01
44 w2 = torch.randn(size=(D, HD_L), dtype=torch.bfloat16, device="cuda") * 0.1
45
46 x_q = quantize_fp8(x, UB, mode=FfnQuantizeMode.FP8_ROWWISE)
47 w1_q = quantize_fp8(w1, UB, mode=FfnQuantizeMode.FP8_ROWWISE)
48 w3_q = quantize_fp8(w3, UB, mode=FfnQuantizeMode.FP8_ROWWISE)
49 w2_q = quantize_fp8(w2, UB, mode=FfnQuantizeMode.FP8_ROWWISE)
50
51 def ref_ffn(x: Tensor, w1: Tensor, w3: Tensor, w2: Tensor) -> Tensor:
52 (B, T, D) = x.shape # noqa: N806
53 (HD_L, D_) = w1.shape # noqa: N806
54 assert D_ == D
55
56 x1 = x.view(B * T, D) @ w1.T
57 x2 = x.view(B * T, D) @ w3.T
58
59 z = torch.nn.functional.silu(x1) * x2
60 return (z @ w2.T).view(B, T, D).to(torch.bfloat16)
61
62 v = ffn_swiglu_fp8_dynamic(x, w1_q, w3_q, w2_q)
63
64 # Fake quant
65 x = x_q.weight.bfloat16() * x_q.scale.unsqueeze(-1)
66 w1 = w1_q.weight.bfloat16() * w1_q.scale.unsqueeze(-1)
67 w3 = w3_q.weight.bfloat16() * w3_q.scale.unsqueeze(-1)
68 w2 = w2_q.weight.bfloat16() * w2_q.scale.unsqueeze(-1)
69
70 v_ref = ref_ffn(x, w1, w3, w2)
71
72 torch.testing.assert_close(v_ref, v, atol=4.0e-3, rtol=4.0e-3)
73
74
75if __name__ == "__main__":
76 unittest.main()