|
| 1 | +# Copyright (c) Meta Platforms, Inc. and affiliates. |
| 2 | +# All rights reserved. |
| 3 | +# |
| 4 | +# This source code is licensed under the BSD-style license found in the |
| 5 | +# LICENSE file in the root directory of this source tree. |
| 6 | + |
| 7 | +"""Nibble-packed W4/BF16 weights for the AOTI Triton matmul path.""" |
| 8 | + |
| 9 | +import torch |
| 10 | +import torch.nn as nn |
| 11 | +from executorch.backends.cuda.triton.kernels.int4_matmul import ( |
| 12 | + int4_matmul, |
| 13 | + int4_matvec_bf16, |
| 14 | +) |
| 15 | +from torchao.utils import TorchAOBaseTensor |
| 16 | + |
| 17 | + |
| 18 | +class AotiPackedInt4Tensor(TorchAOBaseTensor): |
| 19 | + """Symmetric groupwise INT4 weight consumed by AOTI Triton kernels. |
| 20 | +
|
| 21 | + Linears use ``triton::int4_matmul`` by default; the opt-in fixed-shape path |
| 22 | + uses ``triton::int4_matvec_bf16``. |
| 23 | + """ |
| 24 | + |
| 25 | + tensor_data_names = ["qdata", "scale"] |
| 26 | + tensor_attribute_names = ["group_size", "orig_dtype", "use_matvec"] |
| 27 | + |
| 28 | + def __new__(cls, qdata, scale, group_size, orig_dtype, use_matvec=False): |
| 29 | + shape = (qdata.shape[0], qdata.shape[1] * 2) |
| 30 | + self = torch.Tensor._make_wrapper_subclass( |
| 31 | + cls, |
| 32 | + shape, |
| 33 | + dtype=orig_dtype, |
| 34 | + device=qdata.device, |
| 35 | + requires_grad=False, |
| 36 | + ) |
| 37 | + self.qdata = qdata |
| 38 | + self.scale = scale |
| 39 | + self.group_size = group_size |
| 40 | + self.orig_dtype = orig_dtype |
| 41 | + self.use_matvec = use_matvec |
| 42 | + return self |
| 43 | + |
| 44 | + @classmethod |
| 45 | + def from_intx_unpacked_to_int8_tensor( |
| 46 | + cls, weight: torch.Tensor, use_matvec: bool = False |
| 47 | + ) -> "AotiPackedInt4Tensor": |
| 48 | + from torchao.quantization import IntxUnpackedToInt8Tensor |
| 49 | + |
| 50 | + if not isinstance(weight, IntxUnpackedToInt8Tensor): |
| 51 | + raise TypeError( |
| 52 | + "AotiPackedInt4Tensor requires IntxUnpackedToInt8Tensor, got " |
| 53 | + f"{type(weight).__name__}" |
| 54 | + ) |
| 55 | + if weight.target_dtype != torch.int4: |
| 56 | + raise ValueError("AotiPackedInt4Tensor requires target_dtype=torch.int4") |
| 57 | + if weight.activation_quantization is not None: |
| 58 | + raise ValueError("AotiPackedInt4Tensor only supports weight-only INT4") |
| 59 | + if weight.dtype != torch.bfloat16: |
| 60 | + raise ValueError("AotiPackedInt4Tensor requires BF16 activations") |
| 61 | + if weight.qdata.ndim != 2 or weight.block_size[0] != 1: |
| 62 | + raise ValueError("AotiPackedInt4Tensor requires 2D groupwise weights") |
| 63 | + if torch.count_nonzero(weight.zero_point).item() != 0: |
| 64 | + raise ValueError("AotiPackedInt4Tensor requires symmetric zero points") |
| 65 | + group_size = int(weight.block_size[-1]) |
| 66 | + rows, columns = weight.qdata.shape |
| 67 | + if columns % 2 != 0 or columns % group_size != 0: |
| 68 | + raise ValueError( |
| 69 | + "AotiPackedInt4Tensor requires the input dimension to be " |
| 70 | + "divisible by two and the group size" |
| 71 | + ) |
| 72 | + if weight.scale.shape != (rows, columns // group_size): |
| 73 | + raise ValueError("AotiPackedInt4Tensor received incompatible scales") |
| 74 | + |
| 75 | + qdata = (weight.qdata + 8).to(torch.uint8) |
| 76 | + qdata = (qdata[..., ::2] | (qdata[..., 1::2] << 4)).to(torch.int8) |
| 77 | + return cls( |
| 78 | + qdata.contiguous(), |
| 79 | + weight.scale.contiguous(), |
| 80 | + group_size, |
| 81 | + weight.dtype, |
| 82 | + use_matvec, |
| 83 | + ) |
| 84 | + |
| 85 | + def dequantize(self, output_dtype=None): |
| 86 | + dtype = output_dtype or self.orig_dtype |
| 87 | + packed = self.qdata.to(torch.uint8) |
| 88 | + low = (packed & 0x0F).to(torch.float32) - 8.0 |
| 89 | + high = ((packed >> 4) & 0x0F).to(torch.float32) - 8.0 |
| 90 | + values = torch.stack([low, high], dim=-1).reshape(self.shape) |
| 91 | + scale = self.scale.float().repeat_interleave(self.group_size, dim=-1) |
| 92 | + return (values * scale).to(dtype) |
| 93 | + |
| 94 | + def to(self, *args, **kwargs): |
| 95 | + kwargs = self._get_to_kwargs(*args, **kwargs) |
| 96 | + device = kwargs.pop("device") |
| 97 | + dtype = kwargs.pop("dtype") |
| 98 | + if dtype != torch.bfloat16: |
| 99 | + raise ValueError("AotiPackedInt4Tensor requires BF16 activations") |
| 100 | + return AotiPackedInt4Tensor( |
| 101 | + self.qdata.to(device), |
| 102 | + self.scale.to(device=device, dtype=dtype), |
| 103 | + self.group_size, |
| 104 | + dtype, |
| 105 | + self.use_matvec, |
| 106 | + ) |
| 107 | + |
| 108 | + __torch_function__ = torch._C._disabled_torch_function_impl |
| 109 | + |
| 110 | + |
| 111 | +implements = AotiPackedInt4Tensor.implements |
| 112 | + |
| 113 | + |
| 114 | +@implements([torch.ops.aten.linear.default]) |
| 115 | +def _(func, types, args, kwargs): |
| 116 | + input_tensor, weight = args[0], args[1] |
| 117 | + bias = args[2] if len(args) > 2 else None |
| 118 | + input_shape = input_tensor.shape |
| 119 | + input_2d = input_tensor.reshape(-1, input_shape[-1]) |
| 120 | + rows = input_2d.shape[0] |
| 121 | + if isinstance(rows, int) and rows == 1 and weight.use_matvec: |
| 122 | + output = int4_matvec_bf16( |
| 123 | + input_2d, |
| 124 | + weight.qdata, |
| 125 | + weight.scale, |
| 126 | + weight.group_size, |
| 127 | + ) |
| 128 | + else: |
| 129 | + output = int4_matmul( |
| 130 | + input_2d, |
| 131 | + weight.qdata, |
| 132 | + weight.scale, |
| 133 | + weight.group_size, |
| 134 | + ) |
| 135 | + output = output.reshape(*input_shape[:-1], weight.shape[0]) |
| 136 | + return output if bias is None else output + bias |
| 137 | + |
| 138 | + |
| 139 | +@implements([torch.ops.aten.detach.default, torch.ops.aten.alias.default]) |
| 140 | +def _(func, types, args, kwargs): |
| 141 | + return args[0] |
| 142 | + |
| 143 | + |
| 144 | +@implements([torch.ops.aten.t.default]) |
| 145 | +def _(func, types, args, kwargs): |
| 146 | + return args[0].dequantize().t() |
| 147 | + |
| 148 | + |
| 149 | +@implements([torch.ops.aten._to_copy.default]) |
| 150 | +def _(func, types, args, kwargs): |
| 151 | + return args[0].to(**kwargs) |
| 152 | + |
| 153 | + |
| 154 | +def pack_int4_weights_for_aoti(module: nn.Module, *, use_matvec: bool = False) -> int: |
| 155 | + """Pack symmetric TorchAO INT4 linear weights in ``module`` in place.""" |
| 156 | + from torchao.quantization import IntxUnpackedToInt8Tensor |
| 157 | + |
| 158 | + packed = 0 |
| 159 | + for child in module.modules(): |
| 160 | + if not isinstance(child, nn.Linear): |
| 161 | + continue |
| 162 | + weight = child.weight |
| 163 | + if not isinstance(weight, IntxUnpackedToInt8Tensor): |
| 164 | + continue |
| 165 | + if weight.target_dtype != torch.int4: |
| 166 | + continue |
| 167 | + child.weight = nn.Parameter( |
| 168 | + AotiPackedInt4Tensor.from_intx_unpacked_to_int8_tensor( |
| 169 | + weight, |
| 170 | + use_matvec=use_matvec, |
| 171 | + ), |
| 172 | + requires_grad=False, |
| 173 | + ) |
| 174 | + packed += 1 |
| 175 | + return packed |
| 176 | + |
| 177 | + |
| 178 | +torch.serialization.add_safe_globals([AotiPackedInt4Tensor]) |
0 commit comments