|
| 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 | +# pyre-unsafe |
| 8 | + |
| 9 | +# Helper functions for tranforming the model to be able to load pre-quantized checkpoints. |
| 10 | + |
| 11 | +from typing import Any, Optional |
| 12 | + |
| 13 | +import torch |
| 14 | +from torch import nn |
| 15 | + |
| 16 | +from torchao.quantization.GPTQ import _check_linear_int4_k, Int8DynActInt4WeightLinear |
| 17 | +from torchao.quantization.quant_api import _replace_with_custom_fn_if_matches_filter |
| 18 | + |
| 19 | +from .quantize import Int8DynActInt8WeightLinear, QuantizedGroupEmbedding |
| 20 | + |
| 21 | + |
| 22 | +def _replace_linear_with_linear_8da4w_for_pre_quantization( |
| 23 | + module: torch.nn.Module, |
| 24 | + checkpoint: Any, |
| 25 | + group_size: int, |
| 26 | + precision: torch.dtype, |
| 27 | + scales_precision: torch.dtype, |
| 28 | +): |
| 29 | + def filter_fn(child: torch.nn.Module, cur_fqn: str) -> bool: |
| 30 | + # Only replace linear layers where the checkpoint contains explicit scales |
| 31 | + scales_key = f"{cur_fqn}.scales" |
| 32 | + if isinstance(child, nn.Linear) and scales_key in checkpoint: |
| 33 | + assert _check_linear_int4_k(child.in_features, group_size) |
| 34 | + assert checkpoint[f"{cur_fqn}.weight"].dtype == torch.int8 |
| 35 | + assert checkpoint[scales_key].dtype == scales_precision |
| 36 | + return True |
| 37 | + return False |
| 38 | + |
| 39 | + def replacement_fn(child: torch.nn.Module) -> torch.nn.Module: |
| 40 | + new_linear = Int8DynActInt4WeightLinear( |
| 41 | + child.in_features, |
| 42 | + child.out_features, |
| 43 | + bias=False, |
| 44 | + device=child.weight.device, |
| 45 | + groupsize=group_size, |
| 46 | + precision=precision, |
| 47 | + scales_precision=scales_precision, |
| 48 | + ) |
| 49 | + return new_linear |
| 50 | + |
| 51 | + _replace_with_custom_fn_if_matches_filter(module, replacement_fn, filter_fn) |
| 52 | + |
| 53 | + |
| 54 | +def transform_linear_for_pre_quantization( |
| 55 | + module: torch.nn.Module, |
| 56 | + checkpoint: Any, |
| 57 | + group_size: int, |
| 58 | + dtype: torch.dtype, |
| 59 | +) -> torch.nn.Module: |
| 60 | + """ |
| 61 | + Transform the model to be able to load pre-quantized checkpoints that |
| 62 | + are quantized with the given group size and quantization mode for |
| 63 | + linear layers. |
| 64 | + """ |
| 65 | + |
| 66 | + if group_size not in [32, 64, 128, 256]: |
| 67 | + raise ValueError( |
| 68 | + f"Group size {group_size} is not supported for pre-quantized checkpoint." |
| 69 | + ) |
| 70 | + _replace_linear_with_linear_8da4w_for_pre_quantization( |
| 71 | + module, |
| 72 | + checkpoint, |
| 73 | + group_size, |
| 74 | + dtype, |
| 75 | + dtype, |
| 76 | + ) |
| 77 | + return module |
| 78 | + |
| 79 | + |
| 80 | +def _replace_output_linear_with_linear_int8_for_pre_quantization( |
| 81 | + module: torch.nn.Module, |
| 82 | + checkpoint: Any, |
| 83 | + dtype: torch.dtype, |
| 84 | +): |
| 85 | + def filter_fn(child: torch.nn.Module, cur_fqn: str) -> bool: |
| 86 | + scales_key = f"{cur_fqn}.scales" |
| 87 | + if ( |
| 88 | + isinstance(child, nn.Linear) |
| 89 | + and scales_key in checkpoint |
| 90 | + and "output" in cur_fqn |
| 91 | + ): |
| 92 | + assert checkpoint[f"{cur_fqn}.weight"].dtype == torch.int8 |
| 93 | + assert checkpoint[scales_key].dtype == dtype |
| 94 | + return True |
| 95 | + return False |
| 96 | + |
| 97 | + def replacement_fn(child: torch.nn.Module) -> torch.nn.Module: |
| 98 | + new_linear = Int8DynActInt8WeightLinear( |
| 99 | + device=child.weight.device, |
| 100 | + in_features=child.in_features, |
| 101 | + out_features=child.out_features, |
| 102 | + precision=dtype, |
| 103 | + bias=False, |
| 104 | + ) |
| 105 | + return new_linear |
| 106 | + |
| 107 | + _replace_with_custom_fn_if_matches_filter(module, replacement_fn, filter_fn) |
| 108 | + |
| 109 | + |
| 110 | +def transform_output_linear_for_pre_quantization( |
| 111 | + module: torch.nn.Module, |
| 112 | + checkpoint: Any, |
| 113 | + dtype: torch.dtype, |
| 114 | +) -> torch.nn.Module: |
| 115 | + """ |
| 116 | + Transform the model to be able to load pre-quantized checkpoints that |
| 117 | + has the output layer quantized per-channel. |
| 118 | + """ |
| 119 | + _replace_output_linear_with_linear_int8_for_pre_quantization( |
| 120 | + module, |
| 121 | + checkpoint, |
| 122 | + dtype, |
| 123 | + ) |
| 124 | + return module |
| 125 | + |
| 126 | + |
| 127 | +def _replace_embedding_with_quantized_group_embedding_for_pre_quantization( |
| 128 | + module: torch.nn.Module, |
| 129 | + checkpoint: Any, |
| 130 | + dtype: torch.dtype, |
| 131 | + bit_width: int, |
| 132 | + group_size: Optional[int] = None, |
| 133 | +): |
| 134 | + def filter_fn(child: torch.nn.Module, cur_fqn: str) -> bool: |
| 135 | + # Only replace embedding layers where the checkpoint contains explicit scales |
| 136 | + scales_key = f"{cur_fqn}.scales" |
| 137 | + if isinstance(child, nn.Embedding) and scales_key in checkpoint: |
| 138 | + assert checkpoint[f"{cur_fqn}.weight"].dtype == torch.int8 |
| 139 | + assert checkpoint[scales_key].dtype == torch.float32 |
| 140 | + return True |
| 141 | + return False |
| 142 | + |
| 143 | + def replacement_fn(child: torch.nn.Module) -> torch.nn.Module: |
| 144 | + new_embedding = QuantizedGroupEmbedding( |
| 145 | + device=child.weight.device, |
| 146 | + vocab_size=child.weight.shape[0], |
| 147 | + embedding_dim=child.weight.shape[1], |
| 148 | + group_size=group_size, |
| 149 | + dtype=dtype, |
| 150 | + packed=False, # TODO(lunwenh): support packed embedding for pre-quantized |
| 151 | + ) |
| 152 | + return new_embedding |
| 153 | + |
| 154 | + _replace_with_custom_fn_if_matches_filter(module, replacement_fn, filter_fn) |
| 155 | + |
| 156 | + |
| 157 | +def transform_embedding_for_pre_quantization( |
| 158 | + module: torch.nn.Module, |
| 159 | + checkpoint: Any, |
| 160 | + dtype: torch.dtype, |
| 161 | + bit_width: int, |
| 162 | + group_size: Optional[int] = None, |
| 163 | +) -> torch.nn.Module: |
| 164 | + """ |
| 165 | + Transform the model to be able to load pre-quantized checkpoints that |
| 166 | + are quantized with the given bit_width and group size for embedding. |
| 167 | + """ |
| 168 | + if group_size is not None and group_size not in [0, 32, 64, 128, 256]: |
| 169 | + raise ValueError( |
| 170 | + f"Group size {group_size} is not supported for pre-quantized checkpoint." |
| 171 | + ) |
| 172 | + _replace_embedding_with_quantized_group_embedding_for_pre_quantization( |
| 173 | + module, |
| 174 | + checkpoint, |
| 175 | + dtype, |
| 176 | + bit_width, |
| 177 | + group_size, |
| 178 | + ) |
| 179 | + return module |
| 180 | + |
| 181 | + |
| 182 | +def sanitize_checkpoint_from_pre_quantization( |
| 183 | + checkpoint: Any, |
| 184 | +): |
| 185 | + """ |
| 186 | + Sanitize the pre-quantized checkpoint. |
| 187 | + - Converts all tensors to contiguous format |
| 188 | + - Squeeze all tensors |
| 189 | + """ |
| 190 | + for k, v in checkpoint.items(): |
| 191 | + checkpoint[k] = torch.squeeze(v.contiguous()) |
0 commit comments