Loading...
Searching...
No Matches
gpr::linalg::schemeii::Context::Impl Struct Reference

Classes

struct  Table
struct  Workspace

Public Member Functions

 ~Impl ()
int threads () const
std::shared_ptr< const Table > table (std::int64_t k) const
Table build (std::int64_t k, std::int64_t chunk) const
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
void materialize (const Operand::Data &d) 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
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
const Context & hostEngine (int bits) const
void runHost (std::span< const Task > tasks, const Table &tab) const
void runDevice (std::span< const Task > tasks, const Table &tab) const
void runBlocks (std::span< const Task > tasks) const

Static Public Member Functions

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 ()
static Workspace & workspace ()
static bool finishColumn (const double *p, std::int64_t m, double alpha, double beta, double *output)

Public Attributes

Options options
std::unique_ptr< Int8Gemm > int8
int(* thread_source )() = nullptr
Profile profile
bool verify = false
std::mutex tables_mutex
std::vector< std::shared_ptr< const Table > > tables
std::mutex host_mutex
std::vector< std::pair< int, std::unique_ptr< Context > > > host_engines

Detailed Description

Definition at line 1040 of file SchemeII.cpp.

Constructor & Destructor Documentation

◆ ~Impl()

gpr::linalg::schemeii::Context::Impl::~Impl ( )
inline

Definition at line 1078 of file SchemeII.cpp.

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 }

Member Function Documentation

◆ blockReconstruct()

void gpr::linalg::schemeii::Context::Impl::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
inline

Definition at line 1575 of file SchemeII.cpp.

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 }
@ x
Definition Enums.h:28
eon_relax_band_t eon_relax_surface_fn void eon_relax_outcome_t * out
std::shared_ptr< const Table > table(std::int64_t k) const
static bool finishColumn(const double *p, std::int64_t m, double alpha, double beta, double *output)

◆ blockResidues()

void gpr::linalg::schemeii::Context::Impl::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
inline

Definition at line 1499 of file SchemeII.cpp.

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 }
Plan plan(std::int64_t k) const
void materialize(const Operand::Data &d) 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)
std::vector< std::uint32_t > moduli
Definition SchemeII.h:105

◆ build()

Table gpr::linalg::schemeii::Context::Impl::build ( std::int64_t k,
std::int64_t chunk ) const
inline

Definition at line 1120 of file SchemeII.cpp.

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 }
@ y
Definition Enums.h:28
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
constexpr int kMaxBits
Definition SchemeII.h:58

◆ finishColumn()

bool gpr::linalg::schemeii::Context::Impl::finishColumn ( const double * p,
std::int64_t m,
double alpha,
double beta,
double * output )
inlinestatic

Definition at line 1697 of file SchemeII.cpp.

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 }

◆ hostEngine()

const Context & gpr::linalg::schemeii::Context::Impl::hostEngine ( int bits) const
inline

Definition at line 1725 of file SchemeII.cpp.

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 }
std::vector< std::pair< int, std::unique_ptr< Context > > > host_engines

◆ materialize()

void gpr::linalg::schemeii::Context::Impl::materialize ( const Operand::Data & d) const
inline

Definition at line 1459 of file SchemeII.cpp.

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 }
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

◆ prepare()

Operand gpr::linalg::schemeii::Context::Impl::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
inline

Definition at line 1199 of file SchemeII.cpp.

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 }
void runWith(int threads, long count, F &&fn)
run() with an explicit thread count in place of the configured one.
static TilePool & instance()
Eigen::Vector3d at(const FieldMatrixd &mat, Index_t i)
int scaleExponent(double max_abs, int bits) noexcept
Definition SchemeII.cpp:447
static std::vector< double > & scratch()

◆ runBlocks()

void gpr::linalg::schemeii::Context::Impl::runBlocks ( std::span< const Task > tasks) const
inline

Definition at line 1871 of file SchemeII.cpp.

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 }
void runHost(std::span< const Task > tasks, const Table &tab) const
void runDevice(std::span< const Task > tasks, const Table &tab) const

◆ runDevice()

void gpr::linalg::schemeii::Context::Impl::runDevice ( std::span< const Task > tasks,
const Table & tab ) const
inline

Definition at line 1775 of file SchemeII.cpp.

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 }
struct gpr_scheme2_cuda_table_v1 gpr_scheme2_cuda_table_v1
Moduli and CRT tables of one inner dimension (Context::Impl::Table).

◆ runHost()

void gpr::linalg::schemeii::Context::Impl::runHost ( std::span< const Task > tasks,
const Table & tab ) const
inline

Definition at line 1742 of file SchemeII.cpp.

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 }
const Context & hostEngine(int bits) const

◆ scratch()

std::vector< double > & gpr::linalg::schemeii::Context::Impl::scratch ( )
inlinestatic

Definition at line 1475 of file SchemeII.cpp.

1476 {
1477 thread_local std::vector<double> buffer;
1478 return buffer;
1479 }

◆ table()

std::shared_ptr< const Table > gpr::linalg::schemeii::Context::Impl::table ( std::int64_t k) const
inline

Definition at line 1109 of file SchemeII.cpp.

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 }
std::int64_t engineChunk(Engine engine, std::int64_t k)
Inner chunk length of one exact GEMM for an engine.
Definition SchemeII.cpp:436
Table build(std::int64_t k, std::int64_t chunk) const
std::vector< std::shared_ptr< const Table > > tables

◆ threads()

int gpr::linalg::schemeii::Context::Impl::threads ( ) const
inline

Definition at line 1103 of file SchemeII.cpp.

1104 {
1105 if (options.threads > 0) return options.threads;
1106 return thread_source ? std::max(1, thread_source()) : 1;
1107 }

◆ verifyInt8()

void gpr::linalg::schemeii::Context::Impl::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 )
inlinestatic

Definition at line 1049 of file SchemeII.cpp.

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 }

◆ workspace()

Workspace & gpr::linalg::schemeii::Context::Impl::workspace ( )
inlinestatic

Definition at line 1491 of file SchemeII.cpp.

1492 {
1493 thread_local Workspace w;
1494 return w;
1495 }

Member Data Documentation

◆ host_engines

std::vector<std::pair<int, std::unique_ptr<Context> > > gpr::linalg::schemeii::Context::Impl::host_engines
mutable

Definition at line 1723 of file SchemeII.cpp.

◆ host_mutex

std::mutex gpr::linalg::schemeii::Context::Impl::host_mutex
mutable

Definition at line 1722 of file SchemeII.cpp.

◆ int8

std::unique_ptr<Int8Gemm> gpr::linalg::schemeii::Context::Impl::int8

Definition at line 1042 of file SchemeII.cpp.

◆ options

Options gpr::linalg::schemeii::Context::Impl::options

Definition at line 1041 of file SchemeII.cpp.

◆ profile

Profile gpr::linalg::schemeii::Context::Impl::profile
mutable

Definition at line 1044 of file SchemeII.cpp.

◆ tables

std::vector<std::shared_ptr<const Table> > gpr::linalg::schemeii::Context::Impl::tables
mutable

Definition at line 1101 of file SchemeII.cpp.

◆ tables_mutex

std::mutex gpr::linalg::schemeii::Context::Impl::tables_mutex
mutable

Definition at line 1100 of file SchemeII.cpp.

◆ thread_source

int(* gpr::linalg::schemeii::Context::Impl::thread_source) () = nullptr

Definition at line 1043 of file SchemeII.cpp.

◆ verify

bool gpr::linalg::schemeii::Context::Impl::verify = false

Definition at line 1047 of file SchemeII.cpp.


The documentation for this struct was generated from the following file: