GpuFlowGasWaterEnergyBridge.hpp
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 Copyright 2026 Equinor ASA
5
6 This file is part of the Open Porous Media project (OPM).
7
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*/
18#ifndef OPM_GPU_FLOW_GASWATER_ENERGY_BRIDGE_HPP
19#define OPM_GPU_FLOW_GASWATER_ENERGY_BRIDGE_HPP
20
21#if HAVE_CUDA
22
25
26#include <opm/material/fluidsystems/BlackOilFluidSystem.hpp>
32
33#include <array>
34#include <memory>
35#include <optional>
36#include <stdexcept>
37#include <type_traits>
38#include <vector>
39
40namespace Opm::gpuistl {
41
50template <class CpuTypeTag, class DeviceTypeTag>
51class GpuFlowGasWaterEnergyBridge
52{
53 static constexpr unsigned numTimeSlots = 2;
54
55 using CpuPrototypeTypeTag = Properties::TTag::FlowGasWaterEnergyCpuDeviceContract<CpuTypeTag>;
56 using Scalar = GetPropType<CpuTypeTag, Properties::Scalar>;
57 using Problem = GetPropType<CpuTypeTag, Properties::Problem>;
58 using SolutionVector = GetPropType<CpuTypeTag, Properties::SolutionVector>;
59 using HostIntensiveQuantities = GetPropType<CpuTypeTag, Properties::IntensiveQuantities>;
60 using CpuFluidSystem = GetPropType<CpuTypeTag, Properties::FluidSystem>;
61
62 using DevicePrimaryVariables = GetPropType<DeviceTypeTag, Properties::PrimaryVariables>;
63 using DeviceIntensiveQuantities = BlackOilIntensiveQuantities<DeviceTypeTag>;
64 using DeviceFluidSystem = GetPropType<DeviceTypeTag, Properties::FluidSystem>;
65 using DeviceProblem = GetPropType<DeviceTypeTag, Properties::Problem>;
66 using DeviceModelView = SimpleFIBlackOilModel<DeviceTypeTag, gpuistl::GpuView>;
67
68 using DynamicCpuFluidSystem =
69 std::remove_reference_t<decltype(CpuFluidSystem::getNonStaticInstance())>;
70 using FluidSystemBuffer =
71 decltype(::Opm::gpuistl::copy_to_gpu(std::declval<DynamicCpuFluidSystem&>()));
72 using MaterialLawManager =
73 typename GetProp<DeviceTypeTag, Properties::MaterialLaw>::EclMaterialLawManager;
74 using GpuMaterialLawManager =
75 EclMaterialLaw::GpuManager<typename MaterialLawManager::Traits,
76 typename MaterialLawManager::GasOilLaw,
77 typename MaterialLawManager::OilWaterLaw,
78 gpuistl::GpuBuffer,
79 typename MaterialLawManager::MaterialLaw>;
80 using GpuThermalLawManager =
81 EclThermalLaw::GpuManager<Scalar, DeviceFluidSystem, gpuistl::GpuBuffer, gpuistl::GpuView>;
82 using GpuProblemBuffer =
83 GpuFlowProblem<Scalar, GpuMaterialLawManager, gpuistl::GpuBuffer, GpuThermalLawManager>;
84 using GpuProblemView = decltype(::Opm::gpuistl::make_view(std::declval<GpuProblemBuffer&>()));
85
86 static_assert(std::is_same_v<DeviceIntensiveQuantities,
87 GetPropType<DeviceTypeTag, Properties::IntensiveQuantities>>);
88 static_assert(std::is_same_v<DeviceProblem, GpuProblemView>);
89
90public:
91 using DeviceTypeTagPublic = DeviceTypeTag;
92 using DeviceIntensiveQuantitiesView = gpuistl::GpuView<DeviceIntensiveQuantities>;
93 using DevicePrimaryVariablesView = gpuistl::GpuView<const DevicePrimaryVariables>;
94 using DeviceModelViewPublic = DeviceModelView;
95
96 GpuFlowGasWaterEnergyBridge() = default;
97
98 GpuFlowGasWaterEnergyBridge(const GpuFlowGasWaterEnergyBridge&) = delete;
99 GpuFlowGasWaterEnergyBridge& operator=(const GpuFlowGasWaterEnergyBridge&) = delete;
100
101 ~GpuFlowGasWaterEnergyBridge()
102 {
103 // Also cover a failed update that queued work before recording its event.
104 waitForLastWriter_();
105 }
106
107 void updatePrimaryVariables(const Problem& cpuProblem,
108 const SolutionVector& solution,
109 unsigned timeIdx)
110 {
111 validateTimeIdx_(timeIdx);
112 ensureInitialized_(cpuProblem, timeIdx, solution.size());
113
114 if (solution.size() != numDof_) {
115 OPM_THROW(std::invalid_argument,
116 "GPU property bridge received a solution with a mismatched number of DoFs");
117 }
118
119 auto& hostPrimaryVariables = hostPrimaryVariables_[timeIdx];
120 for (std::size_t i = 0; i < numDof_; ++i) {
121 hostPrimaryVariables[i] = DevicePrimaryVariables(solution[i]);
122 }
123
124 detail::gpuMemcpyHostToDeviceAsync(primaryVariablesBuffer_[timeIdx]->data(),
125 hostPrimaryVariables.data(), numDof_, stream_.get());
126 deviceIqValid_[timeIdx] = false;
127 lastWriterTimeIdx_ = timeIdx;
128 }
129
130 auto stream() const
131 {
132 return stream_.get();
133 }
134
135 DevicePrimaryVariablesView primaryVariablesView(unsigned timeIdx) const
136 {
137 validateReadySlot_(timeIdx);
138 return DevicePrimaryVariablesView(primaryVariablesBuffer_[timeIdx]->data(), numDof_);
139 }
140
141 DeviceIntensiveQuantitiesView intensiveQuantitiesView(unsigned timeIdx) const
142 {
143 validateReadySlot_(timeIdx);
144 return DeviceIntensiveQuantitiesView(intensiveQuantitiesBuffer_[timeIdx]->data(), numDof_);
145 }
146
147 void recordPropertyReady(unsigned timeIdx)
148 {
149 validateReadySlot_(timeIdx);
150 recordEvent(propertyReady_, stream_.get());
151 deviceIqValid_[timeIdx] = true;
152 lastWriterTimeIdx_ = timeIdx;
153 }
154
160 void waitForAssembly(unsigned timeIdx) const
161 {
162 validateValidSlot_(timeIdx);
163 if (lastWriterTimeIdx_ != invalidTimeIdx) {
165 }
166 }
167
168 DeviceModelView modelView() const
169 {
170 validateValidSlot_(0);
171 validateValidSlot_(1);
172 return DeviceModelView(::Opm::gpuistl::make_view(*intensiveQuantitiesBuffer_[0]),
173 ::Opm::gpuistl::make_view(*intensiveQuantitiesBuffer_[1]),
174 ::Opm::gpuistl::make_view(*volumesBuffer_));
175 }
176
177 GpuProblemView flowProblemView() const
178 {
179 if (!problemBuffer_) {
180 OPM_THROW(std::logic_error, "GPU property bridge has not been initialized");
181 }
182 return ::Opm::gpuistl::make_view(*problemBuffer_);
183 }
184
191 const DeviceFluidSystem& deviceFluidSystem() const
192 {
193 if (!deviceFluidSystem_) {
194 OPM_THROW(std::logic_error, "GPU property bridge has not been initialized");
195 }
196 return *deviceFluidSystem_;
197 }
198
199 bool hasModelView() const
200 {
201 return deviceIqValid_[0] && deviceIqValid_[1];
202 }
203
204 bool hasIntensiveQuantities(unsigned timeIdx) const
205 {
206 return timeIdx < numTimeSlots && deviceIqValid_[timeIdx];
207 }
208
212 void materializeHostIntensiveQuantities(unsigned timeIdx,
213 HostIntensiveQuantities* const* destination,
214 std::size_t numDof)
215 {
216 validateValidSlot_(timeIdx);
217 if (destination == nullptr || numDof != numDof_) {
218 OPM_THROW(std::invalid_argument,
219 "GPU property bridge received an invalid host IQ materialization destination");
220 }
221 for (std::size_t i = 0; i < numDof_; ++i) {
222 if (destination[i] == nullptr) {
223 OPM_THROW(std::invalid_argument,
224 "GPU property bridge received a null host IQ materialization entry");
225 }
226 }
227
228 if (lastWriterTimeIdx_ != invalidTimeIdx) {
229 synchronizeEvent(propertyReady_);
230 }
231 hostIntensiveQuantities_.assign(numDof_, *prototype_);
232 intensiveQuantitiesBuffer_[timeIdx]->copyToHost(hostIntensiveQuantities_);
233 for (std::size_t i = 0; i < numDof_; ++i) {
234 destination[i]->overlayBlackOilFieldsFrom(hostIntensiveQuantities_[i]);
235 }
236 }
237
241 void advanceTimeLevel()
242 {
243 if (!deviceIqValid_[0]) {
244 deviceIqValid_[1] = false;
245 return;
246 }
247 detail::gpuMemcpyDeviceToDeviceAsync(intensiveQuantitiesBuffer_[1]->data(),
248 intensiveQuantitiesBuffer_[0]->data(),
249 numDof_, stream_.get());
250 recordPropertyReady(/*timeIdx=*/1);
251 }
252
253private:
254 static constexpr unsigned invalidTimeIdx = numTimeSlots;
255
256 void ensureInitialized_(const Problem& cpuProblem, unsigned currentTimeIdx, std::size_t numDof)
257 {
258 if (numDof == 0u) {
259 OPM_THROW(std::invalid_argument, "GPU property bridge cannot be initialized with zero DoFs");
260 }
261 if (numDof_ == numDof && problemBuffer_) {
262 return;
263 }
264
265 waitForLastWriter_();
266 reset_();
267 numDof_ = numDof;
268
269 auto fluidSystemBuffer =
270 ::Opm::gpuistl::copy_to_gpu(CpuFluidSystem::getNonStaticInstance());
271 fluidSystemBuffer_ = std::make_unique<FluidSystemBuffer>(std::move(fluidSystemBuffer));
272 const auto fluidSystemView = ::Opm::gpuistl::make_view(*fluidSystemBuffer_);
273 deviceFluidSystem_ = ::Opm::gpuistl::make_gpu_shared_ptr<DeviceFluidSystem>(fluidSystemView);
274
275 BlackOilIntensiveQuantities<CpuPrototypeTypeTag> cpuPrototype;
276 prototype_ =
277 cpuPrototype.template withOtherFluidSystem<DeviceTypeTag>(deviceFluidSystem());
278
279 std::vector<DeviceIntensiveQuantities> initialIq(numDof_, *prototype_);
280 for (unsigned timeIdx = 0; timeIdx < numTimeSlots; ++timeIdx) {
281 hostPrimaryVariables_[timeIdx].resize(numDof_);
282 primaryVariablesBuffer_[timeIdx] =
283 std::make_unique<gpuistl::GpuBuffer<DevicePrimaryVariables>>(numDof_);
284 intensiveQuantitiesBuffer_[timeIdx] =
285 std::make_unique<gpuistl::GpuBuffer<DeviceIntensiveQuantities>>(initialIq);
286 }
287
288 std::vector<Scalar> volumes(numDof_);
289 for (std::size_t i = 0; i < numDof_; ++i) {
290 volumes[i] = cpuProblem.model().dofTotalVolume(static_cast<unsigned>(i));
291 }
292 volumesBuffer_ = std::make_unique<gpuistl::GpuBuffer<Scalar>>(volumes);
293 problemBuffer_ = std::make_unique<GpuProblemBuffer>(cpuProblem);
294
295 // The first device update overwrites currentTimeIdx. The previous slot
296 // can be seeded once from an already-valid CPU history cache, avoiding
297 // any IQ transfer in steady-state GPU/GPU iterations.
298 initializePreviousSlot_(cpuProblem, currentTimeIdx);
299 }
300
301 void initializePreviousSlot_(const Problem& cpuProblem, unsigned currentTimeIdx)
302 {
303 const unsigned previousTimeIdx = currentTimeIdx == 0 ? 1 : 0;
304 const auto& cpuModel = cpuProblem.model();
305 if (cpuModel.intensiveQuantityCache().size() <= previousTimeIdx) {
306 return;
307 }
308
309 if constexpr (!getPropValue<CpuTypeTag, Properties::EnableDiffusion>()
310 && !getPropValue<CpuTypeTag, Properties::EnableDispersion>()) {
311 std::vector<DeviceIntensiveQuantities> initialIq;
312 initialIq.reserve(numDof_);
313 for (std::size_t i = 0; i < numDof_; ++i) {
314 const auto* cached =
315 cpuModel.cachedIntensiveQuantities(static_cast<unsigned>(i), previousTimeIdx);
316 if (cached == nullptr) {
317 return;
318 }
319 initialIq.emplace_back(
320 cached->template withOtherFluidSystem<DeviceTypeTag>(deviceFluidSystem()));
321 }
322 intensiveQuantitiesBuffer_[previousTimeIdx]->copyFromHost(initialIq);
323 deviceIqValid_[previousTimeIdx] = true;
324 }
325 }
326
327 void validateTimeIdx_(unsigned timeIdx) const
328 {
329 if (timeIdx >= numTimeSlots) {
330 OPM_THROW(std::invalid_argument,
331 "GPU property bridge supports only current and previous IQ time slots");
332 }
333 }
334
335 void validateReadySlot_(unsigned timeIdx) const
336 {
337 validateTimeIdx_(timeIdx);
338 if (!intensiveQuantitiesBuffer_[timeIdx] || !primaryVariablesBuffer_[timeIdx]) {
339 OPM_THROW(std::logic_error, "GPU property bridge has not been initialized");
340 }
341 }
342
343 void validateValidSlot_(unsigned timeIdx) const
344 {
345 validateReadySlot_(timeIdx);
346 if (!deviceIqValid_[timeIdx]) {
347 OPM_THROW(std::logic_error,
348 "GPU property bridge attempted to consume an invalid intensive-quantity slot");
349 }
350 }
351
352 void waitForLastWriter_() const
353 {
354 synchronizeStreamNoThrow(stream_.get());
355 }
356
357 void reset_()
358 {
359 for (unsigned timeIdx = 0; timeIdx < numTimeSlots; ++timeIdx) {
360 primaryVariablesBuffer_[timeIdx].reset();
361 intensiveQuantitiesBuffer_[timeIdx].reset();
362 hostPrimaryVariables_[timeIdx].clear();
363 deviceIqValid_[timeIdx] = false;
364 }
365 volumesBuffer_.reset();
366 problemBuffer_.reset();
367 deviceFluidSystem_.reset();
368 fluidSystemBuffer_.reset();
369 hostIntensiveQuantities_.clear();
370 prototype_.reset();
371 lastWriterTimeIdx_ = invalidTimeIdx;
372 numDof_ = 0;
373 }
374
375 // Construct the stream first so event-construction failure releases it.
376 GPUStream stream_;
377 GPUEvent propertyReady_;
378 std::size_t numDof_{0};
379 std::array<std::unique_ptr<gpuistl::GpuBuffer<DevicePrimaryVariables>>, numTimeSlots>
380 primaryVariablesBuffer_{};
381 std::array<std::unique_ptr<gpuistl::GpuBuffer<DeviceIntensiveQuantities>>, numTimeSlots>
382 intensiveQuantitiesBuffer_{};
383 std::array<std::vector<DevicePrimaryVariables>, numTimeSlots> hostPrimaryVariables_{};
384 std::vector<DeviceIntensiveQuantities> hostIntensiveQuantities_{};
385 std::optional<DeviceIntensiveQuantities> prototype_;
386 std::unique_ptr<gpuistl::GpuBuffer<Scalar>> volumesBuffer_;
387 std::unique_ptr<FluidSystemBuffer> fluidSystemBuffer_;
388 std::shared_ptr<DeviceFluidSystem> deviceFluidSystem_;
389 std::unique_ptr<GpuProblemBuffer> problemBuffer_;
390 std::array<bool, numTimeSlots> deviceIqValid_{false, false};
391 mutable unsigned lastWriterTimeIdx_{invalidTimeIdx};
392};
393
394} // namespace Opm::gpuistl
395
396#endif // HAVE_CUDA
397
398#endif // OPM_GPU_FLOW_GASWATER_ENERGY_BRIDGE_HPP
Dependency-light GPU TypeTag contract for the CO2STORE flow path.
void gpuMemcpyHostToDeviceAsync(T *dstDevice, const T *srcHost, std::size_t count, cudaStream_t stream)
gpuMemcpyHostToDeviceAsync copies count elements of type T from host to device asynchronously.
Definition: gpu_memcpy.hpp:142
constexpr cudaStream_t DEFAULT_STREAM
The default GPU stream (stream 0)
Definition: gpu_constants.hpp:31
void gpuMemcpyDeviceToDeviceAsync(T *dstDevice, const T *srcDevice, std::size_t count, cudaStream_t stream)
Copy count elements between device buffers on the specified stream.
Definition: gpu_memcpy.hpp:194
A small, fixed‑dimension MiniVector class backed by std::array that can be used in both host and CUDA...
Definition: GpuFlowProblem.hpp:49
void recordEvent(const GPUEvent &event, cudaStream_t stream)
Record completion of the work already queued on a stream.
Definition: gpu_resources.hpp:143
inline ::Opm::NoThermalLawManager make_view(::Opm::NoThermalLawManager &)
make_view overload for the no-op thermal manager.
Definition: GpuFlowProblem.hpp:102
void synchronizeEvent(const GPUEvent &event)
Block the host until the recorded event completes.
Definition: gpu_resources.hpp:158
void synchronizeStreamNoThrow(cudaStream_t stream) noexcept
Drain a stream during teardown, reporting errors without throwing.
Definition: gpu_resources.hpp:167
inline ::Opm::NoThermalLawManager copy_to_gpu(const ::Opm::NoThermalLawManager &)
copy_to_gpu overload for the no-op thermal manager.
Definition: GpuFlowProblem.hpp:95
void waitForEventAsync(cudaStream_t stream, const GPUEvent &event)
Order subsequent stream work after the recorded event without blocking the host.
Definition: gpu_resources.hpp:152
The Opm property system, traits with inheritance.