Mneme
Mneme a tool allowing recording the execution of a GPU (CUDA/HIP) kernel and replaying that kernel as an independent executable.
Loading...
Searching...
No Matches
MnemeReplay.hpp
Go to the documentation of this file.
1#include <algorithm>
2#include <cstdint>
3#include <llvm/ADT/STLExtras.h>
4#include <llvm/Bitcode/BitcodeReader.h>
5#include <llvm/IR/LLVMContext.h>
6#include <llvm/IR/Module.h>
7#include <llvm/Support/FileSystem.h>
8#include <llvm/Support/JSON.h>
9#include <llvm/Support/MemoryBuffer.h>
10#include <memory>
11#include <string>
12#include <utility>
13#include <vector>
14
16#include "mneme/MnemeLogger.hpp"
17#include "mneme/MnemeMemory.hpp"
19#include "mneme/MnemeUtils.hpp"
21
22namespace mneme {
23
24template <DeviceVendors VendorTypes> class PrologueState;
25template <DeviceVendors VendorTypes> class EpilogueState;
26
27// Abstract base for a replay memory state. A concrete state is either a
28// prologue (kernel input state) or an epilogue (expected kernel output state).
29// Subclasses provide load(), which materializes the state onto the device.
30template <DeviceVendors VendorTypes> class ReplayMemState {
31public:
33 using DeviceError_t = typename MnemeDeviceRT::DeviceError_t;
34 using DeviceStream_t = typename MnemeDeviceRT::DeviceStream_t;
35 using KernelFunction_t = typename MnemeDeviceRT::KernelFunction_t;
37
38protected:
39 std::shared_ptr<KernelInfo> KInfo;
41 std::unordered_map<std::string, ReplayGlobalVar> GlobalVars;
42 std::unique_ptr<void *[]> Args;
43
44 explicit ReplayMemState(Snapshot<VendorTypes> SnapshotState)
45 : KInfo(std::move(SnapshotState.KInfo)),
46 DeviceMemoryState(std::move(SnapshotState.DeviceMemory)),
47 GlobalVars(std::move(SnapshotState.GlobalVars)) {
48 LOG_DEBUG("Initialized replay memory state for kernel {}",
49 KInfo->getName());
50 Args = copyOutArgs();
51 }
52
53 void copyGlobals() {
54 for (auto &[GVName, GVI] : GlobalVars) {
55 LOG_DEBUG("Copying data of variable {} to device addr {} and of size {}",
56 GVName, GVI.DevAddr, GVI.VarSize);
57 auto CEC = MnemeDeviceRT::DeviceErrorCheck(
58 MnemeDeviceRT::DeviceCopy(GVI.DevAddr, GVI.HostAddr, GVI.VarSize,
59 MnemeDeviceRT::MemcpyHostToDeviceKind()));
60 if (CEC)
61 LOG_FATAL("Could not copy global " + GVName +
62 " to device EC: " + CEC.value() + "\n");
63 }
64 }
65
66private:
67 std::unique_ptr<void *[]> copyOutArgs() const {
68 void **Args = new void *[KInfo->getNumArgs()];
69 auto ArgData = KInfo->getArgData();
70 for (int I = 0; I < getNumArgs(); I++) {
71 Args[I] = ArgData[I].get();
72 }
73 std::unique_ptr<void *[]> ArgUniquePtr{Args};
74 return ArgUniquePtr;
75 }
76
77public:
78 ReplayMemState() = delete;
79 virtual ~ReplayMemState() { release(); }
80
81 virtual void load() = 0;
82
83 // Restores the recorded state; work queued on Stream must finish before the
84 // state is valid.
85 virtual void reset(DeviceStream_t Stream) = 0;
86
87 void release() {
88 for (auto &[DevAddr, MemBlob] : DeviceMemoryState) {
89 auto EC = DeviceTraits<VendorTypes>::DeviceErrorCheck(MemBlob.release());
90 if (EC)
91 LOG_WARN("Could not release replay memory blob: {}", EC.value());
92 }
93 DeviceMemoryState.clear();
94 }
95
99
100 const std::unordered_map<std::string, ReplayGlobalVar> &getGlobalVars() const {
101 return GlobalVars;
102 }
103
104 // RTTI-free downcasts to a concrete role.
105 virtual PrologueState<VendorTypes> *asPrologue() { return nullptr; }
106 virtual EpilogueState<VendorTypes> *asEpilogue() { return nullptr; }
107
108 void **getArgs() const { return reinterpret_cast<void **>(Args.get()); }
109
110 uint64_t getNumArgs() const { return KInfo->getNumArgs(); }
111
113 LOG_INFO("Initializing {} Globals", GlobalVars.size());
114 for (auto &KV : GlobalVars) {
115 auto [LoadedAddr, LoadedSize] =
117 KV.first);
118 if (KV.second.DevAddr != LoadedAddr) {
119 LOG_WARN("Global : {} was loaded on different addresses Record:{} vs "
120 "Replay:{}",
121 KV.first, KV.second.DevAddr, LoadedAddr);
122 KV.second.DevAddr = LoadedAddr;
123 }
124
125 if (KV.second.VarSize != LoadedSize)
126 LOG_FATAL("Global :" + KV.first +
127 "has a different size between record and replay\n" +
128 "Record Size:" + std::to_string(KV.second.VarSize) +
129 "\nReplay Size:" + std::to_string(LoadedSize));
130
133 KV.second.DevAddr, KV.second.HostAddr, KV.second.VarSize,
135 if (EC)
136 LOG_FATAL("Copying Global :" + KV.first +
137 " from host to device raised error\nEC: " + EC.value());
138 LOG_INFO("Successfully loaded global variable: {}", KV.first);
139 }
140 }
141};
142
143// Replay state for the recorded kernel input.
144template <DeviceVendors VendorTypes>
145class PrologueState : public ReplayMemState<VendorTypes> {
146 using MnemeDeviceRT = DeviceTraits<VendorTypes>;
147 using Blob = MnemeMemoryBlob<VendorTypes>;
148
149public:
150 PrologueState(const std::string &KernelName, const std::string &SnapshotFile)
151 : ReplayMemState<VendorTypes>(
152 BaseSnapshotSource<VendorTypes>(SnapshotFile).load(KernelName)) {}
153
154 // Maps every blob at its recorded address. Blobs closer than a large page
155 // share one mapping, owned by the lowest blob and rounded to whole large
156 // pages and driver VA blocks, or to pages if those do not fit.
157 void load() override {
158 std::vector<std::pair<uintptr_t, Blob *>> Blobs;
159 for (auto &[DevAddr, MemBlob] : this->DeviceMemoryState)
160 Blobs.emplace_back(reinterpret_cast<uintptr_t>(DevAddr), &MemBlob);
161 llvm::sort(Blobs, llvm::less_first());
162
163 int DeviceID = 0;
164 MnemeDeviceRT::getDevice(DeviceID);
165 uint64_t PageSize = MnemeDeviceRT::getMinPageSize(DeviceID);
166 uint64_t BlockSize =
167 std::max({PageSize, MnemeDeviceRT::VABlockSize, util::LargePageSize});
168 auto StartOf = [&](size_t I, uint64_t Unit) {
169 return Blobs[I].first & ~(Unit - 1);
170 };
171 auto EndOf = [&](size_t I, uint64_t Unit) {
172 return util::roundUp(Blobs[I].first + Blobs[I].second->getActualSize(),
173 Unit);
174 };
175 // Blobs [I, J) within Slack of each other's Unit-rounded ranges, and their
176 // rounded end.
177 auto Group = [&](size_t I, size_t Limit, uint64_t Slack, uint64_t Unit) {
178 uintptr_t End = EndOf(I, Unit);
179 size_t J = I + 1;
180 for (; J < Limit && StartOf(J, Unit) <= End + Slack; ++J)
181 End = std::max(End, EndOf(J, Unit));
182 return std::make_pair(J, End);
183 };
184 auto MapGroup = [&](size_t I, size_t J, uintptr_t End, uint64_t Unit) {
185 uintptr_t Start = StartOf(I, Unit);
186 if (End > Start) {
187 uint64_t Size = End - Start;
188 auto Status = Blobs[I].second->mapFixed(
189 reinterpret_cast<void *>(Blobs[I].first),
190 reinterpret_cast<void *>(Start), Size,
191 util::mapAlignment(Start, Size, PageSize), DeviceID);
192 if (Status != MapStatus::Mapped)
193 return Status;
194 ++I;
195 }
196 for (size_t K = I; K < J; ++K)
197 Blobs[K].second->mapInto(reinterpret_cast<void *>(Blobs[K].first));
198 return MapStatus::Mapped;
199 };
200
201 for (size_t I = 0, N = Blobs.size(); I < N;) {
202 auto [J, End] = Group(I, N, util::LargePageSize, BlockSize);
203 if (J - I > 1 && MapGroup(I, J, End, BlockSize) == MapStatus::Mapped) {
204 I = J;
205 continue;
206 }
207 // Something may live between the blobs; map only blobs sharing pages.
208 uint64_t Unit = BlockSize;
209 for (size_t K = I; K < J;) {
210 auto [L, E] = Group(K, J, 0, Unit);
211 auto Status = MapGroup(K, L, E, Unit);
212 if (Status != MapStatus::Mapped && Unit != PageSize) {
213 Unit = PageSize;
214 continue;
215 }
216 if (Status != MapStatus::Mapped)
217 LOG_FATAL("Cannot map recorded range {}-{}: {}\n{}",
218 reinterpret_cast<void *>(StartOf(K, Unit)),
219 reinterpret_cast<void *>(E),
220 Status == MapStatus::Occupied ? "occupied"
221 : "out of memory",
222 util::getMappingsIn(StartOf(K, Unit), E));
223 K = L;
224 Unit = BlockSize;
225 }
226 I = J;
227 }
228
229 // Each blob's host memory is freed as soon as its data is on the device.
230 for (auto &[DevAddr, MemBlob] : this->DeviceMemoryState) {
231 MemBlob.moveDataToDevice();
232 restore(MemBlob, nullptr);
233 }
234 auto EC = MnemeDeviceRT::DeviceErrorCheck(
235 MnemeDeviceRT::DeviceStreamSynchronize(nullptr));
236 if (EC)
237 LOG_FATAL("Could not finish loading the prologue: {}", EC.value());
238 }
239
240 // Restores blobs from their recorded data, queued on Stream.
241 void reset(typename MnemeDeviceRT::DeviceStream_t Stream) override {
242 for (const auto &[DevAddr, MemBlob] : this->DeviceMemoryState)
243 restore(MemBlob, Stream);
244 this->copyGlobals();
245 }
246
247 PrologueState<VendorTypes> *asPrologue() override { return this; }
248
249private:
250 // Queues a copy of the blob's recorded data over its mapping on Stream.
251 void restore(const Blob &MemBlob,
252 typename MnemeDeviceRT::DeviceStream_t Stream) {
253 if (MemBlob.getSize() == 0)
254 return;
255 auto EC = MnemeDeviceRT::DeviceErrorCheck(MnemeDeviceRT::DeviceCopyAsync(
256 MemBlob.getBlobAddr(), MemBlob.getDeviceData(), MemBlob.getSize(),
257 MnemeDeviceRT::MemcpyDeviceToDeviceKind(), Stream));
258 if (EC)
259 LOG_FATAL("Could not restore memory blob at {}: {}",
260 MemBlob.getBlobAddr(), EC.value());
261 }
262};
263
264// Replay state for the expected kernel output. Unlike the prologue, load()
265// only moves each blob's recorded data to the device, mapping nothing at the
266// recorded addresses.
267template <DeviceVendors VendorTypes>
268class EpilogueState : public ReplayMemState<VendorTypes> {
269public:
270 explicit EpilogueState(Snapshot<VendorTypes> SnapshotState)
271 : ReplayMemState<VendorTypes>(std::move(SnapshotState)) {}
272
273 void load() override {
274 for (auto &[DevAddr, MemBlob] : this->DeviceMemoryState)
275 MemBlob.moveDataToDevice();
276 }
277
278 // The blobs are never written, so only the globals need restoring.
280 this->copyGlobals();
281 }
282
283 EpilogueState<VendorTypes> *asEpilogue() override { return this; }
284
285 // Verifies a replayed prologue against this expected-output epilogue. At call
286 // time the prologue's device buffers hold the kernel's actual output.
287 virtual bool matches(const PrologueState<VendorTypes> &Prologue) const {
288 return compare(Prologue, /*GlobalsOnDevice=*/true);
289 }
290
291 // True if the prologue's recorded input already satisfies this epilogue, so
292 // a kernel that writes nothing would verify. Must be called before any launch
293 // writes to the prologue's device buffers.
294 bool matchesUnlaunched(const PrologueState<VendorTypes> &Prologue) const {
295 return compare(Prologue, /*GlobalsOnDevice=*/false);
296 }
297
298private:
299 // Globals reach the device only when a replay module is loaded, so before any
300 // launch the prologue's input globals are read from their host copies.
301 bool compare(const PrologueState<VendorTypes> &Prologue,
302 bool GlobalsOnDevice) const {
303 LOG_DEBUG("Comparing memory states");
304 bool Correct = true;
305
306 // Device memory blobs: both states are device-resident, so the blob
307 // comparator reads both device addresses directly.
308 for (auto &[DevAddr, ProBlob] : Prologue.getDeviceMemory()) {
309 auto It = this->DeviceMemoryState.find(DevAddr);
310 if (It == this->DeviceMemoryState.end()) {
311 LOG_WARN("Cannot find {} in comparators", DevAddr);
312 return false;
313 }
314 auto &EpiBlob = It->second;
315 if (EpiBlob.getSize() != ProBlob.getSize()) {
316 LOG_WARN("Sizes Differ {} vs {}", ProBlob.getSize(), EpiBlob.getSize());
317 return false;
318 }
319 if (!EpiBlob.recordedDataMatches(ProBlob))
320 Correct = false;
321 }
322
323 // Global variables: only the prologue's globals are device-resident; the
324 // epilogue never loads globals.
325 for (auto &[GVName, ProGV] : Prologue.getGlobalVars()) {
326 auto It = this->GlobalVars.find(GVName);
327 if (It == this->GlobalVars.end()) {
328 LOG_WARN("comparing with global var {} that exists only on one of the "
329 "comparators",
330 GVName);
331 Correct = false;
332 continue;
333 }
334
335 auto &EpiGV = It->second;
336 if (!GlobalsOnDevice) {
337 if (memcmp(EpiGV.HostAddr, ProGV.HostAddr, ProGV.VarSize) != 0)
338 Correct = false;
339 continue;
340 }
341
342 std::unique_ptr<uint8_t[]> ProData(new uint8_t[ProGV.VarSize]);
343 auto CEC = DeviceTraits<VendorTypes>::DeviceErrorCheck(
344 DeviceTraits<VendorTypes>::DeviceCopy(
345 ProData.get(), ProGV.DevAddr, ProGV.VarSize,
346 DeviceTraits<VendorTypes>::MemcpyDeviceToHostKind()));
347 if (CEC)
348 LOG_FATAL("Could not copy global from device EC: " + CEC.value() +
349 "\n");
350
351 if (memcmp(EpiGV.HostAddr, ProData.get(), ProGV.VarSize) != 0)
352 Correct = false;
353 }
354
355 LOG_DEBUG("Memory States {}", Correct ? "are the same" : "differ");
356 return Correct;
357 }
358};
359
360template <DeviceVendors VendorTypes>
361std::unique_ptr<ReplayMemState<VendorTypes>>
362makeReplayPrologueState(const std::string &KernelName,
363 const std::string &SnapshotFile) {
364 return std::make_unique<PrologueState<VendorTypes>>(KernelName, SnapshotFile);
365}
366
367template <DeviceVendors VendorTypes>
368std::unique_ptr<ReplayMemState<VendorTypes>>
369makeReplayEpilogueState(const std::string &KernelName,
370 const std::string &SnapshotFile,
371 const std::string &BasePrologueFile) {
374 ->read(KernelName, BaseSnapshotSource<VendorTypes>(BasePrologueFile));
375 return std::make_unique<EpilogueState<VendorTypes>>(std::move(Snap));
376}
377
378} // namespace mneme
#define LOG_INFO(...)
Definition MnemeLogger.hpp:110
#define LOG_DEBUG(...)
Definition MnemeLogger.hpp:109
#define LOG_FATAL(...)
Definition MnemeLogger.hpp:113
#define LOG_WARN(...)
Definition MnemeLogger.hpp:111
Definition MnemeSnapshotFormat.hpp:162
Definition MnemeReplay.hpp:268
bool matchesUnlaunched(const PrologueState< VendorTypes > &Prologue) const
Definition MnemeReplay.hpp:294
EpilogueState< VendorTypes > * asEpilogue() override
Definition MnemeReplay.hpp:283
EpilogueState(Snapshot< VendorTypes > SnapshotState)
Definition MnemeReplay.hpp:270
void reset(typename DeviceTraits< VendorTypes >::DeviceStream_t) override
Definition MnemeReplay.hpp:279
void load() override
Definition MnemeReplay.hpp:273
virtual bool matches(const PrologueState< VendorTypes > &Prologue) const
Definition MnemeReplay.hpp:287
Definition MnemeMemory.hpp:227
Definition MnemeReplay.hpp:145
void load() override
Definition MnemeReplay.hpp:157
PrologueState(const std::string &KernelName, const std::string &SnapshotFile)
Definition MnemeReplay.hpp:150
PrologueState< VendorTypes > * asPrologue() override
Definition MnemeReplay.hpp:247
void reset(typename MnemeDeviceRT::DeviceStream_t Stream) override
Definition MnemeReplay.hpp:241
typename MnemeDeviceRT::KernelFunction_t KernelFunction_t
Definition MnemeReplay.hpp:35
DeviceTraits< VendorTypes > MnemeDeviceRT
Definition MnemeReplay.hpp:32
void release()
Definition MnemeReplay.hpp:87
const std::unordered_map< std::string, ReplayGlobalVar > & getGlobalVars() const
Definition MnemeReplay.hpp:100
typename MnemeDeviceRT::DeviceError_t DeviceError_t
Definition MnemeReplay.hpp:33
std::shared_ptr< KernelInfo > KInfo
Definition MnemeReplay.hpp:39
uint64_t getNumArgs() const
Definition MnemeReplay.hpp:110
void ** getArgs() const
Definition MnemeReplay.hpp:108
ReplayMemState(Snapshot< VendorTypes > SnapshotState)
Definition MnemeReplay.hpp:44
typename MnemeDeviceRT::DeviceStream_t DeviceStream_t
Definition MnemeReplay.hpp:34
std::unique_ptr< void *[]> Args
Definition MnemeReplay.hpp:42
typename DeviceTraits< VendorTypes >::DeviceModule_t DeviceModule_t
Definition MnemeReplay.hpp:36
std::unordered_map< std::string, ReplayGlobalVar > GlobalVars
Definition MnemeReplay.hpp:41
virtual void load()=0
const BlobsByAddress< VendorTypes > & getDeviceMemory() const
Definition MnemeReplay.hpp:96
virtual ~ReplayMemState()
Definition MnemeReplay.hpp:79
BlobsByAddress< VendorTypes > DeviceMemoryState
Definition MnemeReplay.hpp:40
void copyGlobals()
Definition MnemeReplay.hpp:53
virtual EpilogueState< VendorTypes > * asEpilogue()
Definition MnemeReplay.hpp:106
virtual PrologueState< VendorTypes > * asPrologue()
Definition MnemeReplay.hpp:105
void initializeGlobals(DeviceModule_t VendorMod)
Definition MnemeReplay.hpp:112
virtual void reset(DeviceStream_t Stream)=0
static std::unique_ptr< SnapshotReader< VendorTypes > > open(const std::string &Filename)
Definition MnemeSnapshotFormat.hpp:418
int64_t u64 Size
Definition cupti_profile.cpp:179
std::string getMappingsIn(uintptr_t Lo, uintptr_t Hi)
Definition MnemeVASpace.hpp:43
constexpr uint64_t LargePageSize
Definition MnemeVASpace.hpp:18
Ty roundUp(Ty Size, Ty Divider)
Definition MnemeUtils.hpp:16
uint64_t mapAlignment(uintptr_t Addr, uint64_t Size, uint64_t PageSize)
Definition MnemeVASpace.hpp:21
Definition MnemeAnnotation.cpp:3
std::unique_ptr< ReplayMemState< VendorTypes > > makeReplayPrologueState(const std::string &KernelName, const std::string &SnapshotFile)
Definition MnemeReplay.hpp:362
@ Mapped
Definition DeviceTraits.hpp:71
@ Occupied
Definition DeviceTraits.hpp:71
std::unique_ptr< ReplayMemState< VendorTypes > > makeReplayEpilogueState(const std::string &KernelName, const std::string &SnapshotFile, const std::string &BasePrologueFile)
Definition MnemeReplay.hpp:369
std::map< void *, MnemeMemoryBlob< VendorTypes > > BlobsByAddress
Definition MnemeMemory.hpp:605
Definition DeviceTraits.hpp:73
Definition MnemeSnapshotFormat.hpp:65