|
| 1 | + |
| 2 | +import math |
| 3 | +from pathlib import Path |
| 4 | + |
| 5 | +import torch |
| 6 | +from safetensors import safe_open |
| 7 | + |
| 8 | + |
| 9 | +REPO_PATH = Path(__file__).parent / "hadamards.safetensors" |
| 10 | + |
| 11 | + |
| 12 | +__all__ = ["random_hadamard_matrix", "deterministic_hadamard_matrix", "is_pow2"] |
| 13 | + |
| 14 | + |
| 15 | +# note that hadamard matrix multiplication reuses the code from |
| 16 | +# https://github.com/vllm-project/compressed-tensors/blob/main/src/compressed_tensors/transform/utils/hadamard.py |
| 17 | + |
| 18 | + |
| 19 | +def deterministic_hadamard_matrix( |
| 20 | + size: int, |
| 21 | + dtype: torch.dtype = torch.bfloat16, |
| 22 | + device: torch.device = torch.device("cpu"), |
| 23 | +) -> torch.Tensor: |
| 24 | + """ |
| 25 | + Construct an n-by-n Hadamard matrix, using Sylvester's construction. |
| 26 | + `n` must be a power of 2. |
| 27 | +
|
| 28 | + Adapated from https://github.com/scipy/scipy/blob/v1.15.2/scipy/linalg/_special_matrices.py # noqa: E501 |
| 29 | +
|
| 30 | + :param size: order of the matrix, must be a power of 2 |
| 31 | + :param dtype: data type of matrix |
| 32 | + :param device: device to construct matrix on |
| 33 | + :return: hadamard matrix of size `size` |
| 34 | + """ |
| 35 | + if size <= 0: |
| 36 | + raise ValueError("Cannot construct deterministic hadamard of size <= 0") |
| 37 | + |
| 38 | + log2 = int(math.log2(size)) |
| 39 | + if size != 2**log2: |
| 40 | + raise ValueError("Cannot construct deterministic hadamard of size != 2^n") |
| 41 | + |
| 42 | + H = torch.tensor([[1]], dtype=dtype, device=device) |
| 43 | + |
| 44 | + # Sylvester's construction |
| 45 | + for _ in range(log2): |
| 46 | + H = torch.vstack((torch.hstack((H, H)), torch.hstack((H, -H)))) |
| 47 | + |
| 48 | + return H |
| 49 | + |
| 50 | + |
| 51 | +def random_hadamard_matrix( |
| 52 | + size: int, |
| 53 | + dtype: torch.dtype = torch.bfloat16, |
| 54 | + device: torch.device = torch.device("cpu"), |
| 55 | + gen: torch.Generator | None = None, |
| 56 | +) -> torch.Tensor: |
| 57 | + """ |
| 58 | + Produces a randomly generated Hadamard matrix. Differs from |
| 59 | + `deterministic_hadamard_matrix` in that this function supports non powers of 2 |
| 60 | + and randomization using a seeded generator |
| 61 | +
|
| 62 | + Adapated from https://github.com/facebookresearch/SpinQuant/blob/main/utils/hadamard_utils.py # noqa: E501 |
| 63 | + Known matrices were retrieved from N. J. A. Sloane's Library of Hadamard Matrices http://www.neilsloane.com/hadamard/ # noqa: E501 |
| 64 | +
|
| 65 | + :param size: The dimension of the hamadard matrix |
| 66 | + :param dtype: data type of matrix |
| 67 | + :param device: device to construct matrix on |
| 68 | + :param gen: Optional generator random values |
| 69 | + :return: randomly generated hadamard matrix |
| 70 | + """ |
| 71 | + Q = torch.randint(low=0, high=2, size=(size,), generator=gen, dtype=dtype) # cpu |
| 72 | + Q = Q.to(device=device) |
| 73 | + Q = Q * 2 - 1 |
| 74 | + Q = torch.diag(Q) |
| 75 | + return _matmul_hadU(Q) |
| 76 | + |
| 77 | + |
| 78 | +def is_pow2(n: int) -> bool: |
| 79 | + """ |
| 80 | + Check if a number is a power of 2 |
| 81 | +
|
| 82 | + :param n: number to check |
| 83 | + :return: True iff `n` is a power of 2 |
| 84 | + """ |
| 85 | + return n > 0 and (n & (n - 1) == 0) |
| 86 | + |
| 87 | + |
| 88 | +def _fetch_hadamard_divisor( |
| 89 | + n: int, |
| 90 | + dtype: torch.dtype, |
| 91 | + device: torch.device = torch.device("cpu"), |
| 92 | + file_path: str = REPO_PATH, |
| 93 | +) -> torch.Tensor | None: |
| 94 | + """ |
| 95 | + Fetch a known hadamard matrix from the given file path. The returned matrix will |
| 96 | + be of of size `k` such that `n / k` is a power of two. Return None if no such |
| 97 | + matrix exists. |
| 98 | +
|
| 99 | + Note: This function reopens the safetensors file every time it is called. |
| 100 | + This is technically inefficient, but a very small runtime cost and simpler |
| 101 | + than forcing callers to manage the file open context |
| 102 | +
|
| 103 | + :param n: size of known hadamard matrix |
| 104 | + :param dtype: data type to move fetched hadamard to |
| 105 | + :param device: device to move fetched hadamard to |
| 106 | + :return: a known hadamard matrix of size `n` if one exists, else None |
| 107 | + """ |
| 108 | + open_device = torch.device("cpu") if device.type == "meta" else device |
| 109 | + with safe_open(file_path, framework="pt", device=str(open_device)) as file: |
| 110 | + divisors = sorted((int(key) for key in file.keys()), reverse=True) |
| 111 | + for divisor in divisors: |
| 112 | + if n % divisor == 0 and is_pow2(n // divisor): |
| 113 | + return file.get_tensor(str(divisor)).to(dtype=dtype, device=device) |
| 114 | + |
| 115 | + return None |
| 116 | + |
| 117 | + |
| 118 | +def _matmul_hadU(X: torch.Tensor) -> torch.Tensor: |
| 119 | + size = X.size(0) |
| 120 | + dtype = X.dtype |
| 121 | + device = X.device |
| 122 | + |
| 123 | + # Check if we have the determined hadamard matrix |
| 124 | + hadK = _fetch_hadamard_divisor(size, dtype, device=device) |
| 125 | + if hadK is None: |
| 126 | + raise ValueError(f"Cannot construct random hadamard matrix of size {size}") |
| 127 | + K = hadK.size(0) |
| 128 | + |
| 129 | + # Reshape diag matrix with randomized -1/+1 |
| 130 | + input = X.clone().view(-1, size, 1) |
| 131 | + output = input.clone() |
| 132 | + while input.shape[1] > K: |
| 133 | + input = input.view(input.shape[0], input.shape[1] // 2, 2, input.shape[2]) |
| 134 | + output = output.view(input.shape) |
| 135 | + output[:, :, 0, :] = input[:, :, 0, :] + input[:, :, 1, :] |
| 136 | + output[:, :, 1, :] = input[:, :, 0, :] - input[:, :, 1, :] |
| 137 | + output = output.view(input.shape[0], input.shape[1], -1) |
| 138 | + (input, output) = (output, input) |
| 139 | + assert input.shape[1] == K |
| 140 | + del output |
| 141 | + |
| 142 | + # Do not explicitly repeat - OOM |
| 143 | + # input = torch.bmm( |
| 144 | + # hadK.repeat(len(input), 1, 1).to(input.device).to(input.dtype), input) |
| 145 | + # Use bcast instead |
| 146 | + input = hadK.view(1, K, K).to(input) @ input |
| 147 | + |
| 148 | + # normalize |
| 149 | + return input.view(X.shape) |
0 commit comments