| 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 | |
| 10 | import collections |
| 11 | from typing import Optional, Type |
| 12 | |
| 13 | try: |
| 14 | import fbgemm_gpu.experimental.gen_ai # noqa: F401 |
| 15 | |
| 16 | print("Using efficient FP8 operators in FBGEMM.") |
| 17 | except ImportError: |
| 18 | print("No efficient FP8 operators. Please install FBGEMM in fp8_requirements.txt.") |
| 19 | raise |
| 20 | |
| 21 | import torch |
| 22 | from torch import nn, Tensor |
| 23 | |
| 24 | |
| 25 | class Fp8ScaledWeights: |
| 26 | # TODO: Ugly trick so torch allows us to replace parameters |
| 27 | # with our custom Fp8Weights instance. Do this properly. |
| 28 | @property |
| 29 | def __class__(self) -> Type[nn.parameter.Parameter]: |
| 30 | return nn.Parameter |
| 31 | |
| 32 | @property |
| 33 | def grad_fn(self) -> None: |
| 34 | return None |
| 35 | |
| 36 | |
| 37 | # pyre-fixme[4]: Attribute annotation cannot be `Any`. |
| 38 | # pyre-fixme[2]: Parameter annotation cannot be `Any`. |
| 39 | class Fp8RowwiseWeights( |
| 40 | Fp8ScaledWeights, |
| 41 | collections.namedtuple( |
| 42 | "Fp8RowwiseWeights", |
| 43 | ["weight", "scale", "shape", "activation_scale_ub"], |
| 44 | ), |
| 45 | ): |
| 46 | pass |
| 47 | |
| 48 | |
| 49 | def ffn_swiglu( |
| 50 | x: Tensor, |
| 51 | w1: Fp8RowwiseWeights, |
| 52 | w3: Fp8RowwiseWeights, |
| 53 | w2: Fp8RowwiseWeights, |
| 54 | num_tokens: Optional[Tensor] = None, |
| 55 | is_memory_bounded: bool = False, |
| 56 | ) -> Tensor: |
| 57 | if ( |
| 58 | isinstance(w1, Fp8ScaledWeights) |
| 59 | and isinstance(w3, Fp8ScaledWeights) |
| 60 | and isinstance(w2, Fp8ScaledWeights) |
| 61 | ): |
| 62 | return ffn_swiglu_fp8_dynamic( |
| 63 | x, w1, w3, w2, w1.activation_scale_ub, num_tokens, is_memory_bounded |
| 64 | ) |
| 65 | |
| 66 | (B, T, D) = x.shape # noqa: N806 |
| 67 | (HD_L, D_) = w1.shape # noqa: N806 |
| 68 | assert D_ == D |
| 69 | |
| 70 | assert isinstance(w1, Tensor) |
| 71 | assert isinstance(w3, Tensor) |
| 72 | x1 = x.view(B * T, D) @ w1.T |
| 73 | x2 = x.view(B * T, D) @ w3.T |
| 74 | z = torch.nn.functional.silu(x1) * x2 |
| 75 | del x1, x2 |
| 76 | assert isinstance(w2, Tensor) |
| 77 | return (z @ w2.T).view(B, T, D) |
| 78 | |
| 79 | |
| 80 | @torch.inference_mode() |
| 81 | def quantize_fp8( |
| 82 | w: Tensor, |
| 83 | fp8_activation_scale_ub: float, |
| 84 | output_device: Optional[torch.device] = None, |
| 85 | ) -> Fp8RowwiseWeights: |
| 86 | """Quantize [n, k] weight tensor. |
| 87 | |
| 88 | Args: |
| 89 | w (Tensor): [n, k] input high precision tensor to quantize. |
| 90 | fp8_activation_scale_ub (float): Upper bound for activation max. |
| 91 | """ |
| 92 | activation_scale_ub = torch.tensor( |
| 93 | [fp8_activation_scale_ub], |
| 94 | dtype=torch.float, |
| 95 | device="cuda", |
| 96 | ) |
| 97 | wq, w_scale = torch.ops.fbgemm.quantize_fp8_per_row(w) |
| 98 | del w |
| 99 | return Fp8RowwiseWeights( |
| 100 | weight=wq, |
| 101 | scale=w_scale, |
| 102 | shape=wq.shape, |
| 103 | activation_scale_ub=activation_scale_ub, |
| 104 | ) |
| 105 | |
| 106 | |
| 107 | @torch.inference_mode() |
| 108 | def load_fp8( |
| 109 | w: Tensor, |
| 110 | w_scale: Tensor, |
| 111 | fp8_activation_scale_ub: float, |
| 112 | ) -> Fp8RowwiseWeights: |
| 113 | """Load FP8 [n, k] weight tensor. |
| 114 | |
| 115 | Args: |
| 116 | w (Tensor): [n, k] input FP8. |
| 117 | fp8_activation_scale_ub (float): Upper bound for activation max. |
| 118 | """ |
| 119 | activation_scale_ub = torch.tensor( |
| 120 | [fp8_activation_scale_ub], |
| 121 | dtype=torch.float, |
| 122 | device="cuda", |
| 123 | ) |
| 124 | return Fp8RowwiseWeights( |
| 125 | weight=w.to(torch.float8_e4m3fn).to(device="cuda"), |
| 126 | scale=w_scale.to(device="cuda"), |
| 127 | shape=w.shape, |
| 128 | activation_scale_ub=activation_scale_ub, |
| 129 | ) |
| 130 | |
| 131 | |
| 132 | def fc_fp8_dynamic( |
| 133 | x: Tensor, |
| 134 | w: Fp8RowwiseWeights, |
| 135 | activation_scale_ub: Optional[Tensor] = None, |
| 136 | num_tokens: Optional[Tensor] = None, |
| 137 | is_memory_bounded: bool = False, |
| 138 | ) -> Tensor: |
| 139 | """ |
| 140 | Single w8a8 fc layer with dynamic row-wise scaling. |
| 141 | """ |
| 142 | if isinstance(w, Fp8RowwiseWeights): |
| 143 | xq, x_scale = torch.ops.fbgemm.quantize_fp8_per_row( |
| 144 | x, num_tokens, activation_scale_ub |
| 145 | ) |
| 146 | y = torch.ops.fbgemm.f8f8bf16_rowwise( |
| 147 | xq, w.weight, x_scale, w.scale, use_fast_accum=True |
| 148 | ) |
| 149 | del xq |
| 150 | return y |
| 151 | |
| 152 | |
| 153 | def ffn_swiglu_fp8_dynamic( |
| 154 | x: Tensor, |
| 155 | w1: Fp8RowwiseWeights, |
| 156 | w3: Fp8RowwiseWeights, |
| 157 | w2: Fp8RowwiseWeights, |
| 158 | activation_scale_ub: Optional[Tensor] = None, |
| 159 | num_tokens: Optional[Tensor] = None, |
| 160 | is_memory_bounded: bool = False, |
| 161 | ) -> Tensor: |
| 162 | (B, T, D) = x.shape # noqa: N806 |
| 163 | HD_L = w1.shape[0] # noqa: N806 |
| 164 | assert HD_L == w3.shape[0] |
| 165 | x1 = fc_fp8_dynamic( |
| 166 | x.view(B * T, D), |
| 167 | w1, |
| 168 | activation_scale_ub, |
| 169 | num_tokens, |
| 170 | is_memory_bounded, |
| 171 | ) |
| 172 | x2 = fc_fp8_dynamic( |
| 173 | x.view(B * T, D), |
| 174 | w3, |
| 175 | activation_scale_ub, |
| 176 | num_tokens, |
| 177 | is_memory_bounded, |
| 178 | ) |
| 179 | z = torch.nn.functional.silu(x1) * x2 |
| 180 | del x1, x2 |
| 181 | |
| 182 | z_ = fc_fp8_dynamic(z, w2, activation_scale_ub, num_tokens, is_memory_bounded) |
| 183 | |
| 184 | return z_.view(B, T, D) |