Loading...
Searching...
No Matches
PredictProduct.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// Copyright (c) gpridge developers
3
4#include <dlfcn.h>
5
6#include <algorithm>
7#include <cmath>
8#include <cstddef>
9#include <cstdio>
10#include <cstdlib>
11#include <limits>
12#include <stdexcept>
13#include <string>
14
17#include "gpr/linalg/ExactSum.h"
21
22#if defined(USE_OPENMP)
23#include <omp.h>
24#endif
25
26namespace gpr::linalg {
27namespace {
28
29// The kernel_float product lives in a device library that meson does not
30// build (scheme_ii_product.cu). A host without it refuses the mode at
31// selection and reports the loader's reason once; it never aborts.
32void* kernelFloatLibrary()
33{
34 static void* const handle = []() -> void* {
35 const char* path = std::getenv("GPR_KERNEL_FLOAT_LIB");
36 if (path == nullptr || path[0] == '\0')
37 path = "libscheme_ii_product.so";
38 void* library = dlopen(path, RTLD_NOW | RTLD_LOCAL);
39 if (library == nullptr) {
40 std::fprintf(stderr, "GPR_PREDICT_SUM=kernel_float: %s\n",
41 dlerror());
42 }
43 return library;
44 }();
45 return handle;
46}
47
48template <class Launch>
49Launch kernelFloatEntry(const char* name)
50{
51 void* const library = kernelFloatLibrary();
52 if (library == nullptr)
53 throw std::runtime_error(
54 "GPR_PREDICT_SUM=kernel_float: the device product library is "
55 "not loadable on this host");
56 const auto entry = reinterpret_cast<Launch>(dlsym(library, name));
57 if (entry == nullptr) {
58 const char* reason = dlerror();
59 throw std::runtime_error(std::string("GPR_PREDICT_SUM=kernel_float: ") +
60 (reason ? reason : name));
61 }
62 return entry;
63}
64
65// Nonfinite operands use binary64 exception propagation. An all-zero product
66// keeps its native zero sign. Finite nonzero terms require exact accumulation
67// even when individual binary64 products overflow or underflow.
68bool nativeBinary64Fallback(const double* left, const double* right, int length,
69 double& native)
70{
71 if (length <= 0) {
72 native = 0.0;
73 return false;
74 }
75 bool nonfinite = false;
76 bool all_zero = true;
77 for (int i = 0; i < length; ++i) {
78 nonfinite =
79 nonfinite || !std::isfinite(left[i]) || !std::isfinite(right[i]);
80 all_zero = all_zero && (left[i] == 0.0 || right[i] == 0.0);
81 }
82 if (!nonfinite && !all_zero) return false;
83 native = left[0] * right[0];
84 for (int i = 1; i < length; ++i)
85 native += left[i] * right[i];
86 return true;
87}
88
89void* emulatedProductLibrary()
90{
91 static void* const handle = []() -> void* {
92 const char* path = std::getenv("GPR_EMULATED_PRODUCT_LIB");
93 if (path == nullptr || path[0] == '\0') return nullptr;
94 void* library = dlopen(path, RTLD_NOW | RTLD_LOCAL);
95 if (library == nullptr) {
96 std::fprintf(stderr, "GPR_EMULATED_PRODUCT_LIB: %s\n", dlerror());
97 std::abort();
98 }
99 return library;
100 }();
101 return handle;
102}
103
104template <class Launch>
105Launch emulatedEntry(const char* name)
106{
107 const auto entry =
108 reinterpret_cast<Launch>(dlsym(emulatedProductLibrary(), name));
109 if (entry == nullptr) {
110 std::fprintf(stderr, "GPR_EMULATED_PRODUCT_LIB: %s\n", dlerror());
111 std::abort();
112 }
113 return entry;
114}
115
116double deviceSchemeProduct(const char* symbol, const double* left,
117 const double* right, int length)
118{
119 using Launch = int (*)(const double*, const double*, int, double*);
120 const Launch launch = emulatedEntry<Launch>(symbol);
121 double total = 0.0;
122 if (launch(left, right, length, &total) != 0) {
123 std::fprintf(stderr, "%s: device product failed\n", symbol);
124 std::abort();
125 }
126 return total;
127}
128
129double kernelFloatProduct(const double* left, const double* right, int length)
130{
131 using Launch = int (*)(const double*, const double*, int, double*);
132 static const Launch launch =
133 kernelFloatEntry<Launch>("scheme_ii_product_launch_v2");
134 double total = 0.0;
135 if (launch(left, right, length, &total) != 0)
136 throw std::runtime_error(
137 "GPR_PREDICT_SUM=kernel_float: device product failed");
138 return total;
139}
140
141void kernelFloatProducts(const StoredProduct* products, int count,
142 double* values)
143{
144 using Launch = int (*)(const double* const*, const double* const*,
145 const int*, int, double*);
146 static const Launch launch =
147 kernelFloatEntry<Launch>("scheme_ii_products_launch_v1");
148 std::vector<const double*> left(count), right(count);
149 std::vector<int> lengths(count);
150 for (int i = 0; i < count; ++i) {
151 left[i] = products[i].left;
152 right[i] = products[i].right;
153 lengths[i] = products[i].length;
154 }
155 const int status =
156 launch(left.data(), right.data(), lengths.data(), count, values);
157 if (status != 0)
158 throw std::runtime_error(
159 "GPR_PREDICT_SUM=kernel_float: device batch failed (" +
160 std::to_string(status) + ")");
161}
162
163} // namespace
164
166{
167 return kernelFloatLibrary() != nullptr;
168}
169
170void evaluateStoredProducts(const StoredProduct* products, int count,
171 ProductMode mode, double* values)
172{
173 if (count < 0 || (count > 0 && (products == nullptr || values == nullptr)))
174 throw std::invalid_argument("invalid product batch");
175 if (count == 0) return;
176 for (int i = 0; i < count; ++i) {
177 const auto& p = products[i];
178 if (p.length < 0 || (p.length > 0 && (!p.left || !p.right)))
179 throw std::invalid_argument("invalid operands in product batch");
180 }
181 if (mode == ProductMode::KernelFloat) {
182 // An empty batch has nothing for the device; its products are zero
183 // whether or not the library is present.
184 bool any_terms = false;
185 for (int i = 0; i < count; ++i)
186 any_terms = any_terms || products[i].length > 0;
187 if (!any_terms) {
188 std::fill(values, values + count, 0.0);
189 return;
190 }
191 bool exceptional = false;
192 for (int i = 0; i < count; ++i) {
193 if (products[i].length <= 0) continue;
194 double native = 0.0;
195 if (nativeBinary64Fallback(products[i].left, products[i].right,
196 products[i].length, native))
197 exceptional = true;
198 }
199 if (!exceptional)
200 kernelFloatProducts(products, count, values);
201 else {
202 for (int i = 0; i < count; ++i)
203 values[i] =
204 evaluateStoredProduct(products[i].left, products[i].right,
205 products[i].length, mode);
206 }
207 } else {
208 for (int i = 0; i < count; ++i)
209 values[i] = evaluateStoredProduct(
210 products[i].left, products[i].right, products[i].length, mode);
211 }
212}
213
215 const std::vector<const PredictProduct*>& products,
216 std::vector<double>& values)
217{
218 if (products.size() > static_cast<size_t>(std::numeric_limits<int>::max()))
219 throw std::length_error("too many prediction products");
220 bool device_batch = true;
221 for (const auto* product: products) {
222 if (product == nullptr)
223 throw std::invalid_argument("null prediction product");
224 device_batch =
225 device_batch && product->mode_ == ProductMode::KernelFloat;
226 }
227 values.resize(products.size());
228 if (!device_batch) {
229 for (size_t i = 0; i < products.size(); ++i)
230 values[i] = products[i]->value();
231 return;
232 }
233 std::vector<StoredProduct> operands;
234 operands.reserve(products.size());
235 for (const auto* product: products) {
236 const auto* terms = product->terms_.get();
237 if (!terms) {
238 operands.push_back({nullptr, nullptr, 0});
239 continue;
240 }
241 if (terms->left.size() >
242 static_cast<size_t>(std::numeric_limits<int>::max()))
243 throw std::length_error("prediction product is too long");
244 operands.push_back({terms->left.data(), terms->right.data(),
245 static_cast<int>(terms->left.size())});
246 }
247 evaluateStoredProducts(operands.data(), static_cast<int>(operands.size()),
248 ProductMode::KernelFloat, values.data());
249}
250
251void contractPredictionMatrix(const double* column_major, int rows, int cols,
252 const double* coefficients, double* output,
253 ProductMode mode)
254{
255 if (cols < 0 || rows < 0 ||
256 (cols > 0 && (column_major == nullptr || output == nullptr)) ||
257 (rows > 0 && coefficients == nullptr))
258 throw std::invalid_argument("invalid prediction contraction");
259 // One column is one energy or one force component of one test point.
260 // Each column is an exact sum of products rounded once, so the column
261 // a thread owns does not depend on the team. Kernel-float launches stay
262 // on the calling thread.
263 const double flops =
264 2.0 * static_cast<double>(rows) * static_cast<double>(cols);
265 const bool parallel =
267#if defined(USE_OPENMP)
268#pragma omp parallel for schedule(static) if (parallel)
269#endif
270 for (int col = 0; col < cols; ++col) {
271 output[col] = evaluateStoredProduct(
272 column_major + static_cast<std::ptrdiff_t>(col) * rows,
273 coefficients, rows, mode);
274 }
275}
276
277double evaluateStoredProduct(const double* left, const double* right,
278 int length, ProductMode mode)
279{
280 if (length <= 0) return 0.0;
281 const bool emulated = mode == ProductMode::SchemeI ||
282 mode == ProductMode::SchemeII ||
284 if (emulated) {
285 double native = 0.0;
286 if (nativeBinary64Fallback(left, right, length, native)) return native;
287 }
288 if (mode == ProductMode::SchemeI || mode == ProductMode::SchemeII) {
289 double certified;
290 if (tryCertifiedProduct(left, right, length, certified))
291 return certified;
292 }
293 const char* device_library = std::getenv("GPR_EMULATED_PRODUCT_LIB");
294 const bool on_device =
295 device_library != nullptr && device_library[0] != '\0';
296 if (mode == ProductMode::SchemeI) {
297 if (on_device)
298 return deviceSchemeProduct("scheme_i_product_launch_v1", left,
299 right, length);
300 Eigen::Map<const Eigen::VectorXd> left_terms(left, length);
301 Eigen::Map<const Eigen::VectorXd> right_terms(right, length);
302 return schemeIProduct(left_terms, right_terms);
303 }
304 if (mode == ProductMode::SchemeII) {
305 if (on_device)
306 return deviceSchemeProduct("scheme_ii_native_launch_v1", left,
307 right, length);
308 return schemeIIProductRaw(left, right, length);
309 }
310 if (mode == ProductMode::KernelFloat)
311 return kernelFloatProduct(left, right, length);
312 // Eigen KK'*a and cutoff Sexpat energy. ExactSum stores the
313 // TwoProductFMA split and value() rounds once. CompensatedSum::addProduct
314 // sums that split with Neumaier, which returns 0 for the Ozaki window
315 // residual 2^-300 and moves the alternating-pi dots off the cell.
316 ExactSum sum;
317 for (int i = 0; i < length; ++i)
318 sum.addProduct(left[i], right[i]);
319 return sum.value();
320}
321
322} // namespace gpr::linalg
Exact floating-point accumulator (Kulisch long accumulator).
void addProduct(double a, double b) noexcept
Definition ExactSum.h:70
double value() const noexcept
The exact sum rounded once to the nearest double, ties to even.
Definition ExactSum.h:190
static void evaluateTogether(const std::vector< const PredictProduct * > &products, std::vector< double > &values)
int status
Dense and structured linear algebra behind the GP: Cholesky and eigen solvers, linear operators,...
void contractPredictionMatrix(const double *column_major, int rows, int cols, const double *coefficients, double *output, ProductMode mode)
double schemeIProduct(const Eigen::MatrixBase< Left > &left, const Eigen::MatrixBase< Right > &right)
Definition OzakiScheme.h:38
bool kernelFloatProductAvailable()
double evaluateStoredProduct(const double *left, const double *right, int length, ProductMode mode)
void evaluateStoredProducts(const StoredProduct *products, int count, ProductMode mode, double *values)
bool teamParallelPays(double flops)
bool tryCertifiedProduct(const double *left, const double *right, int length, double &result)
double schemeIIProductRaw(const double *left, const double *right, int length)