Elffuss BraidHub

kikocis/kleidiai public

main · 6.5 KiBRawPermalink
1//
2// SPDX-FileCopyrightText: Copyright 2025-2026 Arm Limited and/or its affiliates <open-source-office@arm.com>
3//
4// SPDX-License-Identifier: Apache-2.0
5//
6
7#pragma once
8
9#include <algorithm>
10#include <cstddef>
11#include <cstdint>
12#include <numeric>
13#include <optional>
14#include <random>
15#include <unordered_set>
16#include <utility>
17#include <vector>
18
19#include "test/common/matmul_test_common.hpp"
20#include "test/common/safe_math.hpp"
21
22namespace kai::test {
23
24class MatMulShapeGenerator {
25public:
26 // Construct with inclusive ranges for M, N, and K.
27 MatMulShapeGenerator(
28 const Range<std::size_t> m_range, const Range<std::size_t> n_range, const Range<std::size_t> k_range,
29 SeedFeed& feed) :
30 m_m_range(m_range), m_n_range(n_range), m_k_range(k_range), m_rng(feed()) {
31 if (!m_m_range.is_valid()) {
32 KAI_ERROR("Invalid M range");
33 }
34 if (!m_n_range.is_valid()) {
35 KAI_ERROR("Invalid N range");
36 }
37 if (!m_k_range.is_valid()) {
38 KAI_ERROR("Invalid K range");
39 }
40 rebuild_distributions();
41 }
42
43 /// Generate the next random shape.
44 ///
45 /// @return Random shape.
46 MatMulShape next() {
47 return MatMulShape{m_dist_m(m_rng), m_dist_n(m_rng), m_dist_k(m_rng)};
48 }
49
50 /// Generate a set of unique random shapes.
51 ///
52 /// @param[in] count Number of unique shapes to generate.
53 ///
54 /// @return A vector of unique shapes.
55 std::vector<MatMulShape> generate(const std::size_t count) {
56 // Max unique combos in the current grid (safeguard against over-asking)
57 const std::size_t m_span = m_m_range.inclusive_count();
58 const std::size_t n_span = m_n_range.inclusive_count();
59 const std::size_t k_span = m_k_range.inclusive_count();
60 const auto mn_prod = safe_mul(m_span, n_span);
61 const auto total = mn_prod ? safe_mul(*mn_prod, k_span) : std::optional<std::size_t>{};
62
63 const std::size_t target = total ? std::min<std::size_t>(count, *total) : count;
64
65 std::vector<MatMulShape> out;
66 out.reserve(target);
67 std::unordered_set<MatMulShape, MatMulShape::Hash> seen;
68 seen.reserve(target * 2 + 1);
69
70 // First try random sampling with a bounded number of attempts.
71 // Heuristic: cap attempts to 10x target or 1e5, whichever larger for small targets
72 const std::size_t max_attempts = std::max<std::size_t>(target * 10, 100000);
73 std::size_t attempts = 0;
74
75 while (out.size() < target && attempts < max_attempts) {
76 ++attempts;
77 if (const MatMulShape s = next(); seen.insert(s).second) {
78 out.emplace_back(s);
79 }
80 }
81
82 if (out.size() == target) {
83 return out;
84 }
85
86 // Fallback deterministic fill to guarantee completion:
87 // Walk the grid in a pseudo-random permutation using a stride relatively prime to spans.
88 // We only need to fill remaining slots.
89 const std::size_t need = target - out.size();
90 if (!total) {
91 // When total overflowed, we can't enumerate the grid reliably.
92 // Fall back to a simple deterministic scan within the finite ranges.
93 fill_deterministic_scan(need, seen, out);
94 return out;
95 }
96
97 // Enumerate indices in [0, total). Map index -> (m, n, k).
98 // index_to_triplet(i): m varies fastest, then n, then k.
99 const std::size_t mn_span = mn_prod.value_or(1);
100
101 // Choose random start and stride; make stride odd and co-prime-ish to total when possible.
102 std::uniform_int_distribution<std::size_t> dist_index(0, *total - 1);
103 const std::size_t start = dist_index(m_rng);
104 std::size_t stride = dist_index(m_rng) | 1ULL; // odd stride
105
106 // Try to adjust stride a few times to avoid small common factors with spans
107 for (int tries = 0; tries < 8; ++tries) {
108 if (std::gcd(stride, *total) == 1) {
109 break;
110 }
111 stride += 2; // stay odd
112 if (stride >= *total) {
113 stride %= *total;
114 }
115 if (stride == 0) {
116 stride = 1;
117 }
118 }
119
120 std::size_t filled = 0;
121 for (std::size_t i = 0; i < *total && filled < need; ++i) {
122 const std::size_t idx = (start + i * stride) % *total;
123 const std::size_t m = m_m_range.min + (idx % m_span);
124 const std::size_t n = m_n_range.min + ((idx / m_span) % n_span);
125 const std::size_t k = m_k_range.min + (idx / mn_span);
126 if (const MatMulShape s{m, n, k}; seen.insert(s).second) {
127 out.emplace_back(s);
128 ++filled;
129 }
130 }
131
132 // Fill any remaining slots with a simple deterministic scan.
133 if (filled < need) {
134 fill_deterministic_scan(need - filled, seen, out);
135 }
136 return out;
137 }
138
139private:
140 Range<std::size_t> m_m_range;
141 Range<std::size_t> m_n_range;
142 Range<std::size_t> m_k_range;
143 std::mt19937 m_rng;
144 std::uniform_int_distribution<std::size_t> m_dist_m{1, 1};
145 std::uniform_int_distribution<std::size_t> m_dist_n{1, 1};
146 std::uniform_int_distribution<std::size_t> m_dist_k{1, 1};
147
148 void rebuild_distributions() {
149 m_dist_m = std::uniform_int_distribution(m_m_range.min, m_m_range.max);
150 m_dist_n = std::uniform_int_distribution(m_n_range.min, m_n_range.max);
151 m_dist_k = std::uniform_int_distribution(m_k_range.min, m_k_range.max);
152 }
153
154 void fill_deterministic_scan(
155 std::size_t need, std::unordered_set<MatMulShape, MatMulShape::Hash>& seen,
156 std::vector<MatMulShape>& out) const {
157 // Simple row-major scan across the finite ranges (M fastest, then N, then K)
158 std::size_t k = m_k_range.min;
159 while (k <= m_k_range.max && need > 0) {
160 std::size_t n = m_n_range.min;
161 while (n <= m_n_range.max && need > 0) {
162 std::size_t m = m_m_range.min;
163 while (m <= m_m_range.max && need > 0) {
164 if (const MatMulShape s{m, n, k}; seen.insert(s).second) {
165 out.emplace_back(s);
166 --need;
167 }
168 if (m == m_m_range.max) {
169 break;
170 }
171 ++m;
172 }
173 if (n == m_n_range.max) {
174 break;
175 }
176 ++n;
177 }
178 if (k == m_k_range.max) {
179 break;
180 }
181 ++k;
182 }
183 }
184};
185
186} // namespace kai::test