Loading...
Searching...
No Matches
EnvironmentStdparGpu.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// Copyright (c) gpridge developers
3#include <cublas_v2.h>
4#include <cuda_runtime.h>
5#include <thrust/iterator/counting_iterator.h>
6
7#include <algorithm>
8#include <cstdio>
9#include <execution>
10#include <memory>
11#include <mutex>
12#include <stdexcept>
13#include <string>
14#include <vector>
15
16#include "EnvironmentGpuApi.h"
17
18namespace {
19using namespace gpr::detail;
20
21void cudaCheck(cudaError_t status)
22{
23 if (status != cudaSuccess)
24 throw std::runtime_error(cudaGetErrorString(status));
25}
26
27void blasCheck(cublasStatus_t status)
28{
30 throw std::runtime_error("cuBLAS status " +
31 std::to_string(static_cast<int>(status)));
32}
33
34struct Workspace {
35 cublasHandle_t handle = nullptr;
36 std::mutex mutex;
37 Workspace()
38 {
39 blasCheck(cublasCreate(&handle));
40 }
41 ~Workspace()
42 {
43 if (handle) cublasDestroy(handle);
44 }
45};
46
47struct DeviceEnvironments {
48 std::vector<int> species;
49 std::vector<double> values, jacobians, inverse_variance;
50 EnvironmentBatchView view;
51
52 explicit DeviceEnvironments(EnvironmentBatchView source)
53 {
54 if (source.configurations <= 0 || source.atoms <= 0 ||
55 source.dimensions <= 0 || source.features <= 0 || !source.species ||
56 !source.values || !source.jacobians || !source.inverse_variance)
57 throw std::invalid_argument("invalid GPU environment view");
58 const std::size_t atoms =
59 std::size_t(source.configurations) * source.atoms;
60 species.assign(source.species, source.species + atoms);
61 values.assign(source.values, source.values + atoms * source.features);
62 jacobians.assign(
63 source.jacobians,
64 source.jacobians + atoms * source.dimensions * source.features);
65 inverse_variance.assign(source.inverse_variance,
66 source.inverse_variance + atoms);
67 view = source;
68 view.species = species.data();
69 view.values = values.data();
70 view.jacobians = jacobians.data();
71 view.inverse_variance = inverse_variance.data();
72 }
73};
74
75template <class Work>
76void execute(std::size_t count, Work work)
77{
78 const auto begin = thrust::make_counting_iterator<std::size_t>(0);
79 std::for_each(std::execution::par_unseq, begin, begin + count, work);
80 cudaCheck(cudaDeviceSynchronize());
81}
82
83void assemble(Workspace& workspace, const EnvironmentPairBatch& input,
84 double* output)
85{
86 if (input.pair_count == 0) return;
87 if (!output || !input.left_indices || !input.right_indices ||
88 !input.channels || input.channel_count <= 0 ||
89 input.left.features != input.right.features)
90 throw std::invalid_argument("invalid GPU environment pairs");
91 std::lock_guard<std::mutex> guard(workspace.mutex);
92 DeviceEnvironments left(input.left), right(input.right);
93 std::vector<int> left_indices(input.left_indices,
94 input.left_indices + input.pair_count);
95 std::vector<int> right_indices(input.right_indices,
96 input.right_indices + input.pair_count);
97 std::vector<int> channels(input.channels,
98 input.channels + input.channel_count);
99 for (std::size_t pair = 0; pair < input.pair_count; ++pair)
100 if (left_indices[pair] < 0 ||
101 left_indices[pair] >= left.view.configurations ||
102 right_indices[pair] < 0 ||
103 right_indices[pair] >= right.view.configurations)
104 throw std::invalid_argument(
105 "GPU environment pair index is invalid");
106 const std::size_t al = left.view.atoms, ar = right.view.atoms;
107 const std::size_t dl = left.view.dimensions, dr = right.view.dimensions;
108 const std::size_t features = left.view.features, nc = input.channel_count;
109 const std::size_t jet_size = al * ar * (2 + dl + dr);
110 const std::size_t weighted_size = nc * al * dr * features;
111 const std::size_t gram_size = nc * al * dl * dr;
112 const std::size_t block_size = nc * (1 + dl) * (1 + dr);
113 std::size_t free_bytes = 0, total_bytes = 0;
114 cudaCheck(cudaMemGetInfo(&free_bytes, &total_bytes));
115 const std::size_t bytes_per_pair =
116 sizeof(double) * (jet_size + weighted_size + gram_size + block_size);
117 const std::size_t tile_size =
118 std::min(input.pair_count,
119 std::min(std::size_t{32}, free_bytes / 4 / bytes_per_pair));
120 if (tile_size == 0)
121 throw std::runtime_error("GPU memory cannot hold one environment pair");
122 std::vector<double> jets(tile_size * jet_size),
123 weighted(tile_size * weighted_size);
124 std::vector<double> grams(tile_size * gram_size),
125 blocks(tile_size * block_size);
126 for (std::size_t begin = 0; begin < input.pair_count; begin += tile_size) {
127 const std::size_t count = std::min(tile_size, input.pair_count - begin);
128 const EnvironmentPairBatch batch{left.view,
129 right.view,
130 left_indices.data() + begin,
131 right_indices.data() + begin,
132 channels.data(),
133 input.channel_count,
134 count,
135 input.magnitude};
136 execute(count * al * ar, EnvironmentPairJets{batch, jets.data()});
137 execute(
138 count * weighted_size,
139 EnvironmentWeightedJacobians{batch, jets.data(), weighted.data()});
140 const double one = 1.0, zero = 0.0;
141 for (std::size_t pair = 0; pair < count; ++pair)
142 for (std::size_t channel = 0; channel < nc; ++channel) {
143 const std::size_t matrix = (pair * nc + channel) * al;
144 const double* a =
145 left.view.jacobians +
146 std::size_t(input.left_indices[begin + pair]) * al * dl *
147 features;
148 blasCheck(cublasDgemmStridedBatched(
149 workspace.handle, CUBLAS_OP_N, CUBLAS_OP_T, dl, dr,
150 features, &one, a, dl, dl * features,
151 weighted.data() + matrix * dr * features, dr, dr * features,
152 &zero, grams.data() + matrix * dl * dr, dl, dl * dr, al));
153 }
154 cudaCheck(cudaDeviceSynchronize());
155 execute(count * block_size,
156 EnvironmentBlockEntries{batch, jets.data(), grams.data(),
157 blocks.data()});
158 std::copy_n(blocks.data(), count * block_size,
159 output + begin * block_size);
160 }
161}
162
163void report(char* error, std::size_t capacity, const char* message) noexcept
164{
165 if (error && capacity) std::snprintf(error, capacity, "%s", message);
166}
167} // namespace
168
169extern "C" void* gpr_stdpar_environment_create_v1(char* error,
170 std::size_t capacity) noexcept
171{
172 try {
173 return new Workspace;
174 } catch (const std::exception& failure) {
175 report(error, capacity, failure.what());
176 } catch (...) {
177 report(error, capacity, "unknown GPU workspace error");
178 }
179 return nullptr;
180}
181
182extern "C" void gpr_stdpar_environment_destroy_v1(void* workspace) noexcept
183{
184 delete static_cast<Workspace*>(workspace);
185}
186
188 void* workspace, const gpr::detail::EnvironmentPairBatch* batch,
189 double* blocks, char* error, std::size_t capacity) noexcept
190{
191 try {
192 if (!workspace || !batch)
193 throw std::invalid_argument("GPU workspace and batch are required");
194 assemble(*static_cast<Workspace*>(workspace), *batch, blocks);
195 return 0;
196 } catch (const std::exception& failure) {
197 report(error, capacity, failure.what());
198 } catch (...) {
199 report(error, capacity, "unknown GPU environment error");
200 }
201 return 1;
202}
static constexpr int CUBLAS_OP_N
void * cublasHandle_t
static constexpr int CUBLAS_STATUS_SUCCESS
static constexpr int CUBLAS_OP_T
int cublasStatus_t
void gpr_stdpar_environment_destroy_v1(void *workspace) noexcept
int gpr_stdpar_environment_blocks_v1(void *workspace, const gpr::detail::EnvironmentPairBatch *batch, double *blocks, char *error, std::size_t capacity) noexcept
void * gpr_stdpar_environment_create_v1(char *error, std::size_t capacity) noexcept
int status
Eigen::VectorXd assemble(const DeviceEnvironments &left_environments, const DeviceEnvironments &right_environments, const gpr::detail::EnvironmentPairBatch &batch, std::size_t scratch_bytes)