Loading...
Searching...
No Matches
SchemeII.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// Copyright (c) gpridge developers
3
4// The residue and reconstruction loops round, floor and select on every
5// entry. GCC vectorizes those only when it may assume that floating-point
6// operations do not trap; the computed values are the same IEEE results.
7#if defined(__GNUC__) && !defined(__clang__)
8#pragma GCC optimize("no-trapping-math")
9#endif
10
11#include "SchemeII.h"
12
13#include <dlfcn.h>
14
15#include <Eigen/Core>
16#if defined(__x86_64__) && defined(__GNUC__)
17#include <immintrin.h>
18#endif
19#include <algorithm>
20#include <atomic>
21#include <bit>
22#include <chrono>
23#include <cmath>
24#include <cstdio>
25#include <cstdlib>
26#include <cstring>
27#include <limits>
28#include <mutex>
29#include <numeric>
30#include <stdexcept>
31#include <tuple>
32
33#include "../TileParallel.h"
34#include "CudaEngine.h"
35
37namespace {
38
39#if defined(__x86_64__) && defined(__GNUC__)
40bool signedResidueSimdAvailable()
41{
42 static const bool supported =
43 __builtin_cpu_supports("avx2") && __builtin_cpu_supports("fma");
44 // Scalar execution preserves the order of unmasked floating-point traps.
45 return supported && (_mm_getcsr() & _MM_MASK_MASK) == _MM_MASK_MASK;
46}
47
48// Rounding follows MXCSR, and neither reduction suppresses inexact exceptions.
49// Both fused reductions precede the two ordered centering operations.
50#define GPR_SIGNED_RESIDUE_PACKET(Result, Values) \
51 do { \
52 Result = _mm256_loadu_pd(Values); \
53 __m256d nearest = _mm256_round_pd(_mm256_mul_pd(Result, reciprocal), \
54 _MM_FROUND_CUR_DIRECTION); \
55 Result = _mm256_fmadd_pd(_mm256_xor_pd(nearest, negative_zero), \
56 modulus, Result); \
57 nearest = _mm256_round_pd(_mm256_mul_pd(Result, reciprocal), \
58 _MM_FROUND_CUR_DIRECTION); \
59 Result = _mm256_fmadd_pd(_mm256_xor_pd(nearest, negative_zero), \
60 modulus, Result); \
61 Result = _mm256_blendv_pd(Result, _mm256_sub_pd(Result, modulus), \
62 _mm256_cmp_pd(Result, upper, _CMP_GT_OQ)); \
63 Result = _mm256_blendv_pd(Result, _mm256_add_pd(Result, modulus), \
64 _mm256_cmp_pd(Result, lower, _CMP_LT_OQ)); \
65 } while (false)
66
67__attribute__((target("avx2,fma"))) std::int64_t signedFp64ResiduesAvx2(
68 const double* values, double* output, std::int64_t length, double p,
69 double inverse, double low, double high)
70{
71 const __m256d modulus = _mm256_set1_pd(p);
72 const __m256d reciprocal = _mm256_set1_pd(inverse);
73 const __m256d lower = _mm256_set1_pd(low);
74 const __m256d upper = _mm256_set1_pd(high);
75 const __m256d negative_zero = _mm256_set1_pd(-0.0);
76 std::int64_t q = 0;
77 for (; length - q >= 4; q += 4) {
78 __m256d residue;
79 GPR_SIGNED_RESIDUE_PACKET(residue, values + q);
80 _mm256_storeu_pd(output + q, residue);
81 }
82 return q;
83}
84
85__attribute__((target("avx2,fma"))) std::int64_t signedInt8ResiduesAvx2(
86 const double* values, std::int8_t* output, std::int64_t length, double p,
87 double inverse, double low, double high)
88{
89 const __m256d modulus = _mm256_set1_pd(p);
90 const __m256d reciprocal = _mm256_set1_pd(inverse);
91 const __m256d lower = _mm256_set1_pd(low);
92 const __m256d upper = _mm256_set1_pd(high);
93 const __m256d negative_zero = _mm256_set1_pd(-0.0);
94 std::int64_t q = 0;
95 for (; length - q >= 8; q += 8) {
96 __m256d first, second;
97 GPR_SIGNED_RESIDUE_PACKET(first, values + q);
98 GPR_SIGNED_RESIDUE_PACKET(second, values + q + 4);
99 // Centered residues lie in [-128, 127], so both packs are exact.
100 const __m128i first_ints = _mm256_cvttpd_epi32(first);
101 const __m128i second_ints = _mm256_cvttpd_epi32(second);
102 const __m128i words = _mm_packs_epi32(first_ints, second_ints);
103 const __m128i bytes = _mm_packs_epi16(words, _mm_setzero_si128());
104 _mm_storeu_si64(output + q, bytes);
105 }
106 return q;
107}
108#undef GPR_SIGNED_RESIDUE_PACKET
109#endif
110
111#if defined(__x86_64__) && defined(__GNUC__) && !defined(EIGEN_USE_BLAS) && \
112 !defined(EIGEN_USE_MKL_ALL)
113using Fp64ResidueKernel = void (*)(std::int64_t, const double*, std::int64_t,
114 const double*, std::int64_t, double*,
115 std::int64_t);
116
117// Registers hold independent output rows; each dot product advances through
118// the inner dimension in order. Only complete row vectors enter these kernels.
119#define GPR_FP64_RESIDUE_KERNEL(Name, Isa, Vector, Width, Load, Broadcast, \
120 Fma, Store) \
121 template <int Columns, int Rows> \
122 __attribute__((target(Isa))) void Name( \
123 std::int64_t depth, const double* left, std::int64_t left_stride, \
124 const double* right, std::int64_t right_stride, double* output, \
125 std::int64_t output_stride) \
126 { \
127 static_assert((Columns == 1 || Columns == 4) && \
128 (Rows == 1 || Rows == 2)); \
129 Vector sum00{}; \
130 [[maybe_unused]] Vector sum01{}, sum10{}, sum11{}, sum20{}, sum21{}, \
131 sum30{}, sum31{}; \
132 for (std::int64_t l = 0; l < depth; ++l) { \
133 const Vector a0 = Load(left + l * left_stride); \
134 [[maybe_unused]] Vector a1; \
135 if constexpr (Rows == 2) \
136 a1 = Load(left + Width + l * left_stride); \
137 const Vector b0 = Broadcast(right[l]); \
138 sum00 = Fma(a0, b0, sum00); \
139 if constexpr (Rows == 2) sum01 = Fma(a1, b0, sum01); \
140 if constexpr (Columns == 4) { \
141 const Vector b1 = Broadcast(right[l + right_stride]); \
142 const Vector b2 = Broadcast(right[l + 2 * right_stride]); \
143 const Vector b3 = Broadcast(right[l + 3 * right_stride]); \
144 sum10 = Fma(a0, b1, sum10); \
145 if constexpr (Rows == 2) sum11 = Fma(a1, b1, sum11); \
146 sum20 = Fma(a0, b2, sum20); \
147 if constexpr (Rows == 2) sum21 = Fma(a1, b2, sum21); \
148 sum30 = Fma(a0, b3, sum30); \
149 if constexpr (Rows == 2) sum31 = Fma(a1, b3, sum31); \
150 } \
151 } \
152 Store(output, sum00); \
153 if constexpr (Rows == 2) Store(output + Width, sum01); \
154 if constexpr (Columns == 4) { \
155 Store(output + output_stride, sum10); \
156 if constexpr (Rows == 2) \
157 Store(output + Width + output_stride, sum11); \
158 Store(output + 2 * output_stride, sum20); \
159 if constexpr (Rows == 2) \
160 Store(output + Width + 2 * output_stride, sum21); \
161 Store(output + 3 * output_stride, sum30); \
162 if constexpr (Rows == 2) \
163 Store(output + Width + 3 * output_stride, sum31); \
164 } \
165 }
166
167GPR_FP64_RESIDUE_KERNEL(fp64ResidueAvx2, "avx2,fma", __m256d, 4,
168 _mm256_loadu_pd, _mm256_set1_pd, _mm256_fmadd_pd,
169 _mm256_storeu_pd)
170GPR_FP64_RESIDUE_KERNEL(fp64ResidueAvx512, "avx512f,fma", __m512d, 8,
171 _mm512_loadu_pd, _mm512_set1_pd, _mm512_fmadd_pd,
172 _mm512_storeu_pd)
173#undef GPR_FP64_RESIDUE_KERNEL
174#endif
175
176// Prepared residues are integers with depth * max_abs(left) * max_abs(right)
177// at most 2^53. Every partial sum is exact, including fused accumulation.
178void fp64ResidueProduct(std::int64_t m, std::int64_t n, std::int64_t depth,
179 const double* left, std::int64_t left_stride,
180 const double* right, std::int64_t right_stride,
181 double* output)
182{
183#if defined(__x86_64__) && defined(__GNUC__) && !defined(EIGEN_USE_BLAS) && \
184 !defined(EIGEN_USE_MKL_ALL)
185 struct Kernels {
186 std::int64_t width;
187 Fp64ResidueKernel four_two, four_one, one_two, one_one;
188 };
189 static const Kernels avx2{4, fp64ResidueAvx2<4, 2>, fp64ResidueAvx2<4, 1>,
190 fp64ResidueAvx2<1, 2>, fp64ResidueAvx2<1, 1>};
191 static const Kernels avx512{
192 8, fp64ResidueAvx512<4, 2>, fp64ResidueAvx512<4, 1>,
193 fp64ResidueAvx512<1, 2>, fp64ResidueAvx512<1, 1>};
194 static const bool has_avx2 =
195 __builtin_cpu_supports("avx2") && __builtin_cpu_supports("fma");
196 static const bool has_avx512 =
197 has_avx2 && __builtin_cpu_supports("avx512f");
198 const Kernels* kernels = has_avx512 && m >= 16 ? &avx512
199 : has_avx2 && m >= 4 ? &avx2
200 : nullptr;
201 if (kernels) {
202 const auto columns = [&](std::int64_t j, int count) {
203 const auto two = count == 4 ? kernels->four_two : kernels->one_two;
204 const auto one = count == 4 ? kernels->four_one : kernels->one_one;
205 std::int64_t i = 0;
206 for (; m - i >= 2 * kernels->width; i += 2 * kernels->width)
207 two(depth, left + i, left_stride, right + j * right_stride,
208 right_stride, output + i + j * m, m);
209 if (m - i >= kernels->width) {
210 one(depth, left + i, left_stride, right + j * right_stride,
211 right_stride, output + i + j * m, m);
212 i += kernels->width;
213 }
214 if (kernels->width == 8 && m - i >= 4) {
215 const auto tail = count == 4 ? avx2.four_one : avx2.one_one;
216 tail(depth, left + i, left_stride, right + j * right_stride,
217 right_stride, output + i + j * m, m);
218 i += 4;
219 }
220 // Scalar rows keep every load inside its operand's active extent.
221 for (; i < m; ++i)
222 for (int column = 0; column < count; ++column) {
223 double sum = 0.0;
224 for (std::int64_t l = 0; l < depth; ++l)
225 sum = std::fma(left[i + l * left_stride],
226 right[l + (j + column) * right_stride],
227 sum);
228 output[i + (j + column) * m] = sum;
229 }
230 };
231 std::int64_t j = 0;
232 for (; n - j >= 4; j += 4)
233 columns(j, 4);
234 for (; j < n; ++j)
235 columns(j, 1);
236 return;
237 }
238#endif
239 using Map = Eigen::Map<const Eigen::MatrixXd, 0, Eigen::OuterStride<>>;
240 const Map a(left, m, depth, Eigen::OuterStride<>(left_stride));
241 const Map b(right, depth, n, Eigen::OuterStride<>(right_stride));
242 Eigen::Map<Eigen::MatrixXd> out(output, m, n);
243 out.noalias() = a * b;
244}
245
246// ---------------------------------------------------------------------------
247// Unsigned integers of arbitrary width, only for the setup of the moduli
248// tables (products, inverses, bounds). Little-endian 32-bit limbs.
249struct BigUInt {
250 std::vector<std::uint32_t> limb;
251
252 static BigUInt from(std::uint64_t value)
253 {
254 BigUInt r;
255 while (value) {
256 r.limb.push_back(static_cast<std::uint32_t>(value));
257 value >>= 32;
258 }
259 return r;
260 }
261 void trim()
262 {
263 while (!limb.empty() && limb.back() == 0)
264 limb.pop_back();
265 }
266 BigUInt times(std::uint64_t factor) const // factor < 2^32
267 {
268 BigUInt r;
269 std::uint64_t carry = 0;
270 for (const std::uint32_t l: limb) {
271 const std::uint64_t v = std::uint64_t{l} * factor + carry;
272 r.limb.push_back(static_cast<std::uint32_t>(v));
273 carry = v >> 32;
274 }
275 while (carry) {
276 r.limb.push_back(static_cast<std::uint32_t>(carry));
277 carry >>= 32;
278 }
279 r.trim();
280 return r;
281 }
282 // Quotient by a divisor below 2^32; remainder returned.
283 std::uint64_t divide(std::uint64_t divisor, BigUInt& quotient) const
284 {
285 quotient.limb.assign(limb.size(), 0);
286 std::uint64_t rem = 0;
287 for (std::size_t i = limb.size(); i-- > 0;) {
288 const std::uint64_t cur = (rem << 32) | limb[i];
289 quotient.limb[i] = static_cast<std::uint32_t>(cur / divisor);
290 rem = cur % divisor;
291 }
292 quotient.trim();
293 return rem;
294 }
295 BigUInt shifted(int bits) const
296 {
297 BigUInt r;
298 const int words = bits / 32, rest = bits % 32;
299 r.limb.assign(words, 0);
300 std::uint32_t carry = 0;
301 for (const std::uint32_t l: limb) {
302 r.limb.push_back(rest ? (l << rest) | carry : l);
303 carry = rest ? l >> (32 - rest) : 0;
304 }
305 if (carry) r.limb.push_back(carry);
306 r.trim();
307 return r;
308 }
309 BigUInt plus(const BigUInt& other) const
310 {
311 BigUInt r;
312 std::uint64_t carry = 0;
313 for (std::size_t i = 0; i < std::max(limb.size(), other.limb.size());
314 ++i) {
315 const std::uint64_t v =
316 carry + (i < limb.size() ? limb[i] : 0u) +
317 (i < other.limb.size() ? other.limb[i] : 0u);
318 r.limb.push_back(static_cast<std::uint32_t>(v));
319 carry = v >> 32;
320 }
321 if (carry) r.limb.push_back(static_cast<std::uint32_t>(carry));
322 r.trim();
323 return r;
324 }
325 int compare(const BigUInt& other) const
326 {
327 if (limb.size() != other.limb.size())
328 return limb.size() < other.limb.size() ? -1 : 1;
329 for (std::size_t i = limb.size(); i-- > 0;)
330 if (limb[i] != other.limb[i])
331 return limb[i] < other.limb[i] ? -1 : 1;
332 return 0;
333 }
334 std::uint64_t modulo(std::uint64_t divisor) const
335 {
336 BigUInt q;
337 return divide(divisor, q);
338 }
339 // Bits [first, first + count) as an integer, count <= 52.
340 std::uint64_t bits(int first, int count) const
341 {
342 std::uint64_t v = 0;
343 for (int b = 0; b < count; ++b) {
344 const int at = first + b;
345 const std::size_t word = static_cast<std::size_t>(at / 32);
346 if (word < limb.size() && ((limb[word] >> (at % 32)) & 1u))
347 v |= std::uint64_t{1} << b;
348 }
349 return v;
350 }
351 int bitLength() const
352 {
353 if (limb.empty()) return 0;
354 return static_cast<int>(32 * (limb.size() - 1)) +
355 std::bit_width(limb.back());
356 }
357 double log2() const
358 {
359 if (limb.empty()) return -std::numeric_limits<double>::infinity();
360 const int length = bitLength();
361 const int start = std::max(0, length - 52);
362 return std::log2(static_cast<double>(bits(start, length - start))) +
363 start;
364 }
365};
366
367std::uint64_t inverseModulo(std::uint64_t a, std::uint64_t p)
368{
369 // Extended Euclid on signed 64-bit; p < 2^32.
370 std::int64_t t = 0, new_t = 1;
371 std::int64_t r = static_cast<std::int64_t>(p),
372 new_r = static_cast<std::int64_t>(a % p);
373 while (new_r != 0) {
374 const std::int64_t q = r / new_r;
375 std::tie(t, new_t) = std::make_pair(new_t, t - q * new_t);
376 std::tie(r, new_r) = std::make_pair(new_r, r - q * new_r);
377 }
378 if (r != 1) throw std::logic_error("Scheme II moduli are not coprime");
379 return static_cast<std::uint64_t>(t < 0 ? t + static_cast<std::int64_t>(p)
380 : t);
381}
382
383bool isPrime(std::uint64_t value)
384{
385 if (value < 2) return false;
386 for (std::uint64_t d = 2; d * d <= value; ++d)
387 if (value % d == 0) return false;
388 return true;
389}
390
391// ---------------------------------------------------------------------------
392// Moduli tables.
393
394constexpr int kMaxModuli = 24;
395constexpr std::int64_t kInt8Chunk = 65536; // 128 * 255 * 2^16 < 2^31
396constexpr std::int64_t kFp64MaxChunk = 4096;
397
398// INT8: the largest pairwise coprime integers not above 256 (Section 3.1 of
399// arXiv:2504.08009), chosen greedily from 256 down. Their residues in the
400// symmetric range lie in [-128, 127].
401const std::vector<std::uint32_t>& int8Moduli()
402{
403 static const std::vector<std::uint32_t> table = [] {
404 std::vector<std::uint32_t> chosen;
405 for (std::uint32_t c = 256; c >= 2 && chosen.size() < kMaxModuli; --c)
406 if (std::all_of(chosen.begin(), chosen.end(), [&](std::uint32_t p) {
407 return std::gcd(p, c) == 1;
408 }))
409 chosen.push_back(c);
410 return chosen;
411 }();
412 return table;
413}
414
415// FP64: primes p with chunk ((p - 1) / 2)^2 <= 2^53, largest first (the
416// condition (20) of arXiv:2504.08009 written for symmetric residues). Every
417// partial sum of one GEMM over at most `chunk` terms is then an integer of
418// magnitude at most 2^53 and is exact in binary64.
419std::vector<std::uint32_t> fp64Moduli(std::int64_t chunk)
420{
421 const long double half = std::floor(
422 std::sqrt(std::ldexp(1.0L, 53) / static_cast<long double>(chunk)));
423 std::uint64_t p = static_cast<std::uint64_t>(2 * half + 1);
424 while (static_cast<long double>(chunk) * std::pow((p - 1) / 2.0L, 2) >
425 std::ldexp(1.0L, 53))
426 --p;
427 p = std::min<std::uint64_t>(p, (std::uint64_t{1} << 31) - 1);
428 std::vector<std::uint32_t> chosen;
429 for (; p > 2 && chosen.size() < kMaxModuli; --p)
430 if (isPrime(p)) chosen.push_back(static_cast<std::uint32_t>(p));
431 return chosen;
432}
433
434} // namespace
435
436std::int64_t engineChunk(Engine engine, std::int64_t k)
437{
438 return std::max<std::int64_t>(
439 1, std::min(k, engine == Engine::Int8 ? kInt8Chunk : kFp64MaxChunk));
440}
441
442std::vector<std::uint32_t> engineModuli(Engine engine, std::int64_t chunk)
443{
444 return engine == Engine::Int8 ? int8Moduli() : fp64Moduli(chunk);
445}
446
447int scaleExponent(double max_abs, int bits) noexcept
448{
449 if (!(max_abs > 0.0) || !std::isfinite(max_abs)) return 0;
450 // max_abs in [2^(E-1), 2^E); then max_abs 2^(bits-1-E) < 2^(bits-1).
451 const int e = std::ilogb(max_abs) + 1;
452 return bits - 1 - e;
453}
454
455bool isSpec(std::string_view spec) noexcept
456{
457 return spec.substr(0, 7) == "scheme2";
458}
459
460Options parseOptions(std::string_view spec)
461{
462 if (!isSpec(spec))
463 throw std::invalid_argument("not a Scheme II specification");
464 Options options;
465 std::vector<std::string> parts;
466 std::size_t start = 0;
467 while (start <= spec.size()) {
468 const std::size_t end = std::min(spec.find(':', start), spec.size());
469 parts.emplace_back(spec.substr(start, end - start));
470 start = end + 1;
471 }
472 if (parts.front() != "scheme2")
473 throw std::invalid_argument(
474 "Scheme II specification must start with scheme2");
475 bool engine_seen = false;
476 const auto integer = [](const std::string& text, const char* what) {
477 std::size_t used = 0;
478 const long value = std::stol(text, &used);
479 if (used != text.size() || value < 0)
480 throw std::invalid_argument(std::string("invalid Scheme II ") +
481 what);
482 return value;
483 };
484 for (std::size_t i = 1; i < parts.size(); ++i) {
485 const std::string& part = parts[i];
486 const std::size_t eq = part.find('=');
487 if (eq == std::string::npos) {
488 if (part == "fp64")
489 options.engine = Engine::Fp64;
490 else if (part == "int8")
491 options.engine = Engine::Int8;
492 else
493 throw std::invalid_argument("unknown Scheme II engine " + part);
494 engine_seen = true;
495 continue;
496 }
497 const std::string key = part.substr(0, eq), value = part.substr(eq + 1);
498 if (key == "bits")
499 options.bits = static_cast<int>(integer(value, "bits"));
500 else if (key == "moduli")
501 options.moduli = static_cast<int>(integer(value, "moduli"));
502 else if (key == "threads")
503 options.threads = static_cast<int>(integer(value, "threads"));
504 else if (key == "library")
505 options.library = value;
506 else if (key == "device")
507 options.device = static_cast<int>(integer(value, "device"));
508 else if (key == "device_min")
509 options.device_min =
510 static_cast<double>(integer(value, "device_min"));
511 else if (key == "block_rows")
512 options.block_rows = integer(value, "block_rows");
513 else if (key == "block_cols")
514 options.block_cols = integer(value, "block_cols");
515 else if (key == "provider") {
516 if (value == "auto")
518 else if (value == "builtin")
520 else if (value == "mkl")
521 options.provider = Int8Provider::Mkl;
522 else if (value == "onednn")
524 else if (value == "cuda")
526 else
527 throw std::invalid_argument("unknown INT8 provider " + value);
528 } else
529 throw std::invalid_argument("unknown Scheme II option " + key);
530 }
531 if (!engine_seen && parts.size() > 1 &&
532 parts[1].find('=') != std::string::npos)
533 options.engine = Engine::Fp64;
534 if (options.bits != 0 && (options.bits < 2 || options.bits > kMaxBits))
535 throw std::invalid_argument("Scheme II bits must lie in [2, 62]");
536 if (options.moduli > kMaxModuli)
537 throw std::invalid_argument("too many Scheme II moduli");
538 if (options.block_rows < 1 || options.block_cols < 1)
539 throw std::invalid_argument("invalid Scheme II block size");
540 return options;
541}
542
543// ---------------------------------------------------------------------------
544// INT8 GEMM providers. All compute the column-major INT32 product
545// C (m x n) = R (m x k, signed) * S (k x n), where S holds signed residues,
546// or unsigned residues in [0, p) when the provider wants them.
547
548namespace {
549
550struct Int8Gemm {
551 virtual ~Int8Gemm() = default;
552 [[nodiscard]] virtual bool unsignedColumns() const = 0;
553 [[nodiscard]] virtual std::string name() const = 0;
554 virtual void prepareThread() const { }
555 virtual void gemm(std::int64_t m, std::int64_t n, std::int64_t k,
556 const std::int8_t* r, std::int64_t ldr, const void* s,
557 std::int64_t lds, std::int32_t* c,
558 std::int64_t ldc) const = 0;
559};
560
561#if defined(__x86_64__) && defined(__GNUC__)
562// Signed products have magnitude at most 128 * 128. A chunk contains at
563// most 65536 terms, so every partial sum fits in [-2^30, 2^30].
564__attribute__((target("avx2"))) void builtinInt8Avx2(
565 std::int64_t m, std::int64_t n, std::int64_t k, const std::int8_t* r,
566 std::int64_t ldr, const std::int8_t* s, std::int64_t lds, std::int32_t* c,
567 std::int64_t ldc)
568{
569 for (std::int64_t j = 0; j < n; ++j) {
570 std::int32_t* out = c + j * ldc;
571 std::fill_n(out, m, 0);
572 for (std::int64_t l = 0; l < k; ++l) {
573 const std::int32_t b = s[l + j * lds];
574 if (b == 0) continue;
575 const std::int8_t* a = r + l * ldr;
576 const __m256i scale = _mm256_set1_epi32(b);
577 std::int64_t i = 0;
578 for (; m - i >= 8; i += 8) {
579 const __m256i values =
580 _mm256_cvtepi8_epi32(_mm_loadu_si64(a + i));
581 const __m256i sum = _mm256_loadu_si256(
582 reinterpret_cast<const __m256i_u*>(out + i));
583 _mm256_storeu_si256(
584 reinterpret_cast<__m256i_u*>(out + i),
585 _mm256_add_epi32(sum, _mm256_mullo_epi32(values, scale)));
586 }
587 for (; i < m; ++i)
588 out[i] += static_cast<std::int32_t>(a[i]) * b;
589 }
590 }
591}
592
593// The sixteen-row conversion and arithmetic require AVX512F; the
594// eight-row tail uses AVX2. Each byte load covers only its active rows.
595__attribute__((target("avx512f,avx2"))) void builtinInt8Avx512(
596 std::int64_t m, std::int64_t n, std::int64_t k, const std::int8_t* r,
597 std::int64_t ldr, const std::int8_t* s, std::int64_t lds, std::int32_t* c,
598 std::int64_t ldc)
599{
600 for (std::int64_t j = 0; j < n; ++j) {
601 std::int32_t* out = c + j * ldc;
602 std::fill_n(out, m, 0);
603 for (std::int64_t l = 0; l < k; ++l) {
604 const std::int32_t b = s[l + j * lds];
605 if (b == 0) continue;
606 const std::int8_t* a = r + l * ldr;
607 const __m512i scale = _mm512_set1_epi32(b);
608 std::int64_t i = 0;
609 for (; m - i >= 16; i += 16) {
610 const __m512i values = _mm512_cvtepi8_epi32(
611 _mm_loadu_si128(reinterpret_cast<const __m128i_u*>(a + i)));
612 const __m512i sum = _mm512_loadu_si512(out + i);
613 _mm512_storeu_si512(
614 out + i,
615 _mm512_add_epi32(sum, _mm512_mullo_epi32(values, scale)));
616 }
617 if (m - i >= 8) {
618 const __m256i values =
619 _mm256_cvtepi8_epi32(_mm_loadu_si64(a + i));
620 const __m256i sum = _mm256_loadu_si256(
621 reinterpret_cast<const __m256i_u*>(out + i));
622 _mm256_storeu_si256(
623 reinterpret_cast<__m256i_u*>(out + i),
624 _mm256_add_epi32(
625 sum, _mm256_mullo_epi32(values, _mm256_set1_epi32(b))));
626 i += 8;
627 }
628 for (; i < m; ++i)
629 out[i] += static_cast<std::int32_t>(a[i]) * b;
630 }
631 }
632}
633#endif
634
635// Portable exact kernel: one column of C at a time, k ascending; the
636// widening multiply-add vectorizes over the rows.
637struct BuiltinInt8 final : Int8Gemm {
638 bool unsignedColumns() const override
639 {
640 return false;
641 }
642 std::string name() const override
643 {
644 return "builtin";
645 }
646 void gemm(std::int64_t m, std::int64_t n, std::int64_t k,
647 const std::int8_t* r, std::int64_t ldr, const void* s_raw,
648 std::int64_t lds, std::int32_t* c,
649 std::int64_t ldc) const override
650 {
651 const auto* s = static_cast<const std::int8_t*>(s_raw);
652#if defined(__x86_64__) && defined(__GNUC__)
653 static const bool has_avx2 = __builtin_cpu_supports("avx2");
654 static const bool has_avx512 =
655 has_avx2 && __builtin_cpu_supports("avx512f");
656 if (has_avx512 && m >= 16) {
657 builtinInt8Avx512(m, n, k, r, ldr, s, lds, c, ldc);
658 return;
659 }
660 if (has_avx2 && m >= 8) {
661 builtinInt8Avx2(m, n, k, r, ldr, s, lds, c, ldc);
662 return;
663 }
664#endif
665 for (std::int64_t j = 0; j < n; ++j) {
666 std::int32_t* out = c + j * ldc;
667 std::fill_n(out, m, 0);
668 for (std::int64_t l = 0; l < k; ++l) {
669 const std::int32_t b = s[l + j * lds];
670 if (b == 0) continue;
671 const std::int8_t* a = r + l * ldr;
672 for (std::int64_t i = 0; i < m; ++i)
673 out[i] += static_cast<std::int32_t>(a[i]) * b;
674 }
675 }
676 }
677};
678
679void* openFirst(const std::string& requested,
680 std::initializer_list<const char*> defaults, std::string& used)
681{
682 if (!requested.empty()) {
683 void* handle = dlopen(requested.c_str(), RTLD_NOW | RTLD_LOCAL);
684 if (!handle) throw std::runtime_error(dlerror());
685 used = requested;
686 return handle;
687 }
688 for (const char* name: defaults) {
689 if (void* handle = dlopen(name, RTLD_NOW | RTLD_LOCAL)) {
690 used = name;
691 return handle;
692 }
693 }
694 return nullptr;
695}
696
697// oneDNN dnnl_gemm_s8s8s32 (row-major). The column-major product
698// C = R S is the row-major C^T = S^T R^T, so S is passed first.
699struct OnednnInt8 final : Int8Gemm {
700 using Fn = int (*)(char, char, char, std::int64_t, std::int64_t,
701 std::int64_t, float, const std::int8_t*, std::int64_t,
702 std::int8_t, const std::int8_t*, std::int64_t,
703 std::int8_t, float, std::int32_t*, std::int64_t,
704 const std::int32_t*);
705 void* handle = nullptr;
706 Fn fn = nullptr;
707 void (*set_threads)(int) = nullptr;
708 std::string path;
709
710 explicit OnednnInt8(const std::string& library)
711 {
712 handle = openFirst(library, {"libdnnl.so.3", "libdnnl.so"}, path);
713 if (!handle) throw std::runtime_error("oneDNN library not found");
714 fn = reinterpret_cast<Fn>(dlsym(handle, "dnnl_gemm_s8s8s32"));
715 if (!fn) throw std::runtime_error("oneDNN lacks dnnl_gemm_s8s8s32");
716 // The OpenMP runtime oneDNN was built with: each worker of the
717 // Scheme II pool runs a one-thread team.
718 set_threads = reinterpret_cast<void (*)(int)>(
719 dlsym(handle, "omp_set_num_threads"));
720 }
721 ~OnednnInt8() override
722 { /* kept loaded: OpenMP teams may hold it */
723 }
724 bool unsignedColumns() const override
725 {
726 return false;
727 }
728 std::string name() const override
729 {
730 return "onednn " + path;
731 }
732 void prepareThread() const override
733 {
734 if (set_threads) set_threads(1);
735 }
736 void gemm(std::int64_t m, std::int64_t n, std::int64_t k,
737 const std::int8_t* r, std::int64_t ldr, const void* s,
738 std::int64_t lds, std::int32_t* c,
739 std::int64_t ldc) const override
740 {
741 const std::int32_t zero = 0;
742 const int status =
743 fn('N', 'N', 'F', n, m, k, 1.0f, static_cast<const std::int8_t*>(s),
744 lds, 0, r, ldr, 0, 0.0f, c, ldc, &zero);
745 if (status != 0)
746 throw std::runtime_error("dnnl_gemm_s8s8s32 returned " +
747 std::to_string(status));
748 }
749};
750
751// MKL cblas_gemm_s8u8s32. One operand is unsigned; which one depends on the
752// layout, so the layout is probed once and the column residues are stored
753// unsigned.
754//
755// MKL is reached only through the shim libgpr_scheme2_mkl.so, which lists
756// the LP64 interface, sequential threading and core libraries as its own
757// dependencies. Opened with RTLD_LOCAL, their symbols stay in the shim's
758// local scope. libmkl_rt instead loads those libraries into the global
759// scope, where the MKL dgemm_, dpotrf_ and the rest would answer every later
760// lookup from ScaLAPACK or LAPACKE and change arithmetic that never passes
761// through Scheme II; it is refused.
762struct MklInt8 final : Int8Gemm {
763 // The LP64 interface: MKL_INT is int.
764 using Fn = void (*)(int, int, int, int, int, int, int, float, const void*,
765 int, std::int8_t, const void*, int, std::int8_t, float,
766 std::int32_t*, int, const std::int32_t*);
767 static constexpr int kColMajor = 102, kRowMajor = 101, kNoTrans = 111,
768 kFixOffset = 173;
769 void* handle = nullptr;
770 Fn fn = nullptr;
771 bool row_major_swap = false; // column residues as MKL's A operand
772 std::string path;
773
774 explicit MklInt8(const std::string& library)
775 {
776 if (library.find("mkl_rt") != std::string::npos)
777 throw std::invalid_argument(
778 "libmkl_rt loads MKL's BLAS into the global symbol scope; "
779 "select the libgpr_scheme2_mkl.so shim instead");
780 handle = openFirst(library, {"libgpr_scheme2_mkl.so"}, path);
781 if (!handle) throw std::runtime_error("MKL shim library not found");
782 fn = reinterpret_cast<Fn>(dlsym(handle, "cblas_gemm_s8u8s32"));
783 if (!fn) throw std::runtime_error("MKL lacks cblas_gemm_s8u8s32");
784 // Probe: a row residue byte 0xFF must read -1 and a column residue
785 // byte 0xFF must read 255.
786 const std::uint8_t ff = 0xFF, one = 0x01;
787 const std::int32_t zero = 0;
788 for (const bool swap: {false, true}) {
789 std::int32_t row_signed = 0, column_unsigned = 0;
790 call(swap, 1, 1, 1, &ff, 1, &one, 1, &row_signed, 1, &zero);
791 call(swap, 1, 1, 1, &one, 1, &ff, 1, &column_unsigned, 1, &zero);
792 if (row_signed == -1 && column_unsigned == 255) {
793 row_major_swap = swap;
794 return;
795 }
796 }
797 throw std::runtime_error("cblas_gemm_s8u8s32 signedness probe failed");
798 }
799 void call(bool swap, std::int64_t m, std::int64_t n, std::int64_t k,
800 const void* r, std::int64_t ldr, const void* s, std::int64_t lds,
801 std::int32_t* c, std::int64_t ldc, const std::int32_t* zero) const
802 {
803 constexpr std::int64_t limit = std::numeric_limits<int>::max();
804 if (std::max({m, n, k, ldr, lds, ldc}) > limit)
805 throw std::length_error("MKL LP64 dimension overflow");
806 const auto i = [](std::int64_t v) { return static_cast<int>(v); };
807 if (!swap)
808 fn(kColMajor, kNoTrans, kNoTrans, kFixOffset, i(m), i(n), i(k),
809 1.0f, r, i(ldr), 0, s, i(lds), 0, 0.0f, c, i(ldc), zero);
810 else
811 fn(kRowMajor, kNoTrans, kNoTrans, kFixOffset, i(n), i(m), i(k),
812 1.0f, s, i(lds), 0, r, i(ldr), 0, 0.0f, c, i(ldc), zero);
813 }
814 bool unsignedColumns() const override
815 {
816 return true;
817 }
818 std::string name() const override
819 {
820 return "mkl " + path;
821 }
822 void gemm(std::int64_t m, std::int64_t n, std::int64_t k,
823 const std::int8_t* r, std::int64_t ldr, const void* s,
824 std::int64_t lds, std::int32_t* c,
825 std::int64_t ldc) const override
826 {
827 const std::int32_t zero = 0;
828 call(row_major_swap, m, n, k, r, ldr, s, lds, c, ldc, &zero);
829 }
830};
831
832// INT8 tensor cores through libgpr_scheme2_cuda.so (CudaEngine.h). gemm()
833// serves single block products (Context::residues); Context::run hands
834// whole tasks to run() instead, so a run crosses the bus once per operand.
835struct CudaInt8 final : Int8Gemm {
836 void* handle = nullptr;
837 void* engine = nullptr;
838 std::string path, device;
839 decltype(&gpr_scheme2_cuda_destroy_v1) destroy = nullptr;
840 decltype(&gpr_scheme2_cuda_run_v1) run_fn = nullptr;
841 decltype(&gpr_scheme2_cuda_gemm_s8_v1) gemm_fn = nullptr;
842
843 CudaInt8(const std::string& library, int device_index)
844 {
845 handle = openFirst(library, {"libgpr_scheme2_cuda.so"}, path);
846 if (!handle)
847 throw std::runtime_error("CUDA Scheme II library not found");
848 const auto create =
849 reinterpret_cast<decltype(&gpr_scheme2_cuda_create_v1)>(
850 dlsym(handle, "gpr_scheme2_cuda_create_v1"));
851 const auto describe =
852 reinterpret_cast<decltype(&gpr_scheme2_cuda_describe_v1)>(
853 dlsym(handle, "gpr_scheme2_cuda_describe_v1"));
854 destroy = reinterpret_cast<decltype(&gpr_scheme2_cuda_destroy_v1)>(
855 dlsym(handle, "gpr_scheme2_cuda_destroy_v1"));
856 run_fn = reinterpret_cast<decltype(&gpr_scheme2_cuda_run_v1)>(
857 dlsym(handle, "gpr_scheme2_cuda_run_v1"));
858 gemm_fn = reinterpret_cast<decltype(&gpr_scheme2_cuda_gemm_s8_v1)>(
859 dlsym(handle, "gpr_scheme2_cuda_gemm_s8_v1"));
860 if (!create || !describe || !destroy || !run_fn || !gemm_fn)
861 throw std::runtime_error("incompatible CUDA Scheme II library");
862 char error[1024]{};
863 engine = create(device_index, error, sizeof(error));
864 if (!engine) throw std::runtime_error(error);
865 char text[256]{};
866 describe(engine, text, sizeof(text));
867 device = text;
868 }
869 ~CudaInt8() override
870 {
871 if (engine) destroy(engine);
872 // The CUDA runtime stays loaded: its teardown at exit expects it.
873 }
874 bool unsignedColumns() const override
875 {
876 return false;
877 }
878 std::string name() const override
879 {
880 return "cuda " + device;
881 }
882 void gemm(std::int64_t m, std::int64_t n, std::int64_t k,
883 const std::int8_t* r, std::int64_t ldr, const void* s,
884 std::int64_t lds, std::int32_t* c,
885 std::int64_t ldc) const override
886 {
887 char error[1024]{};
888 if (gemm_fn(engine, m, n, k, r, ldr, static_cast<const std::int8_t*>(s),
889 lds, c, ldc, error, sizeof(error)))
890 throw std::runtime_error(error);
891 }
892};
893
894std::unique_ptr<Int8Gemm> makeInt8(const Options& options)
895{
896 switch (options.provider) {
898 return std::make_unique<BuiltinInt8>();
900 return std::make_unique<MklInt8>(options.library);
902 return std::make_unique<OnednnInt8>(options.library);
904 return std::make_unique<CudaInt8>(options.library, options.device);
906 break;
907 }
908 try {
909 return std::make_unique<MklInt8>(options.library);
910 } catch (const std::exception&) {
911 }
912 try {
913 return std::make_unique<OnednnInt8>(options.library);
914 } catch (const std::exception&) {
915 }
916 return std::make_unique<BuiltinInt8>();
917}
918
919// OpenBLAS keeps its thread count in a global; the pool calls BLAS from its
920// own workers, each with one BLAS thread.
921struct BlasThreads {
922 void (*set)(int) = nullptr;
923 int (*get)() = nullptr;
924 BlasThreads()
925 {
926 set = reinterpret_cast<void (*)(int)>(
927 dlsym(RTLD_DEFAULT, "openblas_set_num_threads"));
928 get = reinterpret_cast<int (*)()>(
929 dlsym(RTLD_DEFAULT, "openblas_get_num_threads"));
930 }
931};
932
933const BlasThreads& blasThreads()
934{
935 static const BlasThreads threads;
936 return threads;
937}
938
939} // namespace
940
941// ---------------------------------------------------------------------------
942
943namespace {
944enum class Phase {
945 Prepare,
946 Gemm,
947 Reduce,
948 Reconstruct,
949 PrepareWall,
950 RunWall,
951 Count
952};
953
954// Thread-seconds per phase, collected when GPR_SCHEME2_PROFILE is set and
955// printed when the context is destroyed.
956struct Profile {
957 bool enabled = false;
958 std::atomic<std::int64_t> nanoseconds[static_cast<int>(Phase::Count)]{};
959 std::atomic<std::int64_t> products{0};
960};
961
962class PhaseTimer {
963public:
964 PhaseTimer(const Profile& profile, Phase phase)
965 : profile_(profile.enabled ? &const_cast<Profile&>(profile) : nullptr),
966 phase_(phase)
967 {
968 if (profile_) start_ = std::chrono::steady_clock::now();
969 }
970 ~PhaseTimer()
971 {
972 if (!profile_) return;
973 profile_->nanoseconds[static_cast<int>(phase_)] +=
974 std::chrono::duration_cast<std::chrono::nanoseconds>(
975 std::chrono::steady_clock::now() - start_)
976 .count();
977 }
978 PhaseTimer(const PhaseTimer&) = delete;
979 PhaseTimer& operator=(const PhaseTimer&) = delete;
980
981private:
982 Profile* profile_;
983 Phase phase_;
984 std::chrono::steady_clock::time_point start_;
985};
986} // namespace
987
989 bool rows = true; // row operand (m x k) or column operand (k x n)
990 std::int64_t extent = 0, depth = 0;
991 std::int64_t plan_k = 0; // inner dimension of the plan
992 int moduli = 0;
993 std::vector<int> exponents;
994 std::vector<double> f64; // Engine::Fp64 residues
995 std::vector<std::int8_t> i8; // Engine::Int8 residues
996 // Column residues for a provider with unsigned columns, in [0, p).
997 bool unsigned_values = false;
998 // provider=cuda: the operand values instead of residues, in the
999 // orientation of the source: element (e, l) at source[l * ld + e], or at
1000 // source[e * ld + l] when l_contiguous. `source` points into `values`, or
1001 // into the caller's matrix for the operands of one Context::gemm call.
1002 // The device forms the residues; the host forms them (into i8) only
1003 // when a single block product asks for them.
1004 bool deferred = false;
1005 bool l_contiguous = false;
1006 const double* source = nullptr;
1007 std::int64_t source_ld = 0;
1008 std::vector<double> values;
1010 std::size_t stride() const
1011 {
1012 return static_cast<std::size_t>(extent * depth);
1013 }
1014};
1015
1016Operand::Operand() = default;
1017Operand::Operand(Operand&&) noexcept = default;
1018Operand& Operand::operator=(Operand&&) noexcept = default;
1019Operand::~Operand() = default;
1020std::int64_t Operand::extent() const noexcept
1021{
1022 return data_ ? data_->extent : 0;
1023}
1024std::int64_t Operand::depth() const noexcept
1025{
1026 return data_ ? data_->depth : 0;
1027}
1028const std::vector<int>& Operand::exponents() const noexcept
1029{
1030 static const std::vector<int> none;
1031 return data_ ? data_->exponents : none;
1032}
1033std::size_t Operand::bytes() const noexcept
1034{
1035 return data_ ? (data_->f64.size() + data_->values.size()) * sizeof(double) +
1036 data_->i8.size()
1037 : 0;
1038}
1039
1042 std::unique_ptr<Int8Gemm> int8;
1043 int (*thread_source)() = nullptr;
1044 mutable Profile profile;
1045 // GPR_SCHEME2_VERIFY: every INT8 provider product is compared with an
1046 // INT64 evaluation; a mismatch throws with its shape.
1047 bool verify = false;
1048
1049 static void verifyInt8(std::int64_t m, std::int64_t n, std::int64_t k,
1050 const std::int8_t* r, std::int64_t ldr,
1051 const std::int8_t* s, std::int64_t lds,
1052 bool unsigned_columns, const std::int32_t* c)
1053 {
1054 for (std::int64_t j = 0; j < n; ++j)
1055 for (std::int64_t i = 0; i < m; ++i) {
1056 std::int64_t sum = 0;
1057 for (std::int64_t l = 0; l < k; ++l) {
1058 const std::int64_t b =
1059 unsigned_columns
1060 ? static_cast<std::int64_t>(
1061 static_cast<std::uint8_t>(s[l + j * lds]))
1062 : static_cast<std::int64_t>(s[l + j * lds]);
1063 sum += static_cast<std::int64_t>(r[i + l * ldr]) * b;
1064 }
1065 if (sum != c[i + j * m])
1066 throw std::runtime_error(
1067 "INT8 provider product differs at (" +
1068 std::to_string(i) + ", " + std::to_string(j) +
1069 ") of m=" + std::to_string(m) +
1070 " n=" + std::to_string(n) + " k=" + std::to_string(k) +
1071 " ldr=" + std::to_string(ldr) +
1072 " lds=" + std::to_string(lds) + ": " +
1073 std::to_string(c[i + j * m]) + " for " +
1074 std::to_string(sum));
1075 }
1076 }
1077
1079 {
1080 if (!profile.enabled) return;
1081 const char* names[] = {"prepare", "gemm", "reduce",
1082 "reconstruct", "prepare_wall", "run_wall"};
1083 std::fprintf(stderr, "[scheme2] runs=%lld",
1084 static_cast<long long>(profile.products.load()));
1085 for (int i = 0; i < static_cast<int>(Phase::Count); ++i)
1086 std::fprintf(stderr, " %s=%.3fs", names[i],
1087 profile.nanoseconds[i].load() * 1e-9);
1088 std::fprintf(stderr, " (thread-seconds)\n");
1089 }
1090
1091 struct Table {
1093 int beta_bits = 0; // limb width of the CRT weights
1094 int limbs = 0;
1095 std::vector<double> weight; // weight[t * limbs + j]
1096 std::vector<double> modulus; // limbs of M
1097 double inverse_modulus = 0.0;
1098 std::vector<double> inverse_p;
1099 };
1100 mutable std::mutex tables_mutex;
1101 mutable std::vector<std::shared_ptr<const Table>> tables;
1102
1103 int threads() const
1104 {
1105 if (options.threads > 0) return options.threads;
1106 return thread_source ? std::max(1, thread_source()) : 1;
1107 }
1108
1109 std::shared_ptr<const Table> table(std::int64_t k) const
1110 {
1111 const std::int64_t chunk = engineChunk(options.engine, k);
1112 std::lock_guard lock(tables_mutex);
1113 for (const auto& t: tables)
1114 if (t->plan.k == k) return t;
1115 auto t = std::make_shared<Table>(build(k, chunk));
1116 tables.push_back(t);
1117 return t;
1118 }
1119
1120 Table build(std::int64_t k, std::int64_t chunk) const
1121 {
1122 const std::vector<std::uint32_t> all =
1123 engineModuli(options.engine, chunk);
1124 const auto product = [&](int count) {
1125 BigUInt m = BigUInt::from(1);
1126 for (int i = 0; i < count; ++i)
1127 m = m.times(all[static_cast<std::size_t>(i)]);
1128 return m;
1129 };
1130 // Unique reconstruction with a margin for the floating-point
1131 // quotient estimate: 2 k 2^(2 bits - 2) (1 + 2^-16) < M.
1132 const auto supports = [&](int bits, const BigUInt& m) {
1133 const BigUInt bound = BigUInt::from(static_cast<std::uint64_t>(k))
1134 .shifted(2 * bits - 1);
1135 return bound.shifted(16).plus(bound).compare(m.shifted(16)) < 0;
1136 };
1137 int count = options.moduli;
1138 int bits = options.bits;
1139 if (count == 0) {
1140 if (bits == 0) bits = kDefaultBits;
1141 count = 1;
1142 while (count <= static_cast<int>(all.size()) &&
1143 !supports(bits, product(count)))
1144 ++count;
1145 if (count > static_cast<int>(all.size()))
1146 throw std::invalid_argument(
1147 "Scheme II moduli cannot support the requested bits");
1148 } else {
1149 if (count > static_cast<int>(all.size()))
1150 throw std::invalid_argument("too many Scheme II moduli");
1151 const BigUInt m = product(count);
1152 if (bits == 0) {
1153 bits = kMaxBits;
1154 while (bits >= 2 && !supports(bits, m))
1155 --bits;
1156 if (bits < 2)
1157 throw std::invalid_argument("too few Scheme II moduli");
1158 } else if (!supports(bits, m))
1159 throw std::invalid_argument(
1160 "Scheme II moduli cannot support the requested bits");
1161 }
1162 Table t;
1163 t.plan.bits = bits;
1164 t.plan.k = k;
1165 t.plan.chunk = chunk;
1166 t.plan.moduli.assign(all.begin(), all.begin() + count);
1167 const BigUInt m = product(count);
1168 t.plan.log2_modulus_product = m.log2();
1169 // Limb width beta: N p_max 2^beta <= 2^52 keeps every limb sum
1170 // T_j = sum_t r_t w_tj, and T_j - q M_j, exact in binary64 with one
1171 // bit to spare for the carries.
1172 const int log_n = std::bit_width(static_cast<unsigned>(count - 1));
1173 const int log_p = std::bit_width(t.plan.moduli.front() - 1u);
1174 t.beta_bits = 52 - log_n - log_p;
1175 t.limbs = (m.bitLength() + t.beta_bits - 1) / t.beta_bits;
1176 t.weight.resize(static_cast<std::size_t>(count * t.limbs));
1177 for (int i = 0; i < count; ++i) {
1178 const std::uint32_t p = t.plan.moduli[static_cast<std::size_t>(i)];
1179 BigUInt cofactor;
1180 m.divide(p, cofactor);
1181 const std::uint64_t y = inverseModulo(cofactor.modulo(p), p);
1182 const BigUInt w = cofactor.times(y); // < M
1183 for (int j = 0; j < t.limbs; ++j)
1184 t.weight[static_cast<std::size_t>(i * t.limbs + j)] =
1185 static_cast<double>(w.bits(j * t.beta_bits, t.beta_bits));
1186 }
1187 t.modulus.resize(static_cast<std::size_t>(t.limbs));
1188 for (int j = 0; j < t.limbs; ++j)
1189 t.modulus[static_cast<std::size_t>(j)] =
1190 static_cast<double>(m.bits(j * t.beta_bits, t.beta_bits));
1191 t.inverse_modulus = std::exp2(-t.plan.log2_modulus_product);
1192 for (const std::uint32_t p: t.plan.moduli)
1193 t.inverse_p.push_back(1.0 / p);
1194 return t;
1195 }
1196
1197 // ---- operand preparation ------------------------------------------------
1198
1199 Operand prepare(bool rows, const double* x, std::int64_t ld, bool transpose,
1200 std::int64_t extent, std::int64_t depth, const Plan& plan,
1201 const int* exponents, bool host_residues = false,
1202 bool borrow = false) const
1203 {
1204 if (extent < 0 || depth < 0 || (extent * depth > 0 && !x))
1205 throw std::invalid_argument("invalid Scheme II operand");
1206 const PhaseTimer timer(profile, Phase::PrepareWall);
1207 // Element (e, l): e indexes rows of op(A) or columns of op(B), l the
1208 // inner dimension. Row operand: op(A)(e, l), which is A(e, l) or
1209 // A(l, e). Column operand: op(B)(l, e), which is B(l, e) or B(e, l).
1210 // `contiguous_e` says whether consecutive e are adjacent in memory.
1211 const bool element_major = rows ? transpose : !transpose;
1212 const auto at = [&](std::int64_t e, std::int64_t l) {
1213 return element_major ? x[l + e * ld] : x[e + l * ld];
1214 };
1215 Operand out;
1216 out.data_ = std::make_unique<Operand::Data>();
1217 auto& d = *out.data_;
1218 d.rows = rows;
1219 d.extent = extent;
1220 d.depth = depth;
1221 d.moduli = static_cast<int>(plan.moduli.size());
1222 d.plan_k = plan.k;
1223 if (table(plan.k)->plan.moduli != plan.moduli || depth > plan.k)
1224 throw std::invalid_argument("Scheme II plan from another context");
1225 d.exponents.resize(static_cast<std::size_t>(extent));
1226 const int count = d.moduli;
1227 const bool int8_engine = options.engine == Engine::Int8;
1228 d.unsigned_values = int8_engine && !rows && int8->unsignedColumns();
1229 d.deferred = int8_engine && options.provider == Int8Provider::Cuda &&
1230 !host_residues;
1231 if (d.deferred)
1232 d.l_contiguous = element_major;
1233 else if (int8_engine)
1234 d.i8.resize(static_cast<std::size_t>(count) * d.stride());
1235 else
1236 d.f64.resize(static_cast<std::size_t>(count) * d.stride());
1237 if (extent == 0 || depth == 0) return out;
1238 const int threads = this->threads();
1239
1240 // Pass 1: the exponent of every row of op(A) or column of op(B).
1241 // Maxima of slices of the inner dimension are combined afterwards;
1242 // a maximum does not depend on the order of its terms.
1243 if (exponents) {
1244 std::copy_n(exponents, extent, d.exponents.begin());
1245 } else {
1246 const std::int64_t e_span = 512;
1247 const long e_pieces =
1248 static_cast<long>((extent + e_span - 1) / e_span);
1249 const long wanted = 4L * threads;
1250 const long l_pieces = static_cast<long>(std::clamp<std::int64_t>(
1251 (wanted + e_pieces - 1) / e_pieces, 1, (depth + 255) / 256));
1252 const std::int64_t l_span = (depth + l_pieces - 1) / l_pieces;
1253 std::vector<double> partial(
1254 static_cast<std::size_t>(l_pieces * extent), 0.0);
1255 std::atomic<bool> finite{true};
1257 threads, e_pieces * l_pieces, [&](long piece) {
1258 const PhaseTimer piece_timer(profile, Phase::Prepare);
1259 const long ep = piece % e_pieces, lp = piece / e_pieces;
1260 const std::int64_t first = ep * e_span;
1261 const std::int64_t count_e =
1262 std::min(extent, first + e_span) - first;
1263 const std::int64_t l0 = lp * l_span;
1264 const std::int64_t l1 = std::min(depth, l0 + l_span);
1265 double* largest = partial.data() + static_cast<std::size_t>(
1266 lp * extent + first);
1267 bool ok = true;
1268 if (element_major) {
1269 for (std::int64_t q = 0; q < count_e; ++q) {
1270 const double* v = x + (first + q) * ld;
1271 double big = 0.0;
1272 for (std::int64_t l = l0; l < l1; ++l) {
1273 ok = ok & std::isfinite(v[l]);
1274 big = std::max(big, std::abs(v[l]));
1275 }
1276 largest[q] = big;
1277 }
1278 } else {
1279 for (std::int64_t l = l0; l < l1; ++l) {
1280 const double* v = x + first + l * ld;
1281 for (std::int64_t q = 0; q < count_e; ++q) {
1282 ok = ok & std::isfinite(v[q]);
1283 largest[q] =
1284 std::max(largest[q], std::abs(v[q]));
1285 }
1286 }
1287 }
1288 if (!ok) finite = false;
1289 });
1290 if (!finite)
1291 throw std::invalid_argument("nonfinite Scheme II operand");
1292 for (std::int64_t e = 0; e < extent; ++e) {
1293 double big = 0.0;
1294 for (long lp = 0; lp < l_pieces; ++lp)
1295 big = std::max(
1296 big,
1297 partial[static_cast<std::size_t>(lp * extent + e)]);
1298 d.exponents[static_cast<std::size_t>(e)] =
1299 scaleExponent(big, plan.bits);
1300 }
1301 }
1302
1303 // Pass 2: scaled integers and their residues, one storage column at
1304 // a time. A row operand is stored m x k (storage column l), a column
1305 // operand k x n (storage column e).
1306 const std::int64_t length = rows ? extent : depth; // storage rows
1307 const std::int64_t columns = rows ? depth : extent; // storage columns
1308 const std::int64_t group = std::max<std::int64_t>(
1309 1, 16384 / std::max<std::int64_t>(1, length));
1310 const long pieces = static_cast<long>((columns + group - 1) / group);
1311 const double limit = std::ldexp(1.0, plan.bits - 1);
1312 // 2^s as two exact factors, so |s| up to about 2000 stays finite.
1313 std::vector<double> half_scale(static_cast<std::size_t>(extent)),
1314 rest_scale(static_cast<std::size_t>(extent));
1315 for (std::int64_t e = 0; e < extent; ++e) {
1316 const int sh = d.exponents[static_cast<std::size_t>(e)];
1317 const int h = sh / 2;
1318 half_scale[static_cast<std::size_t>(e)] = std::ldexp(1.0, h);
1319 rest_scale[static_cast<std::size_t>(e)] = std::ldexp(1.0, sh - h);
1320 }
1321 if (d.deferred) {
1322 // The values in the orientation of the source, compacted unless
1323 // borrowed; exponents supplied by the caller are checked here as
1324 // the residue pass would check them.
1325 const std::int64_t outer = element_major ? extent : depth;
1326 const std::int64_t inner = element_major ? depth : extent;
1327 if (borrow) {
1328 d.source = x;
1329 d.source_ld = ld;
1330 } else {
1331 d.values.resize(d.stride());
1332 d.source = d.values.data();
1333 d.source_ld = inner;
1334 }
1335 const std::int64_t span = std::max<std::int64_t>(
1336 1, 65536 / std::max<std::int64_t>(1, inner));
1337 const long parts = static_cast<long>((outer + span - 1) / span);
1338 std::atomic<bool> within_all{true};
1339 TilePool::instance().runWith(threads, parts, [&](long part) {
1340 const PhaseTimer piece_timer(profile, Phase::Prepare);
1341 const std::int64_t first = part * span;
1342 const std::int64_t last = std::min(outer, first + span);
1343 bool within = true;
1344 for (std::int64_t o = first; o < last; ++o) {
1345 const double* in = x + o * ld;
1346 if (!borrow)
1347 std::copy_n(in, inner,
1348 d.values.data() +
1349 static_cast<std::size_t>(o * inner));
1350 if (!exponents) continue;
1351 for (std::int64_t q = 0; q < inner; ++q) {
1352 const std::size_t e =
1353 static_cast<std::size_t>(element_major ? o : q);
1354 within = within &
1355 (std::abs(std::rint(in[q] * half_scale[e] *
1356 rest_scale[e])) <= limit);
1357 }
1358 }
1359 if (!within) within_all = false;
1360 });
1361 if (!within_all)
1362 throw std::invalid_argument(
1363 "Scheme II operand exceeds its scale exponent");
1364 return out;
1365 }
1366 TilePool::instance().runWith(threads, pieces, [&](long piece) {
1367 const PhaseTimer piece_timer(profile, Phase::Prepare);
1368 std::vector<double>& y = scratch();
1369 y.resize(static_cast<std::size_t>(length));
1370 const std::int64_t first = piece * group;
1371 const std::int64_t last = std::min(columns, first + group);
1372 for (std::int64_t col = first; col < last; ++col) {
1373 bool within = true;
1374 if (rows) {
1375 // y[e] = A'(e, l) for l = col.
1376 const std::int64_t l = col;
1377 for (std::int64_t e = 0; e < length; ++e) {
1378 const double v = at(e, l);
1379 const double scaled = std::rint(
1380 v * half_scale[static_cast<std::size_t>(e)] *
1381 rest_scale[static_cast<std::size_t>(e)]);
1382 within = within & (std::abs(scaled) <= limit);
1383 y[static_cast<std::size_t>(e)] = scaled;
1384 }
1385 } else {
1386 // y[l] = B'(l, e) for e = col.
1387 const std::int64_t e = col;
1388 const double f1 = half_scale[static_cast<std::size_t>(e)];
1389 const double f2 = rest_scale[static_cast<std::size_t>(e)];
1390 for (std::int64_t l = 0; l < length; ++l) {
1391 const double scaled = std::rint(at(e, l) * f1 * f2);
1392 within = within & (std::abs(scaled) <= limit);
1393 y[static_cast<std::size_t>(l)] = scaled;
1394 }
1395 }
1396 if (!within)
1397 throw std::invalid_argument(
1398 "Scheme II operand exceeds its scale exponent");
1399 for (int t = 0; t < count; ++t) {
1400 const double p = plan.moduli[static_cast<std::size_t>(t)];
1401 const double inverse = 1.0 / p;
1402 const double low = -std::floor(p / 2); // symmetric range
1403 const double high = p - 1 + low;
1404 const std::size_t base =
1405 static_cast<std::size_t>(t) * d.stride() +
1406 static_cast<std::size_t>(col * length);
1407 // r = y - p round(y / p) twice: the first step leaves a
1408 // few p, the second is exact. fma returns y - q p exactly
1409 // because the true value is a small integer.
1410 if (int8_engine) {
1411 std::int8_t* out_i8 = d.i8.data() + base;
1412 const bool positive = d.unsigned_values;
1413 std::int64_t q = 0;
1414#if defined(__x86_64__) && defined(__GNUC__)
1415 if (!positive && length >= 8 &&
1416 signedResidueSimdAvailable())
1417 q = signedInt8ResiduesAvx2(y.data(), out_i8, length,
1418 p, inverse, low, high);
1419#endif
1420 for (; q < length; ++q) {
1421 const double v = y[static_cast<std::size_t>(q)];
1422 double r = std::fma(-std::rint(v * inverse), p, v);
1423 r = std::fma(-std::rint(r * inverse), p, r);
1424 if (positive)
1425 r = r < 0.0 ? r + p : r;
1426 else {
1427 r = r > high ? r - p : r;
1428 r = r < low ? r + p : r;
1429 }
1430 out_i8[q] = static_cast<std::int8_t>(
1431 static_cast<std::uint8_t>(static_cast<int>(r)));
1432 }
1433 } else {
1434 double* out_f64 = d.f64.data() + base;
1435 std::int64_t q = 0;
1436#if defined(__x86_64__) && defined(__GNUC__)
1437 if (length >= 4 && signedResidueSimdAvailable())
1438 q = signedFp64ResiduesAvx2(y.data(), out_f64,
1439 length, p, inverse, low,
1440 high);
1441#endif
1442 for (; q < length; ++q) {
1443 const double v = y[static_cast<std::size_t>(q)];
1444 double r = std::fma(-std::rint(v * inverse), p, v);
1445 r = std::fma(-std::rint(r * inverse), p, r);
1446 r = r > high ? r - p : r;
1447 r = r < low ? r + p : r;
1448 out_f64[q] = r;
1449 }
1450 }
1451 }
1452 }
1453 });
1454 return out;
1455 }
1456
1457 // Host residues of a deferred operand, formed once from its values and
1458 // exponents by the residue pass of prepare().
1459 void materialize(const Operand::Data& d) const
1460 {
1461 if (!d.deferred) return;
1462 auto& m = const_cast<Operand::Data&>(d);
1463 std::lock_guard lock(m.materialize_mutex);
1464 if (!m.i8.empty() || m.stride() == 0) return;
1465 const Plan plan = table(d.plan_k)->plan;
1466 // Rows read op(A)(e, l) l-contiguously when transposed, columns
1467 // read op(B)(l, e) l-contiguously when not transposed.
1468 const bool transpose = d.rows ? d.l_contiguous : !d.l_contiguous;
1469 const Operand host =
1470 prepare(d.rows, d.source, d.source_ld, transpose, d.extent, d.depth,
1471 plan, d.exponents.data(), true);
1472 m.i8 = std::move(host.data_->i8);
1473 }
1474
1475 static std::vector<double>& scratch()
1476 {
1477 thread_local std::vector<double> buffer;
1478 return buffer;
1479 }
1480
1481 // ---- block products
1482 // -------------------------------------------------------
1483
1484 struct Workspace {
1485 std::vector<double> residue; // N x (m x n)
1486 std::vector<double> product; // m x n
1487 std::vector<std::int32_t> integer; // m x n
1488 std::vector<double> limbs; // L x m
1489 };
1490
1492 {
1493 thread_local Workspace w;
1494 return w;
1495 }
1496
1497 // Residues of A'B' in [0, p_t) for a block, as doubles, in
1498 // w.residue[t * m * n + i + j * m].
1500 std::int64_t row0, const Operand::Data& s,
1501 std::int64_t col0, std::int64_t m, std::int64_t n,
1502 Workspace& w) const
1503 {
1504 const Plan& plan = table.plan;
1505 const int count = static_cast<int>(plan.moduli.size());
1506 const std::int64_t k = r.depth;
1507 const std::size_t size = static_cast<std::size_t>(m * n);
1508 w.residue.assign(static_cast<std::size_t>(count) * size, 0.0);
1509 if (k == 0) return;
1510 const bool int8_engine = options.engine == Engine::Int8;
1511 if (int8_engine) {
1512 materialize(r);
1513 materialize(s);
1514 int8->prepareThread();
1515 w.integer.resize(size);
1516 }
1517 w.product.resize(size);
1518 for (int t = 0; t < count; ++t) {
1519 const double p = plan.moduli[static_cast<std::size_t>(t)];
1520 const double inverse = table.inverse_p[static_cast<std::size_t>(t)];
1521 double* acc = w.residue.data() + static_cast<std::size_t>(t) * size;
1522 for (std::int64_t first = 0; first < k; first += plan.chunk) {
1523 const std::int64_t depth = std::min(plan.chunk, k - first);
1524 const double* values;
1525 {
1526 const PhaseTimer gemm_timer(profile, Phase::Gemm);
1527 if (int8_engine) {
1528 const std::int8_t* a =
1529 r.i8.data() +
1530 static_cast<std::size_t>(t) * r.stride() + row0 +
1531 first * r.extent;
1532 const std::int8_t* b =
1533 s.i8.data() +
1534 static_cast<std::size_t>(t) * s.stride() + first +
1535 col0 * s.depth;
1536 int8->gemm(m, n, depth, a, r.extent, b, s.depth,
1537 w.integer.data(), m);
1538 if (verify)
1539 verifyInt8(m, n, depth, a, r.extent, b, s.depth,
1540 s.unsigned_values, w.integer.data());
1541 for (std::size_t i = 0; i < size; ++i)
1542 w.product[i] = w.integer[i];
1543 values = w.product.data();
1544 } else {
1545 fp64ResidueProduct(
1546 m, n, depth,
1547 r.f64.data() +
1548 static_cast<std::size_t>(t) * r.stride() +
1549 row0 + first * r.extent,
1550 r.extent,
1551 s.f64.data() +
1552 static_cast<std::size_t>(t) * s.stride() +
1553 first + col0 * s.depth,
1554 s.depth, w.product.data());
1555 values = w.product.data();
1556 }
1557 }
1558 const PhaseTimer reduce_timer(profile, Phase::Reduce);
1559 // Reduce to [0, p); the quotient estimate is corrected by one
1560 // step each way, and fma returns x - q p exactly.
1561 for (std::size_t i = 0; i < size; ++i) {
1562 const double x = values[i];
1563 const double q = std::floor(x * inverse);
1564 double v = std::fma(-q, p, x);
1565 v = v < 0.0 ? v + p : v;
1566 v = v >= p ? v - p : v;
1567 const double sum = acc[i] + v;
1568 acc[i] = sum >= p ? sum - p : sum;
1569 }
1570 }
1571 }
1572 }
1573
1574 // Writes C from residues stored as w.residue (doubles in [0, p_t)).
1575 void blockReconstruct(const Table& table, const double* residue,
1576 const int* row_exp, const int* col_exp,
1577 std::int64_t m, std::int64_t n, double alpha,
1578 double beta, double* c, std::int64_t ldc,
1579 Workspace& w) const
1580 {
1581 const PhaseTimer timer(profile, Phase::Reconstruct);
1582 const int count = static_cast<int>(table.plan.moduli.size());
1583 const int limbs = table.limbs;
1584 const double radix = std::ldexp(1.0, table.beta_bits);
1585 const double inverse_radix = std::ldexp(1.0, -table.beta_bits);
1586 const std::size_t size = static_cast<std::size_t>(m * n);
1587 // Limb arrays x[l * m + i], plus sign, scale and value per row.
1588 w.limbs.resize(static_cast<std::size_t>(limbs + 4) * m);
1589 double* x = w.limbs.data();
1590 double* sign = x + limbs * m;
1591 double* hi = sign + m;
1592 double* lo = hi + m;
1593 double* est = lo + m;
1594 std::vector<double> place(static_cast<std::size_t>(limbs));
1595 for (int l = 0; l < limbs; ++l)
1596 place[static_cast<std::size_t>(l)] =
1597 std::ldexp(1.0, l * table.beta_bits);
1598 bool finite = true;
1599 for (std::int64_t j = 0; j < n; ++j) {
1600 std::fill(x, x + limbs * m, 0.0);
1601 // T_l = sum_t r_t w_tl, exact (every term and sum below 2^52).
1602 for (int t = 0; t < count; ++t) {
1603 const double* r =
1604 residue + static_cast<std::size_t>(t) * size + j * m;
1605 for (int l = 0; l < limbs; ++l) {
1606 const double weight =
1607 table.weight[static_cast<std::size_t>(t * limbs + l)];
1608 double* out = x + l * m;
1609 for (std::int64_t i = 0; i < m; ++i)
1610 out[i] += r[i] * weight;
1611 }
1612 }
1613 // q = round(S / M) from S = sum_l T_l radix^l; then X = S - q M
1614 // limb by limb (exact: q M_l < 2^52).
1615 std::copy_n(x + (limbs - 1) * m, m, est);
1616 for (int l = limbs - 2; l >= 0; --l) {
1617 const double* t_l = x + l * m;
1618 for (std::int64_t i = 0; i < m; ++i)
1619 est[i] = est[i] * radix + t_l[i];
1620 }
1621 for (std::int64_t i = 0; i < m; ++i)
1622 est[i] = std::rint(est[i] * table.inverse_modulus);
1623 for (int l = 0; l < limbs; ++l) {
1624 const double mod = table.modulus[static_cast<std::size_t>(l)];
1625 double* x_l = x + l * m;
1626 for (std::int64_t i = 0; i < m; ++i)
1627 x_l[i] -= est[i] * mod;
1628 }
1629 const auto normalize = [&] {
1630 for (int l = 0; l + 1 < limbs; ++l) {
1631 double* x_l = x + l * m;
1632 double* x_next = x_l + m;
1633 for (std::int64_t i = 0; i < m; ++i) {
1634 const double carry = std::floor(x_l[i] * inverse_radix);
1635 x_l[i] -= carry * radix;
1636 x_next[i] += carry;
1637 }
1638 }
1639 };
1640 normalize();
1641 // Lower limbs now lie in [0, radix); the top limb has the sign.
1642 const double* top = x + (limbs - 1) * m;
1643 for (std::int64_t i = 0; i < m; ++i)
1644 sign[i] = top[i] < 0.0 ? -1.0 : 1.0;
1645 for (int l = 0; l < limbs; ++l) {
1646 double* x_l = x + l * m;
1647 for (std::int64_t i = 0; i < m; ++i)
1648 x_l[i] *= sign[i];
1649 }
1650 normalize();
1651 // Nonnegative limbs summed from the top in double-word
1652 // arithmetic (TwoSum), then rounded once.
1653 const double top_place = place[static_cast<std::size_t>(limbs - 1)];
1654 for (std::int64_t i = 0; i < m; ++i) {
1655 hi[i] = top[i] * top_place;
1656 lo[i] = 0.0;
1657 }
1658 for (int l = limbs - 2; l >= 0; --l) {
1659 const double* x_l = x + l * m;
1660 const double pl = place[static_cast<std::size_t>(l)];
1661 for (std::int64_t i = 0; i < m; ++i) {
1662 const double term = x_l[i] * pl;
1663 const double s = hi[i] + term;
1664 const double bb = s - hi[i];
1665 const double e = (hi[i] - (s - bb)) + (term - bb);
1666 hi[i] = s;
1667 lo[i] += e;
1668 }
1669 }
1670 // Unscale by 2^-(s_i + t_j) through the exponent field when the
1671 // result stays normal; other entries take ldexp.
1672 double* output = c + j * ldc;
1673 const std::int64_t t_j = col_exp[j];
1674 for (std::int64_t i = 0; i < m; ++i) {
1675 const double v = hi[i] + lo[i];
1676 const std::int64_t shift = -(row_exp[i] + t_j);
1677 const auto bits = std::bit_cast<std::uint64_t>(v);
1678 const std::int64_t biased =
1679 static_cast<std::int64_t>((bits >> 52) & 0x7FF);
1680 const std::int64_t target = biased + shift;
1681 double scaled;
1682 if (v != 0.0 && biased > 0 && target > 0 && target < 0x7FF)
1683 scaled = std::bit_cast<double>(
1684 bits + (static_cast<std::uint64_t>(shift) << 52));
1685 else
1686 scaled = std::ldexp(v, static_cast<int>(shift));
1687 hi[i] = scaled * sign[i];
1688 }
1689 finite = finishColumn(hi, m, alpha, beta, output) & finite;
1690 }
1691 if (!finite) throw std::runtime_error("nonfinite Scheme II result");
1692 }
1693
1694 // output = alpha P + beta output for one column of unscaled products P;
1695 // false when an output entry is not finite. Shared by the host and the
1696 // device reconstructions.
1697 static bool finishColumn(const double* p, std::int64_t m, double alpha,
1698 double beta, double* output)
1699 {
1700 if (beta == 0.0) {
1701 if (alpha == 1.0)
1702 std::copy_n(p, m, output);
1703 else
1704 for (std::int64_t i = 0; i < m; ++i)
1705 output[i] = alpha * p[i];
1706 } else {
1707 for (std::int64_t i = 0; i < m; ++i) {
1708 const double scaled = alpha == 1.0 ? p[i] : alpha * p[i];
1709 output[i] = scaled + beta * output[i];
1710 }
1711 }
1712 bool finite = true;
1713 for (std::int64_t i = 0; i < m; ++i)
1714 finite = finite & std::isfinite(output[i]);
1715 return finite;
1716 }
1717
1718 // A small run of the CUDA provider on the host: an FP64 engine with the
1719 // same bits prepares the operands from their values and exponents and
1720 // returns the same entries (SchemeII.h: an entry depends on its row, its
1721 // column and bits only).
1722 mutable std::mutex host_mutex;
1723 mutable std::vector<std::pair<int, std::unique_ptr<Context>>> host_engines;
1724
1725 const Context& hostEngine(int bits) const
1726 {
1727 std::lock_guard lock(host_mutex);
1728 for (const auto& [b, engine]: host_engines)
1729 if (b == bits) return *engine;
1730 Options fp64;
1731 fp64.engine = Engine::Fp64;
1732 fp64.bits = bits;
1733 fp64.threads = options.threads;
1734 fp64.block_rows = options.block_rows;
1735 fp64.block_cols = options.block_cols;
1736 auto engine = std::make_unique<Context>(fp64);
1737 engine->setThreadSource(thread_source);
1738 host_engines.emplace_back(bits, std::move(engine));
1739 return *host_engines.back().second;
1740 }
1741
1742 void runHost(std::span<const Task> tasks, const Table& tab) const
1743 {
1744 const Context& host = hostEngine(tab.plan.bits);
1745 const Plan plan = host.plan(tab.plan.k);
1746 if (plan.bits != tab.plan.bits)
1747 throw std::logic_error("Scheme II host engine with other bits");
1748 std::vector<const Operand::Data*> unique;
1749 std::vector<Operand> prepared;
1750 const auto operand = [&](const Operand::Data* d) -> const Operand* {
1751 for (std::size_t q = 0; q < unique.size(); ++q)
1752 if (unique[q] == d) return &prepared[q];
1753 const bool transpose = d->rows ? d->l_contiguous : !d->l_contiguous;
1754 unique.push_back(d);
1755 prepared.push_back(host.impl_->prepare(
1756 d->rows, d->source, d->source_ld, transpose, d->extent,
1757 d->depth, plan, d->exponents.data(), false, true));
1758 return &prepared.back();
1759 };
1760 prepared.reserve(2 * tasks.size());
1761 std::vector<Task> mapped;
1762 for (const Task& task: tasks) {
1763 if (task.m <= 0 || task.n <= 0) continue;
1764 Task t = task;
1765 t.rows = operand(task.rows->data_.get());
1766 t.cols = operand(task.cols->data_.get());
1767 mapped.push_back(t);
1768 }
1769 host.run(mapped);
1770 }
1771
1772 // Every task of a run on the device: operands cross the bus once, the
1773 // device returns the unscaled products and the host applies alpha and
1774 // beta with finishColumn.
1775 void runDevice(std::span<const Task> tasks, const Table& tab) const
1776 {
1777 const auto* device = static_cast<const CudaInt8*>(int8.get());
1778 std::vector<const Operand::Data*> unique;
1779 const auto index = [&](const Operand::Data* d) {
1780 const auto at = std::find(unique.begin(), unique.end(), d);
1781 if (at != unique.end())
1782 return static_cast<std::int32_t>(at - unique.begin());
1783 unique.push_back(d);
1784 return static_cast<std::int32_t>(unique.size() - 1);
1785 };
1786 // With alpha = 1 and beta = 0 the device writes C itself; otherwise
1787 // it writes P to a buffer and the host forms alpha P + beta C.
1788 std::vector<gpr_scheme2_cuda_task_v1> device_tasks;
1789 std::vector<std::unique_ptr<double[]>> values;
1790 std::vector<const Task*> sources;
1791 for (const Task& task: tasks) {
1792 if (task.m <= 0 || task.n <= 0) continue;
1793 const bool direct = task.alpha == 1.0 && task.beta == 0.0;
1794 values.emplace_back(
1795 direct ? nullptr
1796 : new double[static_cast<std::size_t>(task.m * task.n)]);
1797 sources.push_back(&task);
1798 device_tasks.push_back({index(task.rows->data_.get()),
1799 index(task.cols->data_.get()), task.row0,
1800 task.m, task.col0, task.n,
1801 direct ? task.c : values.back().get(),
1802 direct ? task.ldc : task.m});
1803 }
1804 if (device_tasks.empty()) return;
1805 std::vector<gpr_scheme2_cuda_operand_v1> operands;
1806 for (const Operand::Data* d: unique) {
1807 if (d->unsigned_values)
1808 throw std::invalid_argument(
1809 "Scheme II operand prepared for another provider");
1810 operands.push_back(
1811 {d->deferred ? d->source : nullptr, d->source_ld,
1812 d->l_contiguous ? 1 : 0, d->deferred ? nullptr : d->i8.data(),
1813 d->extent, d->depth, d->rows ? 1 : 0, d->exponents.data()});
1814 }
1816 static_cast<std::int32_t>(tab.plan.moduli.size()),
1817 tab.limbs,
1818 tab.beta_bits,
1819 tab.plan.chunk,
1820 tab.plan.moduli.data(),
1821 tab.weight.data(),
1822 tab.modulus.data(),
1823 tab.inverse_modulus,
1824 tab.inverse_p.data()};
1825 char error[1024]{};
1826 {
1827 const PhaseTimer gemm_timer(profile, Phase::Gemm);
1828 if (device->run_fn(device->engine, &table, operands.data(),
1829 static_cast<std::int32_t>(operands.size()),
1830 device_tasks.data(),
1831 static_cast<std::int32_t>(device_tasks.size()),
1832 error, sizeof(error)))
1833 throw std::runtime_error(error);
1834 }
1835 const PhaseTimer timer(profile, Phase::Reconstruct);
1836 // Column groups of the tasks; every entry is independent.
1837 struct Group {
1838 std::size_t task;
1839 std::int64_t j0, j1;
1840 };
1841 std::vector<Group> groups;
1842 for (std::size_t u = 0; u < sources.size(); ++u) {
1843 const Task& task = *sources[u];
1844 const std::int64_t span = std::max<std::int64_t>(
1845 1, 65536 / std::max<std::int64_t>(1, task.m));
1846 for (std::int64_t j = 0; j < task.n; j += span)
1847 groups.push_back({u, j, std::min(task.n, j + span)});
1848 }
1849 std::atomic<bool> finite{true};
1851 threads(), static_cast<long>(groups.size()), [&](long g) {
1852 const Group& group = groups[static_cast<std::size_t>(g)];
1853 const Task& task = *sources[group.task];
1854 const double* p = values[group.task].get();
1855 bool ok = true;
1856 for (std::int64_t j = group.j0; j < group.j1; ++j) {
1857 double* out = task.c + j * task.ldc;
1858 if (p)
1859 ok = finishColumn(p + j * task.m, task.m, task.alpha,
1860 task.beta, out) &
1861 ok;
1862 else
1863 for (std::int64_t i = 0; i < task.m; ++i)
1864 ok = ok & std::isfinite(out[i]);
1865 }
1866 if (!ok) finite = false;
1867 });
1868 if (!finite) throw std::runtime_error("nonfinite Scheme II result");
1869 }
1870
1871 void runBlocks(std::span<const Task> tasks) const
1872 {
1873 struct Item {
1874 const Task* task;
1875 std::int64_t i0, j0, m, n;
1876 };
1877 std::vector<Item> items;
1878 std::int64_t depth = -1;
1879 for (const Task& task: tasks) {
1880 if (task.m <= 0 || task.n <= 0) continue;
1881 if (!task.rows || !task.cols || !task.rows->data_ ||
1882 !task.cols->data_ || !task.c || task.ldc < task.m)
1883 throw std::invalid_argument("invalid Scheme II task");
1884 const auto& r = *task.rows->data_;
1885 const auto& s = *task.cols->data_;
1886 if (!r.rows || s.rows || r.depth != s.depth || task.row0 < 0 ||
1887 task.col0 < 0 || task.row0 + task.m > r.extent ||
1888 task.col0 + task.n > s.extent || r.moduli != s.moduli)
1889 throw std::invalid_argument("mismatched Scheme II operands");
1890 if (r.plan_k != s.plan_k || (depth >= 0 && depth != r.plan_k))
1891 throw std::invalid_argument(
1892 "Scheme II tasks of one run share k");
1893 depth = r.plan_k;
1894 }
1895 if (depth < 0) return;
1896 // Blocks small enough that every thread has about three, no larger
1897 // than the configured block, no smaller than 64 x 32.
1898 const int workers = threads();
1899 double entries = 0.0;
1900 for (const Task& task: tasks)
1901 if (task.m > 0 && task.n > 0)
1902 entries +=
1903 static_cast<double>(task.m) * static_cast<double>(task.n);
1904 const double area = std::clamp(
1905 entries / (3.0 * workers), 64.0 * 32.0,
1906 static_cast<double>(options.block_rows * options.block_cols));
1907 for (const Task& task: tasks) {
1908 if (task.m <= 0 || task.n <= 0) continue;
1909 const std::int64_t rows = std::min<std::int64_t>(
1910 {task.m, options.block_rows,
1911 std::max<std::int64_t>(
1912 64, static_cast<std::int64_t>(2.0 * std::sqrt(area)))});
1913 const std::int64_t cols = std::min<std::int64_t>(
1914 {task.n, options.block_cols,
1915 std::max<std::int64_t>(
1916 32, static_cast<std::int64_t>(area / rows))});
1917 for (std::int64_t i = 0; i < task.m; i += rows)
1918 for (std::int64_t j = 0; j < task.n; j += cols)
1919 items.push_back({&task, i, j, std::min(rows, task.m - i),
1920 std::min(cols, task.n - j)});
1921 }
1922 if (items.empty()) return;
1923 ++profile.products;
1924 const PhaseTimer wall(profile, Phase::RunWall);
1925 const auto table_ptr = table(depth);
1926 const Table& tab = *table_ptr;
1927 for (const Task& task: tasks)
1928 if (task.m > 0 && task.n > 0 &&
1929 task.rows->data_->moduli !=
1930 static_cast<int>(tab.plan.moduli.size()))
1931 throw std::invalid_argument(
1932 "Scheme II operand from another plan");
1933 if (options.engine == Engine::Int8 &&
1934 options.provider == Int8Provider::Cuda) {
1935 double work = 0.0;
1936 for (const Task& task: tasks)
1937 if (task.m > 0 && task.n > 0)
1938 work += static_cast<double>(task.m) *
1939 static_cast<double>(task.n) *
1940 static_cast<double>(depth);
1941 if (work < options.device_min)
1942 runHost(tasks, tab);
1943 else
1944 runDevice(tasks, tab);
1945 return;
1946 }
1947 const BlasThreads& blas = blasThreads();
1948 const int saved = blas.get ? blas.get() : 0;
1949 if (blas.set && saved != 1) blas.set(1);
1950 try {
1952 threads(), static_cast<long>(items.size()), [&](long u) {
1953 const Item& item = items[static_cast<std::size_t>(u)];
1954 const Task& task = *item.task;
1955 const auto& r = *task.rows->data_;
1956 const auto& s = *task.cols->data_;
1957 Workspace& w = workspace();
1958 blockResidues(tab, r, task.row0 + item.i0, s,
1959 task.col0 + item.j0, item.m, item.n, w);
1960 blockReconstruct(tab, w.residue.data(),
1961 r.exponents.data() + task.row0 + item.i0,
1962 s.exponents.data() + task.col0 + item.j0,
1963 item.m, item.n, task.alpha, task.beta,
1964 task.c + item.i0 + item.j0 * task.ldc,
1965 task.ldc, w);
1966 });
1967 } catch (...) {
1968 if (blas.set && saved != 1) blas.set(saved);
1969 throw;
1970 }
1971 if (blas.set && saved != 1) blas.set(saved);
1972 }
1973};
1974
1975Context::Context(Options options) : impl_(std::make_unique<Impl>())
1976{
1977 impl_->options = std::move(options);
1978 if (const char* flag = std::getenv("GPR_SCHEME2_PROFILE"); flag && *flag)
1979 impl_->profile.enabled = true;
1980 if (const char* flag = std::getenv("GPR_SCHEME2_VERIFY"); flag && *flag)
1981 impl_->verify = true;
1982 if (impl_->options.engine == Engine::Int8)
1983 impl_->int8 = makeInt8(impl_->options);
1984 impl_->table(1); // validates bits and moduli
1985}
1986
1987Context::~Context() = default;
1988
1989const Options& Context::options() const noexcept
1990{
1991 return impl_->options;
1992}
1993
1994void Context::setThreadSource(int (*source)())
1995{
1996 impl_->thread_source = source;
1997}
1998
1999Plan Context::plan(std::int64_t k) const
2000{
2001 if (k < 0) throw std::invalid_argument("invalid Scheme II inner dimension");
2002 return impl_->table(k)->plan;
2003}
2004
2005std::string Context::describe(std::int64_t k) const
2006{
2007 const Plan p = plan(k);
2008 std::string text = impl_->options.engine == Engine::Int8 ? "int8" : "fp64";
2009 if (impl_->int8) text += " provider=" + impl_->int8->name();
2010 text += " bits=" + std::to_string(p.bits) +
2011 " moduli=" + std::to_string(p.moduli.size()) +
2012 " chunk=" + std::to_string(p.chunk) +
2013 " log2M=" + std::to_string(p.log2_modulus_product);
2014 return text;
2015}
2016
2017Operand Context::prepareRows(const double* a, std::int64_t lda, bool transpose,
2018 std::int64_t m, std::int64_t k, const Plan& plan,
2019 const int* exponents) const
2020{
2021 return impl_->prepare(true, a, lda, transpose, m, k, plan, exponents);
2022}
2023
2024Operand Context::prepareColumns(const double* b, std::int64_t ldb,
2025 bool transpose, std::int64_t k, std::int64_t n,
2026 const Plan& plan, const int* exponents) const
2027{
2028 return impl_->prepare(false, b, ldb, transpose, n, k, plan, exponents);
2029}
2030
2031void Context::run(std::span<const Task> tasks) const
2032{
2033 impl_->runBlocks(tasks);
2034}
2035
2036void Context::gemm(bool transpose_a, bool transpose_b, std::int64_t m,
2037 std::int64_t n, std::int64_t k, double alpha,
2038 const double* a, std::int64_t lda, const double* b,
2039 std::int64_t ldb, double beta, double* c,
2040 std::int64_t ldc) const
2041{
2042 if (m < 0 || n < 0 || k < 0 || ldc < std::max<std::int64_t>(1, m) ||
2043 !std::isfinite(alpha) || !std::isfinite(beta))
2044 throw std::invalid_argument("invalid Scheme II product");
2045 if (m == 0 || n == 0) return;
2046 if (k == 0 || alpha == 0.0) {
2047 for (std::int64_t j = 0; j < n; ++j)
2048 for (std::int64_t i = 0; i < m; ++i)
2049 c[i + j * ldc] = beta == 0.0 ? 0.0 : beta * c[i + j * ldc];
2050 return;
2051 }
2052 const Plan p = plan(k);
2053 const std::size_t per_entry =
2054 p.moduli.size() *
2055 (impl_->options.engine == Engine::Int8 ? 1 : sizeof(double)) *
2056 static_cast<std::size_t>(k);
2057 // Panels of op(A) rows and op(B) columns whose residues fit the budget:
2058 // whole operands when they fit, else one whole operand and panels of
2059 // the other, else panels of both (op(B) panels are then prepared once
2060 // per op(A) panel).
2061 const std::size_t budget = impl_->options.panel_bytes;
2062 const std::size_t a_bytes = static_cast<std::size_t>(m) * per_entry;
2063 const std::size_t b_bytes = static_cast<std::size_t>(n) * per_entry;
2064 const auto entries = [&](std::size_t bytes, std::int64_t floor) {
2065 return std::max<std::int64_t>(
2066 floor, static_cast<std::int64_t>(bytes / per_entry));
2067 };
2068 std::int64_t row_panel = m, col_panel = n;
2069 if (a_bytes + b_bytes > budget) {
2070 if (a_bytes <= budget / 2)
2071 col_panel = entries(budget - a_bytes, impl_->options.block_cols);
2072 else if (b_bytes <= budget / 2)
2073 row_panel = entries(budget - b_bytes, impl_->options.block_rows);
2074 else {
2075 row_panel = entries(budget / 2, impl_->options.block_rows);
2076 col_panel = entries(budget / 2, impl_->options.block_cols);
2077 }
2078 }
2079 row_panel = std::min(row_panel, m);
2080 col_panel = std::min(col_panel, n);
2081 const auto prepare_columns = [&](std::int64_t j, std::int64_t cols) {
2082 const double* b_panel = transpose_b ? b + j : b + j * ldb;
2083 return impl_->prepare(false, b_panel, ldb, transpose_b, cols, k, p,
2084 nullptr, false, true);
2085 };
2086 Operand whole_right;
2087 if (col_panel == n) whole_right = prepare_columns(0, n);
2088 for (std::int64_t i = 0; i < m; i += row_panel) {
2089 const std::int64_t rows = std::min(row_panel, m - i);
2090 const double* a_panel = transpose_a ? a + i * lda : a + i;
2091 const Operand left = impl_->prepare(true, a_panel, lda, transpose_a,
2092 rows, k, p, nullptr, false, true);
2093 for (std::int64_t j = 0; j < n; j += col_panel) {
2094 const std::int64_t cols = std::min(col_panel, n - j);
2095 Operand panel_right;
2096 if (col_panel != n) panel_right = prepare_columns(j, cols);
2097 const Operand& right = col_panel == n ? whole_right : panel_right;
2098 const Task task{&left, 0, rows, &right, 0,
2099 cols, alpha, beta, c + i + j * ldc, ldc};
2100 run(std::span<const Task>(&task, 1));
2101 }
2102 }
2103}
2104
2105void Context::residues(const Task& task, std::vector<std::uint32_t>& out) const
2106{
2107 if (!task.rows || !task.cols || !task.rows->data_ || !task.cols->data_)
2108 throw std::invalid_argument("invalid Scheme II task");
2109 if (task.rows->data_->plan_k != task.cols->data_->plan_k ||
2110 task.rows->data_->depth != task.cols->data_->depth)
2111 throw std::invalid_argument("mismatched Scheme II operands");
2112 const auto table = impl_->table(task.rows->data_->plan_k);
2114 impl_->blockResidues(*table, *task.rows->data_, task.row0,
2115 *task.cols->data_, task.col0, task.m, task.n, w);
2116 out.assign(w.residue.begin(), w.residue.end());
2117}
2118
2120 std::span<const std::uint32_t> residues,
2121 std::span<const int> row_exponents,
2122 std::span<const int> column_exponents, std::int64_t m,
2123 std::int64_t n, double alpha, double beta, double* c,
2124 std::int64_t ldc) const
2125{
2126 const auto table = impl_->table(plan.k);
2127 if (table->plan.moduli != plan.moduli ||
2128 residues.size() !=
2129 plan.moduli.size() * static_cast<std::size_t>(m * n) ||
2130 row_exponents.size() != static_cast<std::size_t>(m) ||
2131 column_exponents.size() != static_cast<std::size_t>(n))
2132 throw std::invalid_argument("invalid Scheme II reconstruction");
2133 std::vector<double> values(residues.begin(), residues.end());
2134 for (std::size_t t = 0; t < plan.moduli.size(); ++t)
2135 for (std::size_t i = 0; i < static_cast<std::size_t>(m * n); ++i)
2136 if (residues[t * m * n + i] >= plan.moduli[t])
2137 throw std::invalid_argument("Scheme II residue out of range");
2139 impl_->blockReconstruct(*table, values.data(), row_exponents.data(),
2140 column_exponents.data(), m, n, alpha, beta, c, ldc,
2141 w);
2142}
2143
2144} // namespace gpr::linalg::schemeii
int gpr_scheme2_cuda_gemm_s8_v1(void *engine, int64_t m, int64_t n, int64_t k, const int8_t *r, int64_t ldr, const int8_t *s, int64_t lds, int32_t *c, int64_t ldc, char *error, size_t capacity)
int gpr_scheme2_cuda_run_v1(void *engine, const gpr_scheme2_cuda_table_v1 *table, const gpr_scheme2_cuda_operand_v1 *operands, int32_t operand_count, const gpr_scheme2_cuda_task_v1 *tasks, int32_t task_count, char *error, size_t capacity)
Products of every task. Operands are copied to the device once per call.
void gpr_scheme2_cuda_destroy_v1(void *engine)
void * gpr_scheme2_cuda_create_v1(int device, char *error, size_t capacity)
device < 0 selects the local rank modulo the visible device count.
int gpr_scheme2_cuda_describe_v1(void *engine, char *text, size_t capacity)
One line naming the device.
@ x
Definition Enums.h:28
@ y
Definition Enums.h:28
__attribute__((visibility("default"))) void *gpr_training_product_create_v1(char *error
void runWith(int threads, long count, F &&fn)
run() with an explicit thread count in place of the configured one.
static TilePool & instance()
void residues(const Task &task, std::vector< std::uint32_t > &out) const
Plan plan(std::int64_t k) const
void gemm(bool transpose_a, bool transpose_b, std::int64_t m, std::int64_t n, std::int64_t k, double alpha, const double *a, std::int64_t lda, const double *b, std::int64_t ldb, double beta, double *c, std::int64_t ldc) const
Operand prepareRows(const double *a, std::int64_t lda, bool transpose, std::int64_t m, std::int64_t k, const Plan &plan, const int *exponents=nullptr) const
Row operand from op(A) (m x k). Exponents override the row maxima.
void setThreadSource(int(*source)())
Thread count used when Options::threads is zero.
const Options & options() const noexcept
void run(std::span< const Task > tasks) const
void reconstruct(const Plan &plan, std::span< const std::uint32_t > residues, std::span< const int > row_exponents, std::span< const int > column_exponents, std::int64_t m, std::int64_t n, double alpha, double beta, double *c, std::int64_t ldc) const
C block from summed residues (see residues()).
std::string describe(std::int64_t k) const
One line naming engine, provider, bits and moduli for k.
Operand prepareColumns(const double *b, std::int64_t ldb, bool transpose, std::int64_t k, std::int64_t n, const Plan &plan, const int *exponents=nullptr) const
Column operand from op(B) (k x n).
std::int64_t depth() const noexcept
std::size_t bytes() const noexcept
const std::vector< int > & exponents() const noexcept
std::int64_t extent() const noexcept
eon_relax_band_t eon_relax_surface_fn void eon_relax_outcome_t * out
int status
int scaleExponent(double max_abs, int bits) noexcept
Definition SchemeII.cpp:447
constexpr int kDefaultBits
Definition SchemeII.h:57
std::vector< std::uint32_t > engineModuli(Engine engine, std::int64_t chunk)
Moduli of an engine for an inner chunk length, largest first.
Definition SchemeII.cpp:442
std::int64_t engineChunk(Engine engine, std::int64_t k)
Inner chunk length of one exact GEMM for an engine.
Definition SchemeII.cpp:436
bool isSpec(std::string_view spec) noexcept
Definition SchemeII.cpp:455
Options parseOptions(std::string_view spec)
Definition SchemeII.cpp:460
constexpr int kMaxBits
Definition SchemeII.h:58
std::string describe(const Stamp &stamp)
Definition RgminAbi.h:41
STL namespace.
std::vector< std::pair< int, std::unique_ptr< Context > > > host_engines
void runHost(std::span< const Task > tasks, const Table &tab) const
std::shared_ptr< const Table > table(std::int64_t k) const
Table build(std::int64_t k, std::int64_t chunk) const
void runBlocks(std::span< const Task > tasks) const
void blockReconstruct(const Table &table, const double *residue, const int *row_exp, const int *col_exp, std::int64_t m, std::int64_t n, double alpha, double beta, double *c, std::int64_t ldc, Workspace &w) const
void materialize(const Operand::Data &d) const
static bool finishColumn(const double *p, std::int64_t m, double alpha, double beta, double *output)
Operand prepare(bool rows, const double *x, std::int64_t ld, bool transpose, std::int64_t extent, std::int64_t depth, const Plan &plan, const int *exponents, bool host_residues=false, bool borrow=false) const
std::unique_ptr< Int8Gemm > int8
static void verifyInt8(std::int64_t m, std::int64_t n, std::int64_t k, const std::int8_t *r, std::int64_t ldr, const std::int8_t *s, std::int64_t lds, bool unsigned_columns, const std::int32_t *c)
static std::vector< double > & scratch()
void runDevice(std::span< const Task > tasks, const Table &tab) const
const Context & hostEngine(int bits) const
void blockResidues(const Table &table, const Operand::Data &r, std::int64_t row0, const Operand::Data &s, std::int64_t col0, std::int64_t m, std::int64_t n, Workspace &w) const
std::vector< std::shared_ptr< const Table > > tables
std::vector< std::int8_t > i8
Definition SchemeII.cpp:995
int threads
Worker threads. Zero asks the thread source at each product.
Definition SchemeII.h:74
int moduli
Number of moduli. Zero selects the fewest that support bits.
Definition SchemeII.h:66
std::string library
Shared library of the INT8 provider. Empty searches the defaults.
Definition SchemeII.h:69
Moduli for one inner dimension k.
Definition SchemeII.h:101
std::vector< std::uint32_t > moduli
Definition SchemeII.h:105
Moduli and CRT tables of one inner dimension (Context::Impl::Table).
Definition CudaEngine.h:21