|
| 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 | +from dataclasses import dataclass |
| 8 | + |
| 9 | +import torch.nn as nn |
| 10 | +from torchtitan.config import Configurable |
| 11 | +from torchtitan.tools.logging import logger |
| 12 | + |
| 13 | +# Supported scheme names. |
| 14 | +_SUPPORTED_SCHEMES = ( |
| 15 | + "int4_weight_only", |
| 16 | + "intx_weight_only", |
| 17 | + "int8_dynamic_act_intx_weight", |
| 18 | + "float8_dynamic_act_float8_weight", |
| 19 | + "float8_dynamic_act_int4_weight", |
| 20 | + "nvfp4", |
| 21 | + "mx", |
| 22 | +) |
| 23 | + |
| 24 | +# Schemes that accept a group_size parameter. |
| 25 | +_SCHEMES_WITH_GROUP_SIZE = ( |
| 26 | + "int4_weight_only", |
| 27 | + "intx_weight_only", |
| 28 | + "int8_dynamic_act_intx_weight", |
| 29 | +) |
| 30 | + |
| 31 | + |
| 32 | +def _build_base_config(scheme: str, group_size: int): |
| 33 | + """Return a torchao PTQ base config for the given scheme name.""" |
| 34 | + if scheme == "int4_weight_only": |
| 35 | + from torchao.quantization import Int4WeightOnlyConfig |
| 36 | + |
| 37 | + return Int4WeightOnlyConfig(group_size=group_size) |
| 38 | + |
| 39 | + elif scheme == "intx_weight_only": |
| 40 | + import torch |
| 41 | + from torchao.quantization import IntxWeightOnlyConfig |
| 42 | + from torchao.quantization.granularity import PerGroup |
| 43 | + |
| 44 | + int4_dtype = torch.int4 # pyrefly: ignore[missing-attribute] |
| 45 | + return IntxWeightOnlyConfig( |
| 46 | + weight_dtype=int4_dtype, |
| 47 | + granularity=PerGroup(group_size), |
| 48 | + ) |
| 49 | + |
| 50 | + elif scheme == "int8_dynamic_act_intx_weight": |
| 51 | + import torch |
| 52 | + from torchao.quantization import Int8DynamicActivationIntxWeightConfig |
| 53 | + from torchao.quantization.granularity import PerGroup |
| 54 | + |
| 55 | + int4_dtype = torch.int4 # pyrefly: ignore[missing-attribute] |
| 56 | + return Int8DynamicActivationIntxWeightConfig( |
| 57 | + weight_dtype=int4_dtype, |
| 58 | + weight_granularity=PerGroup(group_size), |
| 59 | + ) |
| 60 | + |
| 61 | + elif scheme == "float8_dynamic_act_float8_weight": |
| 62 | + from torchao.quantization import Float8DynamicActivationFloat8WeightConfig |
| 63 | + |
| 64 | + return Float8DynamicActivationFloat8WeightConfig() |
| 65 | + |
| 66 | + elif scheme == "float8_dynamic_act_int4_weight": |
| 67 | + from torchao.quantization import Float8DynamicActivationInt4WeightConfig |
| 68 | + |
| 69 | + return Float8DynamicActivationInt4WeightConfig() |
| 70 | + |
| 71 | + elif scheme == "nvfp4": |
| 72 | + from torchao.prototype.mx_formats import NVFP4DynamicActivationNVFP4WeightConfig |
| 73 | + |
| 74 | + return NVFP4DynamicActivationNVFP4WeightConfig() |
| 75 | + |
| 76 | + elif scheme == "mx": |
| 77 | + from torchao.prototype.mx_formats import MXDynamicActivationMXWeightConfig |
| 78 | + |
| 79 | + return MXDynamicActivationMXWeightConfig() |
| 80 | + |
| 81 | + else: |
| 82 | + raise ValueError( |
| 83 | + f"Unknown QAT scheme '{scheme}'. Supported: {_SUPPORTED_SCHEMES}" |
| 84 | + ) |
| 85 | + |
| 86 | + |
| 87 | +class QATConverter(Configurable): |
| 88 | + """Apply quantization-aware training via torchao's QATConfig. |
| 89 | +
|
| 90 | + Uses ``torchao.quantize_(model, QATConfig(base_config, step="prepare"))`` |
| 91 | + to insert fake quantization into ``nn.Linear`` modules. The ``scheme`` |
| 92 | + config field selects a torchao PTQ base config, which QATConfig uses to |
| 93 | + infer the appropriate fake quantization for both weights and activations. |
| 94 | +
|
| 95 | + Supported schemes: |
| 96 | + - ``"int4_weight_only"`` — int4 weight-only fake quantization |
| 97 | + - ``"intx_weight_only"`` — intx weight-only fake quantization |
| 98 | + - ``"int8_dynamic_act_intx_weight"`` — int8 activation + int4 weight |
| 99 | + - ``"float8_dynamic_act_float8_weight"`` — float8 activation + float8 weight |
| 100 | + - ``"float8_dynamic_act_int4_weight"`` — float8 activation + int4 weight |
| 101 | + - ``"nvfp4"`` — NVFP4 dynamic activation + NVFP4 weight |
| 102 | + - ``"mx"`` — MX dynamic activation + MX weight |
| 103 | +
|
| 104 | + When composed with LoRA (QATConverter listed before LoRAConverter in converters), |
| 105 | + LoRA will inherit from FakeQuantizedLinear so base weights are fake-quantized |
| 106 | + while LoRA adapters stay full-precision. |
| 107 | + """ |
| 108 | + |
| 109 | + @dataclass(kw_only=True, slots=True) |
| 110 | + class Config(Configurable.Config): |
| 111 | + scheme: str = "int4_weight_only" |
| 112 | + """QAT scheme name. Maps to a torchao PTQ base config. |
| 113 | + Supported: 'int4_weight_only', 'intx_weight_only', |
| 114 | + 'int8_dynamic_act_intx_weight', 'float8_dynamic_act_float8_weight', |
| 115 | + 'float8_dynamic_act_int4_weight', 'nvfp4', 'mx'.""" |
| 116 | + |
| 117 | + group_size: int = 256 |
| 118 | + """Group size for per-group weight quantization. |
| 119 | + Used by schemes that support per-group granularity |
| 120 | + (int4_weight_only, intx_weight_only, int8_dynamic_act_intx_weight). |
| 121 | + Must divide in_features of all Linear layers in the model.""" |
| 122 | + |
| 123 | + def __init__(self, config: Config, **kwargs): |
| 124 | + if config.scheme not in _SUPPORTED_SCHEMES: |
| 125 | + raise ValueError( |
| 126 | + f"Unknown QAT scheme '{config.scheme}'. " |
| 127 | + f"Supported: {_SUPPORTED_SCHEMES}" |
| 128 | + ) |
| 129 | + self.scheme = config.scheme |
| 130 | + self.group_size = config.group_size |
| 131 | + if config.scheme not in _SCHEMES_WITH_GROUP_SIZE: |
| 132 | + logger.warning( |
| 133 | + f"QAT scheme '{config.scheme}' does not use group_size, " |
| 134 | + f"ignoring group_size={config.group_size}" |
| 135 | + ) |
| 136 | + logger.info( |
| 137 | + f"QAT training active (scheme={self.scheme}, group_size={self.group_size})" |
| 138 | + ) |
| 139 | + |
| 140 | + def convert(self, model: nn.Module) -> None: |
| 141 | + from torchao.quantization import quantize_ |
| 142 | + from torchao.quantization.qat import QATConfig |
| 143 | + from torchao.quantization.qat.api import QATStep |
| 144 | + |
| 145 | + base_config = _build_base_config(self.scheme, self.group_size) |
| 146 | + quantize_(model, QATConfig(base_config, step=QATStep.PREPARE)) |
| 147 | + logger.info( |
| 148 | + f"Applied QAT fake quantization (scheme={self.scheme}, " |
| 149 | + f"group_size={self.group_size})" |
| 150 | + ) |
| 151 | + |
| 152 | + def post_optimizer_hook(self, model: nn.Module | list[nn.Module]) -> None: |
| 153 | + pass |
0 commit comments