|
| 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 | +"""Backward of 4-bit quantized linear (`et_vk.linear_q4gsw_backward`) export + fp64 golden. |
| 8 | +
|
| 9 | +Mirrors test_quantized_linear.py. The backward computes `d_x = d_out @ dequant(W)` so |
| 10 | +gradients flow through a frozen 4-bit base into a LoRA/DiReFT adapter. CONFIGS reuse the |
| 11 | +real Llama-3.2-1B linear shapes (the backward's d_out is [M, N] and its output d_x is |
| 12 | +[M, K]). The golden is the fp64 dequant-matmul truth; the native test |
| 13 | +(test_webgpu_native.cpp) reconstructs the identical deterministic ramp bit-for-bit. |
| 14 | +""" |
| 15 | + |
| 16 | +import os |
| 17 | +import unittest |
| 18 | +from dataclasses import dataclass |
| 19 | + |
| 20 | +import numpy as np |
| 21 | +import torch |
| 22 | + |
| 23 | +from executorch.backends.vulkan import VulkanPartitioner |
| 24 | +from executorch.exir import to_edge_transform_and_lower |
| 25 | +from torchao.quantization.granularity import PerGroup |
| 26 | +from torchao.quantization.quant_api import IntxWeightOnlyConfig, quantize_ |
| 27 | + |
| 28 | + |
| 29 | +@dataclass(frozen=True) |
| 30 | +class BwdConfig: |
| 31 | + name: str |
| 32 | + m: int # rows (tokens) |
| 33 | + k: int # in_features (== d_x cols) |
| 34 | + n: int # out_features (== d_out cols) |
| 35 | + group_size: int = 32 # K % group_size == 0, K % 8 == 0, N % 8 == 0 |
| 36 | + heavy: bool = False |
| 37 | + |
| 38 | + |
| 39 | +# Mirrored by the C++ kQ4gswBackwardConfigs table (Llama-3.2-1B shapes). |
| 40 | +CONFIGS = [ |
| 41 | + BwdConfig("q_proj", 1, 2048, 2048), # also o_proj |
| 42 | + BwdConfig("kv_proj", 1, 2048, 512), |
| 43 | + BwdConfig("gate_proj", 1, 2048, 8192), |
| 44 | + BwdConfig("down_proj", 1, 8192, 2048), |
| 45 | + BwdConfig("q_proj_112", 112, 2048, 2048), # S=112 multi-row training window |
| 46 | +] |
| 47 | + |
| 48 | + |
| 49 | +def _make_quantized_model(k: int, n: int, group_size: int) -> torch.nn.Module: |
| 50 | + torch.manual_seed(0) # load-bearing: fixes the weights the golden uses |
| 51 | + m = torch.nn.Linear(k, n, bias=False).eval() |
| 52 | + quantize_( |
| 53 | + m, |
| 54 | + IntxWeightOnlyConfig(weight_dtype=torch.int4, granularity=PerGroup(group_size)), |
| 55 | + ) |
| 56 | + return m |
| 57 | + |
| 58 | + |
| 59 | +def _ramp(m_rows: int, cols: int) -> torch.Tensor: |
| 60 | + """Deterministic fp32 [rows, cols]; the C++ side reconstructs it bit-for-bit. |
| 61 | +
|
| 62 | + v[flat] = ((flat % 17) - 8) / 16 -- exact in fp32 (small modulus, po2 denominator). |
| 63 | + """ |
| 64 | + flat = np.arange(m_rows * cols, dtype=np.int64) |
| 65 | + v = ((flat % 17) - 8).astype(np.float32) / np.float32(16.0) |
| 66 | + return torch.from_numpy(v).reshape(m_rows, cols) |
| 67 | + |
| 68 | + |
| 69 | +def _packed_qweights(m: torch.nn.Module): |
| 70 | + """The int4 packed weights + per-group scales `et_vk.linear_q4gsw` consumes. |
| 71 | +
|
| 72 | + Recover them the same way the forward op does: `dequant(W)` is [N, K]; the backward op |
| 73 | + takes the same (weights, weight_scales, group_size) triple the partitioner extracts. |
| 74 | + """ |
| 75 | + aqt = m.weight # AffineQuantizedTensor |
| 76 | + return aqt |
| 77 | + |
| 78 | + |
| 79 | +def _fp64_golden(m: torch.nn.Module, d_out: torch.Tensor) -> np.ndarray: |
| 80 | + """fp64 truth: d_x = d_out @ dequant(W), dequant(W) is [N, K] -> [M, N]@[N, K] = [M, K].""" |
| 81 | + wq = m.weight.dequantize() # [N, K] |
| 82 | + d_x = d_out.double() @ wq.double() # [M, K] in fp64 |
| 83 | + return d_x.to(torch.float32).numpy().astype("<f4") |
| 84 | + |
| 85 | + |
| 86 | +class _BackwardModule(torch.nn.Module): |
| 87 | + """Wraps the linear so autograd through it exercises the registered backward op.""" |
| 88 | + |
| 89 | + def __init__(self, lin: torch.nn.Module) -> None: |
| 90 | + super().__init__() |
| 91 | + self.lin = lin |
| 92 | + |
| 93 | + def forward(self, x: torch.Tensor) -> torch.Tensor: |
| 94 | + return self.lin(x) |
| 95 | + |
| 96 | + |
| 97 | +def _export_backward(m: torch.nn.Module, x: torch.Tensor): |
| 98 | + # Training-style export: forward + backward makes the backward reachable. |
| 99 | + mod = _BackwardModule(m) |
| 100 | + ep = torch.export.export(mod, (x,)) |
| 101 | + return to_edge_transform_and_lower( |
| 102 | + ep, partitioner=[VulkanPartitioner()] |
| 103 | + ).to_executorch() |
| 104 | + |
| 105 | + |
| 106 | +class TestQuantizedLinearBackward(unittest.TestCase): |
| 107 | + def test_op_matches_fp64_golden(self) -> None: |
| 108 | + # Op impl (d_out @ dequant(W)) vs fp64 truth: guards backward formula. |
| 109 | + for cfg in CONFIGS: |
| 110 | + if cfg.heavy: |
| 111 | + continue |
| 112 | + with self.subTest(config=cfg.name): |
| 113 | + m = _make_quantized_model(cfg.k, cfg.n, cfg.group_size) |
| 114 | + d_out = _ramp(cfg.m, cfg.n) |
| 115 | + got = torch.ops.et_vk.linear_q4gsw_backward( |
| 116 | + d_out, _packed_qweights(m), None, cfg.group_size |
| 117 | + ) |
| 118 | + golden = torch.from_numpy(_fp64_golden(m, d_out)) |
| 119 | + torch.testing.assert_close(got, golden, atol=5e-4, rtol=1e-3) |
| 120 | + |
| 121 | + def test_autograd_backward_matches_golden(self) -> None: |
| 122 | + # autograd through linear_q4gsw uses the registered backward op. |
| 123 | + for cfg in CONFIGS: |
| 124 | + if cfg.heavy: |
| 125 | + continue |
| 126 | + with self.subTest(config=cfg.name): |
| 127 | + m = _make_quantized_model(cfg.k, cfg.n, cfg.group_size) |
| 128 | + x = _ramp(cfg.m, cfg.k).requires_grad_(True) |
| 129 | + d_out = _ramp(cfg.m, cfg.n) |
| 130 | + y = m(x) |
| 131 | + y.backward(d_out) |
| 132 | + golden = torch.from_numpy(_fp64_golden(m, d_out)) |
| 133 | + torch.testing.assert_close(x.grad, golden, atol=5e-4, rtol=1e-3) |
| 134 | + |
| 135 | + |
| 136 | +def export_backward_model(cfg: BwdConfig, pte_path: str, golden_path: str) -> None: |
| 137 | + """Export one config's backward .pte + its fp64 golden (raw LE fp32).""" |
| 138 | + m = _make_quantized_model(cfg.k, cfg.n, cfg.group_size) |
| 139 | + x = _ramp(cfg.m, cfg.k) |
| 140 | + et = _export_backward(m, x) |
| 141 | + with open(pte_path, "wb") as f: |
| 142 | + f.write(et.buffer) |
| 143 | + _fp64_golden(m, _ramp(cfg.m, cfg.n)).tofile(golden_path) |
| 144 | + print(f"Exported {pte_path}; golden {golden_path} ({cfg.m * cfg.k} floats)") |
| 145 | + |
| 146 | + |
| 147 | +def export_all_backward_models(out_dir: str, include_heavy: bool = False) -> None: |
| 148 | + for cfg in CONFIGS: |
| 149 | + if cfg.heavy and not include_heavy: |
| 150 | + continue |
| 151 | + pte = os.path.join(out_dir, f"q4gsw_backward_{cfg.name}.pte") |
| 152 | + golden = os.path.join(out_dir, f"q4gsw_backward_{cfg.name}.golden.bin") |
| 153 | + export_backward_model(cfg, pte, golden) |
| 154 | + |
| 155 | + |
| 156 | +if __name__ == "__main__": |
| 157 | + unittest.main() |
0 commit comments