MLX
 
Loading...
Searching...
No Matches
hadamard.h
Go to the documentation of this file.
1// Copyright © 2024 Apple Inc.
2
3#pragma once
4
5#include <map>
6
7#include "mlx/utils.h"
8
9namespace mlx::core {
10
11// From http://neilsloane.com/hadamard/
12constexpr std::string_view h12 = R"(
13+-++++++++++
14--+-+-+-+-+-
15+++-++----++
16+---+--+-++-
17+++++-++----
18+-+---+--+-+
19++--+++-++--
20+--++---+--+
21++----+++-++
22+--+-++---+-
23++++----+++-
24+-+--+-++---
25)";
26
27constexpr std::string_view h20 = R"(
28+----+----++--++-++-
29-+----+---+++---+-++
30--+----+---+++-+-+-+
31---+----+---+++++-+-
32----+----++--++-++-+
33-+++++-----+--+++--+
34+-+++-+---+-+--+++--
35++-++--+---+-+--+++-
36+++-+---+---+-+--+++
37++++-----++--+-+--++
38--++-+-++-+-----++++
39---++-+-++-+---+-+++
40+---++-+-+--+--++-++
41++---++-+----+-+++-+
42-++---++-+----+++++-
43-+--+--++-+----+----
44+-+-----++-+----+---
45-+-+-+---+--+----+--
46--+-+++------+----+-
47+--+--++------+----+
48)";
49
50constexpr std::string_view h28 = R"(
51+------++----++-+--+-+--++--
52-+-----+++-----+-+--+-+--++-
53--+-----+++---+-+-+----+--++
54---+-----+++---+-+-+-+--+--+
55----+-----+++---+-+-+++--+--
56-----+-----++++--+-+--++--+-
57------++----++-+--+-+--++--+
58--++++-+-------++--+++-+--+-
59---++++-+-----+-++--+-+-+--+
60+---+++--+----++-++--+-+-+--
61++---++---+----++-++--+-+-+-
62+++---+----+----++-++--+-+-+
63++++--------+-+--++-++--+-+-
64-++++--------+++--++--+--+-+
65-+-++-++--++--+--------++++-
66+-+-++--+--++--+--------++++
67-+-+-++--+--++--+----+---+++
68+-+-+-++--+--+---+---++---++
69++-+-+-++--+------+--+++---+
70-++-+-+-++--+------+-++++---
71+-++-+---++--+------+-++++--
72-++--++-+-++-+++----++------
73+-++--++-+-++-+++-----+-----
74++-++---+-+-++-+++-----+----
75-++-++-+-+-+-+--+++-----+---
76--++-++++-+-+----+++-----+--
77+--++-+-++-+-+----+++-----+-
78++--++-+-++-+-+----++------+
79)";
80
81inline const std::map<int, std::string_view> hadamard_matrices() {
82 return {{12, h12}, {20, h20}, {28, h28}};
83}
84
85inline std::pair<int, int> decompose_hadamard(int n) {
86 // n = m*2^k
87 int m = 1;
88 if (!is_power_of_2(n)) {
89 auto h_matrices = hadamard_matrices();
90 for (auto [factor, _] : h_matrices) {
91 if (n % factor == 0) {
92 m = factor;
93 n /= factor;
94 break;
95 }
96 }
97 if (m == 1) {
98 throw std::invalid_argument(
99 "[hadamard] Only supports n = m*2^k where m in (1, 12, 20, 28).");
100 }
101 }
102 return {n, m};
103}
104
105} // namespace mlx::core
Definition allocator.h:7
std::pair< int, int > decompose_hadamard(int n)
Definition hadamard.h:85
constexpr std::string_view h12
Definition hadamard.h:12
const std::map< int, std::string_view > hadamard_matrices()
Definition hadamard.h:81
constexpr std::string_view h20
Definition hadamard.h:27
constexpr std::string_view h28
Definition hadamard.h:50
bool is_power_of_2(int n)
Definition utils.h:105