30#ifndef TPFA_LINEARIZER_GPU_PARAMS_HH
31#define TPFA_LINEARIZER_GPU_PARAMS_HH
37#if HAVE_CUDA && OPM_IS_COMPILING_WITH_GPU_COMPILER
49#include <opm/common/utility/gpuistl_if_available.hpp>
53#include <opm/common/utility/SparseTable.hpp>
61#include <opm/simulators/linalg/gpuistl_hip/GpuFlowGasWaterEnergyBridge.hpp>
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,
75 VectorBlock* residual,
79 const unsigned i = blockIdx.x * blockDim.x + threadIdx.x;
81 const unsigned cell = indices[i];
82 residual[cell] += residualDeltas[i];
83 *diagonal[cell] += jacobianDeltas[i];
97template <
class TypeTag>
98class TpfaLinearizerGpuParams
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>;
109 enum { numEq = getPropValue<TypeTag, Properties::NumEq>() };
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>;
116 using ResidualNBInfo =
typename LocalResidual::ResidualNBInfo;
117 using NeighborInfoCPU = NeighborInfoStruct<ResidualNBInfo, MatrixBlockCPU>;
118 using NeighborInfoGPU = NeighborInfoStruct<ResidualNBInfo, MatrixBlockGPU>;
120 using ScalarFluidState =
typename IntensiveQuantities::ScalarFluidState;
121 using BoundaryConditionDataCPU = BoundaryConditionData<VectorBlockCPU, ScalarFluidState>;
122 using BoundaryInfoCPU = BoundaryInfo<BoundaryConditionDataCPU>;
126 using NonStaticFluidSystem = std::decay_t<
decltype(FluidSystem::getNonStaticInstance())>;
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>;
135 using CorrectTypeTagView =
136 typename ::Opm::Properties::TTag::to_gpu_type_t<TypeTag, gpuistl::GpuView>;
140 using GPUBOIQ = BlackOilIntensiveQuantities<CorrectTypeTagView>;
141 using LocalResidualGPU = BlackOilLocalResidualTPFA<CorrectTypeTagView>;
144 using GpuScalarFluidState =
typename GPUBOIQ::ScalarFluidState;
145 using BoundaryConditionDataGPU = BoundaryConditionData<VectorBlockGPU, GpuScalarFluidState>;
146 using BoundaryInfoGPU = BoundaryInfo<BoundaryConditionDataGPU>;
148 using GpuModelBufferType = SimpleFIBlackOilModel<CorrectTypeTagView, gpuistl::GpuBuffer>;
149 using GpuFlowProblemBufferType = ThermalGasWaterFlowProblem<Scalar, gpuistl::GpuBuffer>;
151 using GpuModel = GetPropType<TypeTag, Properties::GpuFIBlackOilModel>;
152 using PropertyAssemblyBridge =
153 gpuistl::GpuFlowGasWaterEnergyBridge<TypeTag, CorrectTypeTagView>;
155 FullDomain<gpuistl::GpuBuffer<int>> domainBuffer_;
156 SparseTable<NeighborInfoGPU, gpuistl::GpuBuffer> neighborInfoBuffer_;
158 gpuistl::GpuView<MatrixBlockGPU*> diagMatAddressView_;
161 gpuistl::GpuSparseMatrixWrapper<Scalar>* gpuJacobian_;
162 gpuistl::GpuBuffer<VectorBlockGPU> residualBuffer_;
163 gpuistl::GpuView<VectorBlockGPU>
167 gpuistl::GpuVector<Scalar> flattenedResidual_;
168 gpuistl::GpuBuffer<unsigned> sourceIndices_;
169 gpuistl::GpuBuffer<VectorBlockGPU> sourceResidualDeltas_;
170 gpuistl::GpuBuffer<MatrixBlockGPU> sourceJacobianDeltas_;
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};
184 bool bindPropertyAssemblyBridge_(Model& model)
187 if constexpr (
requires { model.gpuPropertyAssemblyBridge(); }) {
188 if (model.hasGpuPropertyAssemblyBridge()) {
189 propertyAssemblyBridge_ = &model.gpuPropertyAssemblyBridge();
193 propertyAssemblyBridge_ =
nullptr;
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,
224 const Problem& problem,
225 unsigned int numCells)
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)
235 static_assert(std::is_same_v<
typename PropertyAssemblyBridge::DeviceTypeTagPublic,
236 CorrectTypeTagView>);
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;
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;
263 OPM_THROW(std::logic_error,
264 "Invalid direction for thermal half transmissibility: "
268 ThermalGasWaterFlowProblem<Scalar> gpuFlowProblem(
269 alpha0, alpha1, alpha2, alpha3, alpha4, alpha5, problem.moduleParams());
273 if (bindPropertyAssemblyBridge_(model)) {
274 propertyAssemblyBridge_->waitForAssembly(0);
276 = gpuistl::copy_to_gpu<VectorBlockGPU, GpuScalarFluidState, BoundaryInfoGPU>(
277 boundaryInfo, propertyAssemblyBridge_->deviceFluidSystem());
281 dynamicGpuFluidSystemBuffer_.emplace(
283 dynamicGpuFluidSystemPtr_ =
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]);
291 model.intensiveQuantityCache()[0], model.intensiveQuantityCache()[1], volumes);
294 boundaryInfoBuffer_ =
295 gpuistl::copy_to_gpu<VectorBlockGPU, GpuScalarFluidState, BoundaryInfoGPU>(
296 boundaryInfo, *dynamicGpuFluidSystemPtr_.get());
299 void refreshForLinearization(Model& model,
300 const std::vector<BoundaryInfoCPU>& boundaryInfo,
303 if (numCells != residualBuffer_.size()) {
304 OPM_THROW(std::logic_error,
"GPU assembly topology changed without erasing the matrix");
306 if (bindPropertyAssemblyBridge_(model)) {
307 propertyAssemblyBridge_->waitForAssembly(0);
308 boundaryInfoBuffer_ =
309 gpuistl::copy_to_gpu<VectorBlockGPU, GpuScalarFluidState, BoundaryInfoGPU>(
310 boundaryInfo, propertyAssemblyBridge_->deviceFluidSystem());
312 propertyAssemblyBridge_ =
nullptr;
315 if (!dynamicGpuFluidSystemBuffer_) {
316 dynamicGpuFluidSystemBuffer_.emplace(
320 std::vector<Scalar> volumes(numCells);
321 for (
unsigned cell = 0; cell < numCells; ++cell) {
322 volumes[cell] = model.dofTotalVolume(cell);
325 model.intensiveQuantityCache()[0], model.intensiveQuantityCache()[1], volumes);
326 gpuModelBuffer_.emplace(
329 for (
unsigned timeIdx = 0; timeIdx < 2; ++timeIdx) {
330 const auto& cache = model.intensiveQuantityCache()[timeIdx];
331 auto& staging = intensiveQuantityStaging_[timeIdx];
333 staging.reserve(cache.size());
334 for (
const auto& iq : cache) {
335 staging.push_back(iq.template withOtherFluidSystem<CorrectTypeTagView>(
336 *dynamicGpuFluidSystemPtr_));
338 auto& target = timeIdx == 0 ? gpuModelBuffer_->cachedIntensiveQuantities0_
339 : gpuModelBuffer_->cachedIntensiveQuantities1_;
340 target.copyFromHost(staging);
342 boundaryInfoBuffer_ =
343 gpuistl::copy_to_gpu<VectorBlockGPU, GpuScalarFluidState, BoundaryInfoGPU>(
344 boundaryInfo, *dynamicGpuFluidSystemPtr_);
347 residualBuffer_.size() *
sizeof(VectorBlockGPU));
355 auto neighborInfoView()
360 auto& diagMatAddressView()
362 return diagMatAddressView_;
367 return *gpuJacobian_;
370 auto& residualBuffer()
372 return residualBuffer_;
375 auto& flattenedResidual()
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_;
386 void applySourceContributions(
const std::vector<unsigned>& indices,
387 const std::vector<VectorBlockCPU>& residualContributions,
388 const std::vector<MatrixBlockCPU>& jacobianContributions)
391 if (indices.size() != residualContributions.size()
392 || indices.size() != jacobianContributions.size()) {
393 OPM_THROW(std::invalid_argument,
"GPU source contribution sizes do not match");
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]);
405 if (indices.empty()) {
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;
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(),
434 return residualView_;
437 bool usesGpuPropertyAssemblyBridge()
const
439 return propertyAssemblyBridge_ !=
nullptr;
444 if (propertyAssemblyBridge_) {
445 return propertyAssemblyBridge_->modelView();
450 auto flowProblemView()
455 auto boundaryInfoView()
460 std::size_t boundaryInfoSize()
const
462 return boundaryInfoBuffer_.size();
471 void copyResidualToHost(GlobalEqVector& residual,
unsigned numCells)
473 auto cpuResidualFromGpu = residualBuffer_.asStdVector();
474 std::memcpy(residual.data(), cpuResidualFromGpu.data(), numCells * numEq *
sizeof(Scalar));
482 void copyJacobianToHost(SparseMatrixAdapter& jacobian,
483 gpuistl::GpuSparseMatrixWrapper<Scalar>& gpuJacobian)
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));
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)