Skip to content

Commit 68ec14e

Browse files
committed
apply sqrt division first
Signed-off-by: Kyle Sayers <kylesayrs@gmail.com>
1 parent 5677553 commit 68ec14e

File tree

2 files changed

+11
-11
lines changed

2 files changed

+11
-11
lines changed

src/compressed_tensors/transform/utils/hadamard.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@
2323

2424
# adapted from:
2525
# https://github.com/scipy/scipy/blob/v1.15.2/scipy/linalg/_special_matrices.py
26-
def deterministic_hadamard_matrix(size: int) -> numpy.ndarray:
26+
def deterministic_hadamard_matrix(size: int) -> torch.Tensor:
2727
"""
2828
Construct an Hadamard matrix.
2929
@@ -47,7 +47,7 @@ def deterministic_hadamard_matrix(size: int) -> numpy.ndarray:
4747
for i in range(0, log2):
4848
H = numpy.vstack((numpy.hstack((H, H)), numpy.hstack((H, -H))))
4949

50-
return H
50+
return torch.from_numpy(H / math.sqrt(size))
5151

5252

5353
# adapted from:
@@ -75,7 +75,7 @@ def random_hadamard_matrix(size: int) -> torch.Tensor:
7575
Q = torch.randint(low=0, high=2, size=(size,)).to(torch.float64)
7676
Q = Q * 2 - 1
7777
Q = torch.diag(Q)
78-
return _matmul_hadU(Q)
78+
return _matmul_hadU(Q) / math.sqrt(size)
7979

8080

8181
def _get_hadK(n: int, transpose: bool = False) -> Tuple[torch.Tensor, int]:

tests/test_transform/utils/test_hadamards.py renamed to tests/test_transform/utils/test_hadamard.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -33,10 +33,10 @@
3333
)
3434
def test_packed_hadamard_compliant(had_func):
3535
had_matrix = had_func()
36-
size = had_matrix.shape[0]
36+
size = had_matrix.size(0)
3737
# HH.T == nI
38-
val_1 = had_matrix @ had_matrix.T
39-
assert torch.equal(val_1 / size, torch.eye(size))
38+
product = had_matrix @ had_matrix.T
39+
assert torch.equal(product, size * torch.eye(size))
4040

4141

4242
@pytest.mark.parametrize(
@@ -45,8 +45,8 @@ def test_packed_hadamard_compliant(had_func):
4545
)
4646
def test_random_hadamard_matrix_compliant(size):
4747
had_matrix = random_hadamard_matrix(size)
48-
val_1 = torch.round(had_matrix @ had_matrix.T)
49-
assert torch.equal(val_1 / size, torch.eye(size))
48+
product = torch.round(had_matrix @ had_matrix.T)
49+
assert torch.equal(product, torch.eye(size))
5050

5151

5252
@pytest.mark.parametrize(
@@ -55,6 +55,6 @@ def test_random_hadamard_matrix_compliant(size):
5555
)
5656
def test_deterministic_hadamard_compliant(size):
5757
had_matrix = deterministic_hadamard_matrix(size)
58-
# HH.T == nI
59-
val_1 = had_matrix @ had_matrix.T
60-
assert numpy.array_equal(val_1 / size, numpy.eye(size))
58+
# (H / sqrt(n))(H.T / sqrt(n)) == I
59+
product = had_matrix @ had_matrix.T
60+
assert numpy.array_equal(product, numpy.eye(size))

0 commit comments

Comments
 (0)