tpfalinearizergpuparams.hh
Go to the documentation of this file.
1// -*- mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
2// vi: set et ts=4 sw=4 sts=4:
3/*
4
5 Copyright 2026 Equinor ASA
6
7 This file is part of the Open Porous Media project (OPM).
8 OPM is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or
11 (at your option) any later version.
12
13 OPM is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with OPM. If not, see <http://www.gnu.org/licenses/>.
20*/
30#ifndef TPFA_LINEARIZER_GPU_PARAMS_HH
31#define TPFA_LINEARIZER_GPU_PARAMS_HH
32
33namespace Opm {
34template <class TypeTag> class TpfaLinearizerGpuParams;
35}
36
37#if HAVE_CUDA && OPM_IS_COMPILING_WITH_GPU_COMPILER
38
39#include <algorithm>
40#include <array>
41#include <cstddef>
42#include <utility>
43#include <memory>
44#include <optional>
45#include <string>
46#include <type_traits>
47#include <vector>
48
49#include <opm/common/utility/gpuistl_if_available.hpp>
50
52
53#include <opm/common/utility/SparseTable.hpp>
58
59// This header is not hipified; select the generated bridge for HIP builds.
60#if USE_HIP
61#include <opm/simulators/linalg/gpuistl_hip/GpuFlowGasWaterEnergyBridge.hpp>
62#else
64#endif
65
67
68namespace Opm {
69
70#if HAVE_CUDA && OPM_IS_COMPILING_WITH_GPU_COMPILER
71template <class MatrixBlock, class VectorBlock>
72__global__ void apply_source_deltas(const unsigned* indices,
73 const VectorBlock* residualDeltas,
74 const MatrixBlock* jacobianDeltas,
75 VectorBlock* residual,
76 MatrixBlock** diagonal,
77 unsigned count)
78{
79 const unsigned i = blockIdx.x * blockDim.x + threadIdx.x;
80 if (i < count) {
81 const unsigned cell = indices[i];
82 residual[cell] += residualDeltas[i];
83 *diagonal[cell] += jacobianDeltas[i];
84 }
85}
86#endif
87
97template <class TypeTag>
98class TpfaLinearizerGpuParams
99{
100 using Scalar = GetPropType<TypeTag, Properties::Scalar>;
101 using GlobalEqVector = GetPropType<TypeTag, Properties::GlobalEqVector>;
102 using SparseMatrixAdapter = GetPropType<TypeTag, Properties::SparseMatrixAdapter>;
103 using LocalResidual = GetPropType<TypeTag, Properties::LocalResidual>;
104 using IntensiveQuantities = GetPropType<TypeTag, Properties::IntensiveQuantities>;
105 using FluidSystem = GetPropType<TypeTag, Properties::FluidSystem>;
106 using Model = GetPropType<TypeTag, Properties::Model>;
107 using Problem = GetPropType<TypeTag, Properties::Problem>;
108
109 enum { numEq = getPropValue<TypeTag, Properties::NumEq>() };
110
111 using MatrixBlockCPU = typename SparseMatrixAdapter::MatrixBlock;
112 using VectorBlockCPU = Dune::FieldVector<Scalar, numEq>;
113 using MatrixBlockGPU = gpuistl::MiniMatrix<Scalar, numEq>;
114 using VectorBlockGPU = gpuistl::MiniVector<Scalar, numEq>;
115
116 using ResidualNBInfo = typename LocalResidual::ResidualNBInfo;
117 using NeighborInfoCPU = NeighborInfoStruct<ResidualNBInfo, MatrixBlockCPU>;
118 using NeighborInfoGPU = NeighborInfoStruct<ResidualNBInfo, MatrixBlockGPU>;
119
120 using ScalarFluidState = typename IntensiveQuantities::ScalarFluidState;
121 using BoundaryConditionDataCPU = BoundaryConditionData<VectorBlockCPU, ScalarFluidState>;
122 using BoundaryInfoCPU = BoundaryInfo<BoundaryConditionDataCPU>;
123
124 // Fluid system buffer/view/ptr types derived without spelling out the fluid-system
125 // template parameters explicitly.
126 using NonStaticFluidSystem = std::decay_t<decltype(FluidSystem::getNonStaticInstance())>;
127 using GpuFluidSystemBuffer = std::decay_t<decltype(::Opm::gpuistl::copy_to_gpu(
128 std::declval<NonStaticFluidSystem&>()))>;
129 using GpuFluidSystemView
130 = std::decay_t<decltype(::Opm::gpuistl::make_view(std::declval<GpuFluidSystemBuffer&>()))>;
131 using GpuFluidSystemPtr = std::shared_ptr<GpuFluidSystemView>;
132
133public:
134 // Type aliases required by callers to instantiate the GPU kernel templates.
135 using CorrectTypeTagView =
136 typename ::Opm::Properties::TTag::to_gpu_type_t<TypeTag, gpuistl::GpuView>;
137
138 // GPUBOIQ and LocalResidualGPU are not taken from typetag as we need the
139 // outer class to template correctly here
140 using GPUBOIQ = BlackOilIntensiveQuantities<CorrectTypeTagView>;
141 using LocalResidualGPU = BlackOilLocalResidualTPFA<CorrectTypeTagView>;
142
143private:
144 using GpuScalarFluidState = typename GPUBOIQ::ScalarFluidState;
145 using BoundaryConditionDataGPU = BoundaryConditionData<VectorBlockGPU, GpuScalarFluidState>;
146 using BoundaryInfoGPU = BoundaryInfo<BoundaryConditionDataGPU>;
147
148 using GpuModelBufferType = SimpleFIBlackOilModel<CorrectTypeTagView, gpuistl::GpuBuffer>;
149 using GpuFlowProblemBufferType = ThermalGasWaterFlowProblem<Scalar, gpuistl::GpuBuffer>;
150
151 using GpuModel = GetPropType<TypeTag, Properties::GpuFIBlackOilModel>;
152 using PropertyAssemblyBridge =
153 gpuistl::GpuFlowGasWaterEnergyBridge<TypeTag, CorrectTypeTagView>;
154
155 FullDomain<gpuistl::GpuBuffer<int>> domainBuffer_;
156 SparseTable<NeighborInfoGPU, gpuistl::GpuBuffer> neighborInfoBuffer_;
157 // diagMatAddressView_ is non-owning: the underlying buffer lives in TpfaLinearizer.
158 gpuistl::GpuView<MatrixBlockGPU*> diagMatAddressView_;
159 // Non-owning: the matrix is owned by TpfaLinearizer and kept alive for
160 // the lifetime of this parameter object.
161 gpuistl::GpuSparseMatrixWrapper<Scalar>* gpuJacobian_;
162 gpuistl::GpuBuffer<VectorBlockGPU> residualBuffer_;
163 gpuistl::GpuView<VectorBlockGPU>
164 residualView_; // stored as lvalue because mutable ref must be provided
165 // gpuISTL consumes a flat vector. MiniVector is contiguous, so this is a
166 // device-to-device flattening copy with no host staging.
167 gpuistl::GpuVector<Scalar> flattenedResidual_;
168 gpuistl::GpuBuffer<unsigned> sourceIndices_;
169 gpuistl::GpuBuffer<VectorBlockGPU> sourceResidualDeltas_;
170 gpuistl::GpuBuffer<MatrixBlockGPU> sourceJacobianDeltas_;
171 // Fallback-only IQ and fluid-system owners. The direct path borrows
172 // these views from the model-owned propertyAssemblyBridge_.
173 std::optional<GpuFluidSystemBuffer> dynamicGpuFluidSystemBuffer_;
174 GpuFluidSystemPtr dynamicGpuFluidSystemPtr_;
175 std::optional<GpuModelBufferType> gpuModelBuffer_;
176 std::optional<GpuFlowProblemBufferType> gpuFlowProblemBuffer_;
177 const PropertyAssemblyBridge* propertyAssemblyBridge_{nullptr};
178 gpuistl::GpuBuffer<BoundaryInfoGPU> boundaryInfoBuffer_;
179 std::array<std::vector<GPUBOIQ>, 2> intensiveQuantityStaging_;
180 std::vector<VectorBlockGPU> sourceResidualStaging_;
181 std::vector<MatrixBlockGPU> sourceJacobianStaging_;
182 std::size_t sourceCapacity_{0};
183
184 bool bindPropertyAssemblyBridge_(Model& model)
185 {
186 // Custom model TypeTags may support assembly without a property dispatcher.
187 if constexpr (requires { model.gpuPropertyAssemblyBridge(); }) {
188 if (model.hasGpuPropertyAssemblyBridge()) {
189 propertyAssemblyBridge_ = &model.gpuPropertyAssemblyBridge();
190 return true;
191 }
192 }
193 propertyAssemblyBridge_ = nullptr;
194 return false;
195 }
196
197public:
216 TpfaLinearizerGpuParams(const FullDomain<>& domain,
217 const SparseTable<NeighborInfoCPU>& neighborInfo,
218 gpuistl::GpuSparseMatrixWrapper<Scalar>& gpuJacobian,
219 gpuistl::GpuBuffer<MatrixBlockGPU*>& gpuBufferDiagMatAddress,
220 typename SparseMatrixAdapter::IstlMatrix& cpuJacobian,
221 GlobalEqVector& residual,
222 const std::vector<BoundaryInfoCPU>& boundaryInfo,
223 Model& model,
224 const Problem& problem,
225 unsigned int numCells)
226 : domainBuffer_(copy_to_gpu(domain))
227 , neighborInfoBuffer_(
228 gpuistl::copy_to_gpu<MatrixBlockGPU>(neighborInfo, gpuJacobian, cpuJacobian))
229 , diagMatAddressView_(gpuistl::make_view(gpuBufferDiagMatAddress))
230 , gpuJacobian_(&gpuJacobian)
231 , residualBuffer_(gpuistl::copy_to_gpu_residual<GlobalEqVector, VectorBlockGPU>(residual))
232 , residualView_(gpuistl::make_view(residualBuffer_))
233 , flattenedResidual_(residualBuffer_.size() * numEq)
234 {
235 static_assert(std::is_same_v<typename PropertyAssemblyBridge::DeviceTypeTagPublic,
236 CorrectTypeTagView>);
237
238 gpuFlowProblemBuffer_.emplace([&]() -> GpuFlowProblemBufferType {
239 std::vector<Scalar> alpha0(numCells);
240 std::vector<Scalar> alpha1(numCells);
241 std::vector<Scalar> alpha2(numCells);
242 std::vector<Scalar> alpha3(numCells);
243 std::vector<Scalar> alpha4(numCells);
244 std::vector<Scalar> alpha5(numCells);
245 const auto& thermalHalfTransBoundary
246 = problem.eclTransmissibilities().getThermalHalfTransBoundary();
247 for (const auto& [key, value] : thermalHalfTransBoundary) {
248 const unsigned cell = key.first;
249 const unsigned dir = key.second;
250 if (dir == 0) {
251 alpha0[cell] = value;
252 } else if (dir == 1) {
253 alpha1[cell] = value;
254 } else if (dir == 2) {
255 alpha2[cell] = value;
256 } else if (dir == 3) {
257 alpha3[cell] = value;
258 } else if (dir == 4) {
259 alpha4[cell] = value;
260 } else if (dir == 5) {
261 alpha5[cell] = value;
262 } else {
263 OPM_THROW(std::logic_error,
264 "Invalid direction for thermal half transmissibility: "
265 + std::to_string(dir));
266 }
267 }
268 ThermalGasWaterFlowProblem<Scalar> gpuFlowProblem(
269 alpha0, alpha1, alpha2, alpha3, alpha4, alpha5, problem.moduleParams());
270 return gpuistl::copy_to_gpu(gpuFlowProblem);
271 }());
272
273 if (bindPropertyAssemblyBridge_(model)) {
274 propertyAssemblyBridge_->waitForAssembly(/*timeIdx=*/0);
275 boundaryInfoBuffer_
276 = gpuistl::copy_to_gpu<VectorBlockGPU, GpuScalarFluidState, BoundaryInfoGPU>(
277 boundaryInfo, propertyAssemblyBridge_->deviceFluidSystem());
278 return;
279 }
280
281 dynamicGpuFluidSystemBuffer_.emplace(
282 ::Opm::gpuistl::copy_to_gpu(FluidSystem::getNonStaticInstance()));
283 dynamicGpuFluidSystemPtr_ =
284 gpuistl::make_gpu_shared_ptr(::Opm::gpuistl::make_view(*dynamicGpuFluidSystemBuffer_));
285 gpuModelBuffer_.emplace([&]() -> GpuModelBufferType {
286 std::vector<Scalar> volumes(numCells);
287 for (unsigned i = 0; i < numCells; ++i) {
288 volumes[domain.cells[i]] = model.dofTotalVolume(domain.cells[i]);
289 }
290 GpuModel gpuModel(
291 model.intensiveQuantityCache()[0], model.intensiveQuantityCache()[1], volumes);
292 return gpuistl::copy_to_gpu(gpuModel, *dynamicGpuFluidSystemPtr_.get());
293 }());
294 boundaryInfoBuffer_ =
295 gpuistl::copy_to_gpu<VectorBlockGPU, GpuScalarFluidState, BoundaryInfoGPU>(
296 boundaryInfo, *dynamicGpuFluidSystemPtr_.get());
297 }
298
299 void refreshForLinearization(Model& model,
300 const std::vector<BoundaryInfoCPU>& boundaryInfo,
301 unsigned numCells)
302 {
303 if (numCells != residualBuffer_.size()) {
304 OPM_THROW(std::logic_error, "GPU assembly topology changed without erasing the matrix");
305 }
306 if (bindPropertyAssemblyBridge_(model)) {
307 propertyAssemblyBridge_->waitForAssembly(/*timeIdx=*/0);
308 boundaryInfoBuffer_ =
309 gpuistl::copy_to_gpu<VectorBlockGPU, GpuScalarFluidState, BoundaryInfoGPU>(
310 boundaryInfo, propertyAssemblyBridge_->deviceFluidSystem());
311 } else {
312 propertyAssemblyBridge_ = nullptr;
313 // A runtime fallback can require owners that were absent when the
314 // persistent assembly parameters were first constructed.
315 if (!dynamicGpuFluidSystemBuffer_) {
316 dynamicGpuFluidSystemBuffer_.emplace(
317 ::Opm::gpuistl::copy_to_gpu(FluidSystem::getNonStaticInstance()));
318 dynamicGpuFluidSystemPtr_ = gpuistl::make_gpu_shared_ptr(
319 ::Opm::gpuistl::make_view(*dynamicGpuFluidSystemBuffer_));
320 std::vector<Scalar> volumes(numCells);
321 for (unsigned cell = 0; cell < numCells; ++cell) {
322 volumes[cell] = model.dofTotalVolume(cell);
323 }
324 GpuModel gpuModel(
325 model.intensiveQuantityCache()[0], model.intensiveQuantityCache()[1], volumes);
326 gpuModelBuffer_.emplace(
327 gpuistl::copy_to_gpu(gpuModel, *dynamicGpuFluidSystemPtr_));
328 }
329 for (unsigned timeIdx = 0; timeIdx < 2; ++timeIdx) {
330 const auto& cache = model.intensiveQuantityCache()[timeIdx];
331 auto& staging = intensiveQuantityStaging_[timeIdx];
332 staging.clear();
333 staging.reserve(cache.size());
334 for (const auto& iq : cache) {
335 staging.push_back(iq.template withOtherFluidSystem<CorrectTypeTagView>(
336 *dynamicGpuFluidSystemPtr_));
337 }
338 auto& target = timeIdx == 0 ? gpuModelBuffer_->cachedIntensiveQuantities0_
339 : gpuModelBuffer_->cachedIntensiveQuantities1_;
340 target.copyFromHost(staging);
341 }
342 boundaryInfoBuffer_ =
343 gpuistl::copy_to_gpu<VectorBlockGPU, GpuScalarFluidState, BoundaryInfoGPU>(
344 boundaryInfo, *dynamicGpuFluidSystemPtr_);
345 }
346 gpuistl::detail::gpuMemsetZero(residualBuffer_.data(),
347 residualBuffer_.size() * sizeof(VectorBlockGPU));
348 }
349
350 auto domainView()
351 {
352 return make_view(domainBuffer_);
353 }
354
355 auto neighborInfoView()
356 {
357 return gpuistl::make_view(neighborInfoBuffer_);
358 }
359
360 auto& diagMatAddressView()
361 {
362 return diagMatAddressView_;
363 }
364
365 auto& gpuJacobian()
366 {
367 return *gpuJacobian_;
368 }
369
370 auto& residualBuffer()
371 {
372 return residualBuffer_;
373 }
374
375 auto& flattenedResidual()
376 {
377 static_assert(sizeof(VectorBlockGPU) == numEq * sizeof(Scalar));
378 static_assert(std::is_trivially_copyable_v<VectorBlockGPU>);
380 flattenedResidual_.data(),
381 reinterpret_cast<const Scalar*>(residualBuffer_.data()),
382 flattenedResidual_.dim());
383 return flattenedResidual_;
384 }
385
386 void applySourceContributions(const std::vector<unsigned>& indices,
387 const std::vector<VectorBlockCPU>& residualContributions,
388 const std::vector<MatrixBlockCPU>& jacobianContributions)
389 {
390 // Convert CPU blocks to their device-compatible representations.
391 if (indices.size() != residualContributions.size()
392 || indices.size() != jacobianContributions.size()) {
393 OPM_THROW(std::invalid_argument, "GPU source contribution sizes do not match");
394 }
395 auto& gpuResidualContributions = sourceResidualStaging_;
396 auto& gpuJacobianContributions = sourceJacobianStaging_;
397 gpuResidualContributions.clear();
398 gpuJacobianContributions.clear();
399 gpuResidualContributions.reserve(indices.size());
400 gpuJacobianContributions.reserve(indices.size());
401 for (std::size_t i = 0; i < indices.size(); ++i) {
402 gpuResidualContributions.emplace_back(residualContributions[i]);
403 gpuJacobianContributions.emplace_back(jacobianContributions[i]);
404 }
405 if (indices.empty()) {
406 return;
407 }
408 if (sourceCapacity_ < indices.size()) {
409 const auto capacity = std::max<std::size_t>(20, indices.size());
410 gpuistl::GpuBuffer<unsigned> newIndices(capacity);
411 gpuistl::GpuBuffer<VectorBlockGPU> newResidualDeltas(capacity);
412 gpuistl::GpuBuffer<MatrixBlockGPU> newJacobianDeltas(capacity);
413 sourceIndices_ = std::move(newIndices);
414 sourceResidualDeltas_ = std::move(newResidualDeltas);
415 sourceJacobianDeltas_ = std::move(newJacobianDeltas);
416 sourceCapacity_ = capacity;
417 }
418 sourceIndices_.copyFromHost(indices.data(), indices.size());
419 sourceResidualDeltas_.copyFromHost(gpuResidualContributions.data(), indices.size());
420 sourceJacobianDeltas_.copyFromHost(gpuJacobianContributions.data(), indices.size());
421 constexpr unsigned blockSize = 256;
422 apply_source_deltas<<<(indices.size() + blockSize - 1) / blockSize, blockSize>>>(
423 sourceIndices_.data(),
424 sourceResidualDeltas_.data(),
425 sourceJacobianDeltas_.data(),
426 residualBuffer_.data(),
427 diagMatAddressView_.data(),
428 indices.size());
430 }
431
432 auto& residualView()
433 {
434 return residualView_;
435 }
436
437 bool usesGpuPropertyAssemblyBridge() const
438 {
439 return propertyAssemblyBridge_ != nullptr;
440 }
441
442 auto modelView()
443 {
444 if (propertyAssemblyBridge_) {
445 return propertyAssemblyBridge_->modelView();
446 }
447 return gpuistl::make_view(*gpuModelBuffer_);
448 }
449
450 auto flowProblemView()
451 {
452 return gpuistl::make_view(*gpuFlowProblemBuffer_);
453 }
454
455 auto boundaryInfoView()
456 {
457 return gpuistl::make_view(boundaryInfoBuffer_);
458 }
459
460 std::size_t boundaryInfoSize() const
461 {
462 return boundaryInfoBuffer_.size();
463 }
464
471 void copyResidualToHost(GlobalEqVector& residual, unsigned numCells)
472 {
473 auto cpuResidualFromGpu = residualBuffer_.asStdVector();
474 std::memcpy(residual.data(), cpuResidualFromGpu.data(), numCells * numEq * sizeof(Scalar));
475 }
476
482 void copyJacobianToHost(SparseMatrixAdapter& jacobian,
483 gpuistl::GpuSparseMatrixWrapper<Scalar>& gpuJacobian)
484 {
485 auto gpuJacobianNonZeroes = gpuJacobian.getNonZeroValues().asStdVector();
486 auto& cpuJacobian = jacobian.istlMatrix();
487 const std::size_t totalMatrixSize = cpuJacobian.nonzeroes() * numEq * numEq;
488 std::memcpy(&(cpuJacobian[0][0][0][0]),
489 gpuJacobianNonZeroes.data(),
490 totalMatrixSize * sizeof(Scalar));
491 }
492};
493
494} // namespace Opm
495
496#endif // HAVE_CUDA && OPM_IS_COMPILING_WITH_GPU_COMPILER
497
498#endif // TPFA_LINEARIZER_GPU_PARAMS_HH
Typed owner for the GPU property-evaluation to TPFA-assembly handoff.
Definition: matrixblock.hh:258
Definition: tpfalinearizergpuparams.hh:34
#define OPM_CUDA_CHECK_LAST_ERROR
OPM_CUDA_CHECK_LAST_ERROR checks the return type of cudaGetLastError(), and throws an exception if cu...
Definition: cuda_check_last_error.hpp:81
void gpuMemcpyDeviceToDevice(T *dstDevice, const T *srcDevice, std::size_t count)
gpuMemcpyDeviceToDevice copies count elements of type T from device to device.
Definition: gpu_memcpy.hpp:111
void gpuMemsetZero(void *dstDevice, std::size_t byteCount)
Clear byteCount bytes of device memory to zero on the default stream.
Definition: gpu_memcpy.hpp:43
inline ::Opm::NoThermalLawManager make_view(::Opm::NoThermalLawManager &)
make_view overload for the no-op thermal manager.
Definition: GpuFlowProblem.hpp:102
std::shared_ptr< T > make_gpu_shared_ptr()
Creates a shared pointer managing GPU-allocated memory of the specified element type.
Definition: gpu_smart_pointer.hpp:49
inline ::Opm::NoThermalLawManager copy_to_gpu(const ::Opm::NoThermalLawManager &)
copy_to_gpu overload for the no-op thermal manager.
Definition: GpuFlowProblem.hpp:95
Definition: blackoilbioeffectsmodules.hh:45
std::string to_string(const ConvergenceReport::ReservoirFailure::Type t)