39#if defined(__x86_64__) && defined(__GNUC__)
40bool signedResidueSimdAvailable()
42 static const bool supported =
43 __builtin_cpu_supports(
"avx2") && __builtin_cpu_supports(
"fma");
45 return supported && (_mm_getcsr() & _MM_MASK_MASK) == _MM_MASK_MASK;
50#define GPR_SIGNED_RESIDUE_PACKET(Result, Values) \
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), \
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), \
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)); \
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)
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);
77 for (; length - q >= 4; q += 4) {
79 GPR_SIGNED_RESIDUE_PACKET(residue, values + q);
80 _mm256_storeu_pd(output + q, residue);
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)
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);
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);
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);
108#undef GPR_SIGNED_RESIDUE_PACKET
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*,
119#define GPR_FP64_RESIDUE_KERNEL(Name, Isa, Vector, Width, Load, Broadcast, \
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) \
127 static_assert((Columns == 1 || Columns == 4) && \
128 (Rows == 1 || Rows == 2)); \
130 [[maybe_unused]] Vector sum01{}, sum10{}, sum11{}, sum20{}, sum21{}, \
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); \
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); \
167GPR_FP64_RESIDUE_KERNEL(fp64ResidueAvx2,
"avx2,fma", __m256d, 4,
168 _mm256_loadu_pd, _mm256_set1_pd, _mm256_fmadd_pd,
170GPR_FP64_RESIDUE_KERNEL(fp64ResidueAvx512,
"avx512f,fma", __m512d, 8,
171 _mm512_loadu_pd, _mm512_set1_pd, _mm512_fmadd_pd,
173#undef GPR_FP64_RESIDUE_KERNEL
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,
183#if defined(__x86_64__) && defined(__GNUC__) && !defined(EIGEN_USE_BLAS) && \
184 !defined(EIGEN_USE_MKL_ALL)
187 Fp64ResidueKernel four_two, four_one, one_two, one_one;
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
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;
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);
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);
222 for (
int column = 0; column < count; ++column) {
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],
228 output[i + (j + column) * m] = sum;
232 for (; n - j >= 4; j += 4)
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;
250 std::vector<std::uint32_t> limb;
252 static BigUInt from(std::uint64_t value)
256 r.limb.push_back(
static_cast<std::uint32_t
>(value));
263 while (!limb.empty() && limb.back() == 0)
266 BigUInt times(std::uint64_t factor)
const
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));
276 r.limb.push_back(
static_cast<std::uint32_t
>(carry));
283 std::uint64_t divide(std::uint64_t divisor, BigUInt& quotient)
const
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);
295 BigUInt shifted(
int bits)
const
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;
305 if (carry) r.limb.push_back(carry);
309 BigUInt plus(
const BigUInt& other)
const
312 std::uint64_t carry = 0;
313 for (std::size_t i = 0; i < std::max(limb.size(), other.limb.size());
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));
321 if (carry) r.limb.push_back(
static_cast<std::uint32_t
>(carry));
325 int compare(
const BigUInt& other)
const
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;
334 std::uint64_t modulo(std::uint64_t divisor)
const
337 return divide(divisor, q);
340 std::uint64_t bits(
int first,
int count)
const
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;
351 int bitLength()
const
353 if (limb.empty())
return 0;
354 return static_cast<int>(32 * (limb.size() - 1)) +
355 std::bit_width(limb.back());
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))) +
367std::uint64_t inverseModulo(std::uint64_t a, std::uint64_t p)
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);
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);
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)
383bool isPrime(std::uint64_t value)
385 if (value < 2)
return false;
386 for (std::uint64_t d = 2; d * d <= value; ++d)
387 if (value % d == 0)
return false;
394constexpr int kMaxModuli = 24;
395constexpr std::int64_t kInt8Chunk = 65536;
396constexpr std::int64_t kFp64MaxChunk = 4096;
401const std::vector<std::uint32_t>& int8Moduli()
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;
419std::vector<std::uint32_t> fp64Moduli(std::int64_t chunk)
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))
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));
438 return std::max<std::int64_t>(
439 1, std::min(k, engine ==
Engine::Int8 ? kInt8Chunk : kFp64MaxChunk));
444 return engine ==
Engine::Int8 ? int8Moduli() : fp64Moduli(chunk);
449 if (!(max_abs > 0.0) || !std::isfinite(max_abs))
return 0;
451 const int e = std::ilogb(max_abs) + 1;
455bool isSpec(std::string_view spec)
noexcept
457 return spec.substr(0, 7) ==
"scheme2";
463 throw std::invalid_argument(
"not a Scheme II specification");
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));
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 ") +
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) {
490 else if (part ==
"int8")
493 throw std::invalid_argument(
"unknown Scheme II engine " + part);
497 const std::string key = part.substr(0, eq), value = part.substr(eq + 1);
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")
506 else if (key ==
"device")
507 options.
device =
static_cast<int>(integer(value,
"device"));
508 else if (key ==
"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") {
518 else if (value ==
"builtin")
520 else if (value ==
"mkl")
522 else if (value ==
"onednn")
524 else if (value ==
"cuda")
527 throw std::invalid_argument(
"unknown INT8 provider " + value);
529 throw std::invalid_argument(
"unknown Scheme II option " + key);
531 if (!engine_seen && parts.size() > 1 &&
532 parts[1].find(
'=') != std::string::npos)
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");
539 throw std::invalid_argument(
"invalid Scheme II block size");
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;
561#if defined(__x86_64__) && defined(__GNUC__)
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,
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);
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));
584 reinterpret_cast<__m256i_u*
>(
out + i),
585 _mm256_add_epi32(sum, _mm256_mullo_epi32(values, scale)));
588 out[i] +=
static_cast<std::int32_t
>(a[i]) * b;
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,
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);
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);
615 _mm512_add_epi32(sum, _mm512_mullo_epi32(values, scale)));
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));
623 reinterpret_cast<__m256i_u*
>(
out + i),
625 sum, _mm256_mullo_epi32(values, _mm256_set1_epi32(b))));
629 out[i] +=
static_cast<std::int32_t
>(a[i]) * b;
637struct BuiltinInt8 final : Int8Gemm {
638 bool unsignedColumns()
const override
642 std::string name()
const override
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
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);
660 if (has_avx2 && m >= 8) {
661 builtinInt8Avx2(m, n, k, r, ldr, s, lds, c, ldc);
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;
679void* openFirst(
const std::string& requested,
680 std::initializer_list<const char*> defaults, std::string& used)
682 if (!requested.empty()) {
683 void* handle = dlopen(requested.c_str(), RTLD_NOW | RTLD_LOCAL);
684 if (!handle)
throw std::runtime_error(dlerror());
688 for (
const char* name: defaults) {
689 if (
void* handle = dlopen(name, RTLD_NOW | RTLD_LOCAL)) {
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;
707 void (*set_threads)(int) =
nullptr;
710 explicit OnednnInt8(
const std::string& library)
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");
718 set_threads =
reinterpret_cast<void (*)(
int)
>(
719 dlsym(handle,
"omp_set_num_threads"));
721 ~OnednnInt8()
override
724 bool unsignedColumns()
const override
728 std::string name()
const override
730 return "onednn " + path;
732 void prepareThread()
const override
734 if (set_threads) set_threads(1);
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
741 const std::int32_t zero = 0;
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);
746 throw std::runtime_error(
"dnnl_gemm_s8s8s32 returned " +
762struct MklInt8 final : Int8Gemm {
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,
769 void* handle =
nullptr;
771 bool row_major_swap =
false;
774 explicit MklInt8(
const std::string& library)
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");
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;
797 throw std::runtime_error(
"cblas_gemm_s8u8s32 signedness probe failed");
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
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); };
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);
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);
814 bool unsignedColumns()
const override
818 std::string name()
const override
820 return "mkl " + path;
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
827 const std::int32_t zero = 0;
828 call(row_major_swap, m, n, k, r, ldr, s, lds, c, ldc, &zero);
835struct CudaInt8 final : Int8Gemm {
836 void* handle =
nullptr;
837 void* engine =
nullptr;
838 std::string path, device;
843 CudaInt8(
const std::string& library,
int device_index)
845 handle = openFirst(library, {
"libgpr_scheme2_cuda.so"}, path);
847 throw std::runtime_error(
"CUDA Scheme II library not found");
850 dlsym(handle,
"gpr_scheme2_cuda_create_v1"));
853 dlsym(handle,
"gpr_scheme2_cuda_describe_v1"));
855 dlsym(handle,
"gpr_scheme2_cuda_destroy_v1"));
857 dlsym(handle,
"gpr_scheme2_cuda_run_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");
863 engine = create(device_index, error,
sizeof(error));
864 if (!engine)
throw std::runtime_error(error);
866 describe(engine, text,
sizeof(text));
871 if (engine) destroy(engine);
874 bool unsignedColumns()
const override
878 std::string name()
const override
880 return "cuda " + device;
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
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);
894std::unique_ptr<Int8Gemm> makeInt8(
const Options& options)
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);
909 return std::make_unique<MklInt8>(options.library);
910 }
catch (
const std::exception&) {
913 return std::make_unique<OnednnInt8>(options.library);
914 }
catch (
const std::exception&) {
916 return std::make_unique<BuiltinInt8>();
922 void (*set)(int) =
nullptr;
923 int (*get)() =
nullptr;
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"));
933const BlasThreads& blasThreads()
935 static const BlasThreads threads;
957 bool enabled =
false;
958 std::atomic<std::int64_t> nanoseconds[
static_cast<int>(Phase::Count)]{};
959 std::atomic<std::int64_t> products{0};
964 PhaseTimer(
const Profile& profile, Phase phase)
965 : profile_(profile.enabled ? &const_cast<Profile&>(profile) : nullptr),
968 if (profile_) start_ = std::chrono::steady_clock::now();
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_)
978 PhaseTimer(
const PhaseTimer&) =
delete;
979 PhaseTimer& operator=(
const PhaseTimer&) =
delete;
984 std::chrono::steady_clock::time_point start_;
995 std::vector<std::int8_t>
i8;
1022 return data_ ? data_->extent : 0;
1026 return data_ ? data_->depth : 0;
1030 static const std::vector<int> none;
1031 return data_ ? data_->exponents : none;
1035 return data_ ? (data_->f64.size() + data_->values.size()) *
sizeof(double) +
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)
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 =
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;
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));
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");
1101 mutable std::vector<std::shared_ptr<const Table>>
tables;
1109 std::shared_ptr<const Table>
table(std::int64_t k)
const
1113 for (
const auto& t:
tables)
1114 if (t->plan.k == k)
return t;
1115 auto t = std::make_shared<Table>(
build(k, chunk));
1122 const std::vector<std::uint32_t> all =
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)]);
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;
1142 while (count <=
static_cast<int>(all.size()) &&
1143 !supports(bits, product(count)))
1145 if (count >
static_cast<int>(all.size()))
1146 throw std::invalid_argument(
1147 "Scheme II moduli cannot support the requested bits");
1149 if (count >
static_cast<int>(all.size()))
1150 throw std::invalid_argument(
"too many Scheme II moduli");
1151 const BigUInt m = product(count);
1154 while (bits >= 2 && !supports(bits, m))
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");
1166 t.
plan.
moduli.assign(all.begin(), all.begin() + count);
1167 const BigUInt m = product(count);
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);
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)];
1180 m.divide(p, cofactor);
1181 const std::uint64_t
y = inverseModulo(cofactor.modulo(p), p);
1182 const BigUInt w = cofactor.times(
y);
1183 for (
int j = 0; j < t.
limbs; ++j)
1184 t.
weight[
static_cast<std::size_t
>(i * t.
limbs + j)] =
1188 for (
int j = 0; j < t.
limbs; ++j)
1189 t.
modulus[
static_cast<std::size_t
>(j)] =
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
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);
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];
1216 out.data_ = std::make_unique<Operand::Data>();
1217 auto& d = *
out.data_;
1221 d.moduli =
static_cast<int>(
plan.moduli.size());
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;
1228 d.unsigned_values = int8_engine && !rows &&
int8->unsignedColumns();
1232 d.l_contiguous = element_major;
1233 else if (int8_engine)
1234 d.i8.resize(
static_cast<std::size_t
>(count) * d.stride());
1236 d.f64.resize(
static_cast<std::size_t
>(count) * d.stride());
1237 if (extent == 0 || depth == 0)
return out;
1244 std::copy_n(exponents, extent, d.exponents.begin());
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);
1268 if (element_major) {
1269 for (std::int64_t q = 0; q < count_e; ++q) {
1270 const double* v =
x + (first + q) * ld;
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]));
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]);
1284 std::max(largest[q], std::abs(v[q]));
1288 if (!ok) finite =
false;
1291 throw std::invalid_argument(
"nonfinite Scheme II operand");
1292 for (std::int64_t e = 0; e < extent; ++e) {
1294 for (
long lp = 0; lp < l_pieces; ++lp)
1297 partial[
static_cast<std::size_t
>(lp * extent + e)]);
1298 d.exponents[
static_cast<std::size_t
>(e)] =
1306 const std::int64_t length = rows ? extent : depth;
1307 const std::int64_t columns = rows ? depth : extent;
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);
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);
1325 const std::int64_t outer = element_major ? extent : depth;
1326 const std::int64_t inner = element_major ? depth : extent;
1331 d.values.resize(d.stride());
1332 d.source = d.values.data();
1333 d.source_ld = inner;
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};
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);
1344 for (std::int64_t o = first; o < last; ++o) {
1345 const double* in =
x + o * ld;
1347 std::copy_n(in, inner,
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);
1355 (std::abs(std::rint(in[q] * half_scale[e] *
1356 rest_scale[e])) <= limit);
1359 if (!within) within_all =
false;
1362 throw std::invalid_argument(
1363 "Scheme II operand exceeds its scale exponent");
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) {
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;
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;
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);
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);
1411 std::int8_t* out_i8 = d.i8.data() + base;
1412 const bool positive = d.unsigned_values;
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);
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);
1425 r = r < 0.0 ? r + p : r;
1427 r = r > high ? r - p : r;
1428 r = r < low ? r + p : r;
1430 out_i8[q] =
static_cast<std::int8_t
>(
1431 static_cast<std::uint8_t
>(
static_cast<int>(r)));
1434 double* out_f64 = d.f64.data() + base;
1436#if defined(__x86_64__) && defined(__GNUC__)
1437 if (length >= 4 && signedResidueSimdAvailable())
1438 q = signedFp64ResiduesAvx2(
y.data(), out_f64,
1439 length, p, inverse, low,
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;
1463 std::lock_guard lock(m.materialize_mutex);
1464 if (!m.i8.empty() || m.stride() == 0)
return;
1472 m.i8 = std::move(host.data_->i8);
1477 thread_local std::vector<double> buffer;
1501 std::int64_t col0, std::int64_t m, std::int64_t n,
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);
1514 int8->prepareThread();
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;
1526 const PhaseTimer gemm_timer(
profile, Phase::Gemm);
1528 const std::int8_t* a =
1530 static_cast<std::size_t
>(t) * r.
stride() + row0 +
1532 const std::int8_t* b =
1534 static_cast<std::size_t
>(t) * s.
stride() + first +
1541 for (std::size_t i = 0; i < size; ++i)
1548 static_cast<std::size_t
>(t) * r.
stride() +
1552 static_cast<std::size_t
>(t) * s.
stride() +
1553 first + col0 * s.
depth,
1558 const PhaseTimer reduce_timer(
profile, Phase::Reduce);
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;
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,
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);
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);
1599 for (std::int64_t j = 0; j < n; ++j) {
1600 std::fill(
x,
x + limbs * m, 0.0);
1602 for (
int t = 0; t < count; ++t) {
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;
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];
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;
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;
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)
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;
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);
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;
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));
1686 scaled = std::ldexp(v,
static_cast<int>(shift));
1687 hi[i] = scaled * sign[i];
1689 finite =
finishColumn(hi, m, alpha, beta, output) & finite;
1691 if (!finite)
throw std::runtime_error(
"nonfinite Scheme II result");
1698 double beta,
double* output)
1702 std::copy_n(p, m, output);
1704 for (std::int64_t i = 0; i < m; ++i)
1705 output[i] = alpha * p[i];
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];
1713 for (std::int64_t i = 0; i < m; ++i)
1714 finite = finite & std::isfinite(output[i]);
1723 mutable std::vector<std::pair<int, std::unique_ptr<Context>>>
host_engines;
1729 if (b == bits)
return *engine;
1736 auto engine = std::make_unique<Context>(fp64);
1747 throw std::logic_error(
"Scheme II host engine with other bits");
1748 std::vector<const Operand::Data*> unique;
1749 std::vector<Operand> prepared;
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();
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;
1765 t.
rows = operand(task.rows->data_.get());
1766 t.
cols = operand(task.cols->data_.get());
1767 mapped.push_back(t);
1777 const auto* device =
static_cast<const CudaInt8*
>(
int8.get());
1778 std::vector<const Operand::Data*> unique;
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);
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(
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});
1804 if (device_tasks.empty())
return;
1805 std::vector<gpr_scheme2_cuda_operand_v1> operands;
1807 if (d->unsigned_values)
1808 throw std::invalid_argument(
1809 "Scheme II operand prepared for another provider");
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()});
1816 static_cast<std::int32_t
>(tab.
plan.
moduli.size()),
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);
1835 const PhaseTimer timer(
profile, Phase::Reconstruct);
1839 std::int64_t j0, j1;
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)});
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();
1856 for (std::int64_t j = group.j0; j < group.j1; ++j) {
1857 double* out = task.c + j * task.ldc;
1859 ok = finishColumn(p + j * task.m, task.m, task.alpha,
1863 for (std::int64_t i = 0; i < task.m; ++i)
1864 ok = ok & std::isfinite(out[i]);
1866 if (!ok) finite =
false;
1868 if (!finite)
throw std::runtime_error(
"nonfinite Scheme II result");
1875 std::int64_t i0, j0, m, n;
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");
1895 if (depth < 0)
return;
1898 const int workers =
threads();
1899 double entries = 0.0;
1900 for (
const Task& task: tasks)
1901 if (task.m > 0 && task.n > 0)
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,
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>(
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>(
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)});
1922 if (items.empty())
return;
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 !=
1931 throw std::invalid_argument(
1932 "Scheme II operand from another plan");
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)
1947 const BlasThreads& blas = blasThreads();
1948 const int saved = blas.get ? blas.get() : 0;
1949 if (blas.set && saved != 1) blas.set(1);
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,
1968 if (blas.set && saved != 1) blas.set(saved);
1971 if (blas.set && saved != 1) blas.set(saved);
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;
1983 impl_->int8 = makeInt8(impl_->options);
1991 return impl_->options;
1996 impl_->thread_source = source;
2001 if (k < 0)
throw std::invalid_argument(
"invalid Scheme II inner dimension");
2002 return impl_->table(k)->plan;
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) +
2018 std::int64_t m, std::int64_t k,
const Plan&
plan,
2019 const int* exponents)
const
2021 return impl_->prepare(
true, a, lda, transpose, m, k,
plan, exponents);
2025 bool transpose, std::int64_t k, std::int64_t n,
2026 const Plan&
plan,
const int* exponents)
const
2028 return impl_->prepare(
false, b, ldb, transpose, n, k,
plan, exponents);
2033 impl_->runBlocks(tasks);
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
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];
2053 const std::size_t per_entry =
2055 (impl_->options.engine ==
Engine::Int8 ? 1 :
sizeof(double)) *
2056 static_cast<std::size_t
>(k);
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));
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);
2075 row_panel = entries(budget / 2, impl_->options.block_rows);
2076 col_panel = entries(budget / 2, impl_->options.block_cols);
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);
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);
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));
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);
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
2126 const auto table = impl_->table(
plan.k);
2127 if (table->plan.moduli !=
plan.moduli ||
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");
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)
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,