|
| 1 | +# Copyright (c) 2021 - present / Neuralmagic, Inc. All Rights Reserved. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, |
| 10 | +# software distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +import math |
| 16 | + |
| 17 | +import numpy |
| 18 | +import torch |
| 19 | + |
| 20 | + |
| 21 | +__all__ = ["random_hadamard_matrix", "deterministic_hadamard_matrix"] |
| 22 | + |
| 23 | +# adapted from: |
| 24 | +# https://github.com/scipy/scipy/blob/v1.15.2/scipy/linalg/_special_matrices.py |
| 25 | +def deterministic_hadamard_matrix(size: int): |
| 26 | + """ |
| 27 | + Construct an Hadamard matrix. |
| 28 | +
|
| 29 | + Constructs an n-by-n Hadamard matrix, using Sylvester's |
| 30 | + construction. `n` must be a power of 2. |
| 31 | +
|
| 32 | + :param size: order of the matrix; must be a power of 2 |
| 33 | +
|
| 34 | + returns a (size, size) hadamard matrix |
| 35 | + """ |
| 36 | + |
| 37 | + dtype = int |
| 38 | + if size < 1: |
| 39 | + lg2 = 0 |
| 40 | + else: |
| 41 | + lg2 = int(math.log(size, 2)) |
| 42 | + if 2**lg2 != size: |
| 43 | + raise ValueError("size must be an positive integer and a power of 2") |
| 44 | + |
| 45 | + H = numpy.array([[1]], dtype=dtype) |
| 46 | + |
| 47 | + # Sylvester's construction |
| 48 | + for i in range(0, lg2): |
| 49 | + H = numpy.vstack((numpy.hstack((H, H)), numpy.hstack((H, -H)))) |
| 50 | + |
| 51 | + return H |
| 52 | + |
| 53 | + |
| 54 | +# adapted from: |
| 55 | +# https://github.com/facebookresearch/SpinQuant/blob/main/utils/hadamard_utils.py |
| 56 | + |
| 57 | +# TODO: the following library exists for online rotations and should be considered |
| 58 | +# in the future: |
| 59 | +# https://github.com/Dao-AILab/fast-hadamard-transform/tree/master |
| 60 | + |
| 61 | + |
| 62 | +def random_hadamard_matrix(size: int) -> torch.Tensor: |
| 63 | + """ |
| 64 | + Produces a randomly generated Hadamard matrix. |
| 65 | + See https://cornell-relaxml.github.io/quip-sharp/ , |
| 66 | + Section "Randomized Hadamard Transformation" |
| 67 | +
|
| 68 | + :param size: The dimension of the matrix. Matrix generated will have dimensions |
| 69 | + (size, size) |
| 70 | +
|
| 71 | + """ |
| 72 | + # TODO: potentially update to add "seed" as an arugment, to allow |
| 73 | + # the matrix generated to be reproducible |
| 74 | + |
| 75 | + # Benefits: support other shapes / non powers of 2, support randomization |
| 76 | + Q = torch.randint(low=0, high=2, size=(size,)).to(torch.float64) |
| 77 | + Q = Q * 2 - 1 |
| 78 | + Q = torch.diag(Q) |
| 79 | + return _matmul_hadU(Q) |
| 80 | + |
| 81 | + |
| 82 | +def _get_hadK(n, transpose=False): |
| 83 | + # NOTE: we can easily extend the list of supported shapes/sizes |
| 84 | + # by adding to these methods |
| 85 | + hadK, K = None, None |
| 86 | + if n % 20 == 0: |
| 87 | + assert _is_pow2(n // 20) |
| 88 | + K = 20 |
| 89 | + hadK = _get_had20().T if transpose else _get_had20() |
| 90 | + elif n % 12 == 0: |
| 91 | + assert _is_pow2(n // 12) |
| 92 | + K = 12 |
| 93 | + hadK = _get_had12().T if transpose else _get_had12() |
| 94 | + else: |
| 95 | + assert _is_pow2(n) |
| 96 | + K = 1 |
| 97 | + |
| 98 | + return hadK, K |
| 99 | + |
| 100 | + |
| 101 | +def _matmul_hadU(X, transpose=False): |
| 102 | + n = X.shape[-1] |
| 103 | + # Check if we have the determined hadamard matrix |
| 104 | + hadK, K = _get_hadK(n, transpose) |
| 105 | + # Reshape diag matrix with randomized -1/+1 |
| 106 | + input = X.clone().view(-1, n, 1) |
| 107 | + output = input.clone() |
| 108 | + |
| 109 | + # for cases when hadK is not predetermined, determine hadamard matrix |
| 110 | + while input.shape[1] > K: |
| 111 | + input = input.view(input.shape[0], input.shape[1] // 2, 2, input.shape[2]) |
| 112 | + output = output.view(input.shape) |
| 113 | + output[:, :, 0, :] = input[:, :, 0, :] + input[:, :, 1, :] |
| 114 | + output[:, :, 1, :] = input[:, :, 0, :] - input[:, :, 1, :] |
| 115 | + output = output.view(input.shape[0], input.shape[1], -1) |
| 116 | + (input, output) = (output, input) |
| 117 | + del output |
| 118 | + |
| 119 | + # K == 1 when hadK is None; this happens when the size dim (n) |
| 120 | + # is not comaptible with any of the maintained hadamard matrices |
| 121 | + |
| 122 | + if K > 1: |
| 123 | + # Do not explicitly repeat - OOM |
| 124 | + # input = torch.bmm( |
| 125 | + # hadK.repeat(len(input), 1, 1).to(input.device).to(input.dtype), input) |
| 126 | + # Use bcast instead |
| 127 | + |
| 128 | + # for cases when hadK is pre-determined |
| 129 | + input = hadK.view(1, K, K).to(input) @ input |
| 130 | + |
| 131 | + # normalize |
| 132 | + return input.view(X.shape) / torch.tensor(n).sqrt() |
| 133 | + |
| 134 | + |
| 135 | +def _is_pow2(n): |
| 136 | + return (n & (n - 1) == 0) and (n > 0) |
| 137 | + |
| 138 | + |
| 139 | +def _reshape_bits(packed_bits, original_size): |
| 140 | + had_unpacked = numpy.unpackbits(packed_bits) |
| 141 | + had_unpacked = [1 if x == 1 else -1 for x in had_unpacked] |
| 142 | + had_unpacked = numpy.array(had_unpacked).reshape((original_size, original_size)) |
| 143 | + return had_unpacked |
| 144 | + |
| 145 | + |
| 146 | +# http://www.neilsloane.com/hadamard/index.html |
| 147 | +def _get_had12(): |
| 148 | + # fmt: off |
| 149 | + had_12 = numpy.array([128, 13, 29, 232, 235, 71, 218, |
| 150 | + 62, 209, 246, 139, 180, 157, 168, 237, 199, 106, 59], dtype=numpy.uint8) |
| 151 | + # fmt: on |
| 152 | + # TODO: just unpack during apply |
| 153 | + had_12_unpacked = _reshape_bits(had_12, original_size=12) |
| 154 | + return torch.FloatTensor(had_12_unpacked) |
| 155 | + |
| 156 | + |
| 157 | +def _get_had20(): |
| 158 | + # fmt: off |
| 159 | + had_20 = numpy.array([128, 0, 13, 133, 121, 236, 43, 203, 97, 94, 155, 10, 252, |
| 160 | + 216, 87, 230, 194, 191, 54, 21, 249, 176, 171, 205, 133, 222, 108, 42, 243, |
| 161 | + 97, 215, 155, 10, 188, 216, 149, 230, 200, 175, 54, 133, 121, 188, 43, |
| 162 | + 205, 225, 94, 107, 10, 243], dtype=numpy.uint8) |
| 163 | + # fmt: on |
| 164 | + # TODO: just unpack during apply |
| 165 | + had_20_unpacked = _reshape_bits(had_20, original_size=20) |
| 166 | + return torch.FloatTensor(had_20_unpacked) |
0 commit comments