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
MnemeSnapshotFormat.hpp
Go to the documentation of this file.
1#pragma once
2#include <algorithm>
3#include <cstdint>
4#include <cstring>
5#include <filesystem>
6#include <memory>
7#include <string>
8#include <unordered_map>
9#include <utility>
10#include <vector>
11
12#include <llvm/ADT/ArrayRef.h>
13#include <llvm/ADT/SmallVector.h>
14#include <llvm/ADT/StringRef.h>
15#include <llvm/Support/MemoryBuffer.h>
16#include <llvm/Support/raw_ostream.h>
17
19#include "mneme/MnemeConfig.hpp"
21#include "mneme/MnemeLogger.hpp"
22#include "mneme/MnemeMemory.hpp"
24#include "mneme/MnemeUtils.hpp"
25#include <proteus/KernelMetadata.h>
26
27namespace mneme {
28
30 void *HostAddr;
31 void *DevAddr;
32 uint64_t VarSize;
34 : HostAddr(new uint8_t[VarSize]), DevAddr(DevAddr), VarSize(VarSize) {}
37 ReplayGlobalVar() = delete;
39 if (HostAddr)
40 delete[] static_cast<uint8_t *>(HostAddr);
41 }
42
45
47 : HostAddr(Other.HostAddr), DevAddr(Other.DevAddr),
48 VarSize(Other.VarSize) {
49 Other.HostAddr = nullptr;
50 }
51
53 if (this != &Other) {
54 this->HostAddr = Other.HostAddr;
55 this->DevAddr = Other.DevAddr;
56 this->VarSize = Other.VarSize;
57 Other.HostAddr = nullptr;
58 }
59 return *this;
60 }
61};
62
63// The in-memory contents of a snapshot, as produced by the snapshot readers
64// and consumed by the replay memory state constructors.
65template <DeviceVendors VendorTypes> struct Snapshot {
66 std::shared_ptr<KernelInfo> KInfo;
67 std::unordered_map<std::string, ReplayGlobalVar> GlobalVars;
69};
70
71inline std::pair<std::string, ReplayGlobalVar>
72readGlobalVarRecord(const char *&Buffer) {
74 ReplayGlobalVar RGV(Header.DevAddr, Header.Size);
75 std::memcpy(const_cast<void *>(RGV.HostAddr), Buffer, Header.Size);
76 Buffer += Header.Size;
77 LOG_DEBUG("Loaded from buffer Global, Name:{}, VarSize:{}, RecoredAddr:{}",
78 Header.Name, Header.Size, Header.DevAddr);
79 return std::pair<std::string, ReplayGlobalVar>(std::move(Header.Name),
80 std::move(RGV));
81}
82
83// Host copies of the globals a prologue captured; the diff writer's base.
85 std::unordered_map<std::string, std::vector<uint8_t>>;
86
87enum class SnapshotKind : uint32_t { Bytes = 1, Diff = 2 };
88
89// The only code in Mneme that knows a snapshot magic string.
92 uint32_t Version;
93
94 static constexpr char Magic[8] = {'M', 'N', 'E', 'M', 'E', 'S', 'N', 'P'};
95 static constexpr size_t Size = 16;
96
97 // Returns the header and the number of prefix bytes the payload follows.
98 static std::pair<SnapshotHeader, size_t> parse(llvm::StringRef Buffer);
99 void write(llvm::raw_ostream &OS) const;
100
101private:
102 // Diff files written before the container header carried this instead.
103 static constexpr char LegacyDiffMagic[] = "MNEME_DIFF_V1";
104 static constexpr size_t LegacyDiffMagicSize = sizeof(LegacyDiffMagic) - 1;
105};
106
107inline std::pair<SnapshotHeader, size_t>
108SnapshotHeader::parse(llvm::StringRef Buffer) {
109 if (Buffer.size() >= Size &&
110 Buffer.starts_with(llvm::StringRef(Magic, sizeof(Magic)))) {
112 uint32_t Version;
113 std::memcpy(&Kind, Buffer.data() + sizeof(Magic), sizeof(Kind));
114 std::memcpy(&Version, Buffer.data() + sizeof(Magic) + sizeof(Kind),
115 sizeof(Version));
116 return {SnapshotHeader{Kind, Version}, Size};
117 }
118
119 if (Buffer.starts_with(llvm::StringRef(LegacyDiffMagic, LegacyDiffMagicSize)))
120 return {SnapshotHeader{SnapshotKind::Diff, 1}, LegacyDiffMagicSize};
121
122 return {SnapshotHeader{SnapshotKind::Bytes, 0}, 0};
123}
124
125// Bytes files carry the prefix too so that they can be versioned.
126inline void SnapshotHeader::write(llvm::raw_ostream &OS) const {
127 util::writeBytes(OS, llvm::StringRef(Magic, sizeof(Magic)));
130}
131
132template <DeviceVendors VendorTypes> class BaseSnapshotSource;
133
134// An opened snapshot file. Each subclass decodes one on-disk layout.
135template <DeviceVendors VendorTypes> class SnapshotReader {
136public:
138 std::unique_ptr<llvm::MemoryBuffer> Buffer,
139 size_t PayloadOffset)
140 : Filename(std::move(Filename)), Buffer(std::move(Buffer)),
142 virtual ~SnapshotReader() = default;
143
144 // True if read() needs a base snapshot to reconstruct the state.
145 virtual bool requiresBaseSnapshot() const = 0;
146
148 read(const std::string &KernelName,
149 const BaseSnapshotSource<VendorTypes> &Base) const = 0;
150
151protected:
152 const char *payload() const {
153 return Buffer->getBufferStart() + PayloadOffset;
154 }
155
156 std::string Filename;
157 std::unique_ptr<llvm::MemoryBuffer> Buffer;
159};
160
161// Loads a base prologue snapshot on demand for readers that need one.
162template <DeviceVendors VendorTypes> class BaseSnapshotSource {
163public:
164 // An empty Filename means no base is available.
165 explicit BaseSnapshotSource(std::string Filename = "")
166 : Filename(std::move(Filename)) {}
167
168 bool empty() const { return Filename.empty(); }
169
170 Snapshot<VendorTypes> load(const std::string &KernelName) const;
171
172private:
173 std::string Filename;
174};
175
177
178// Section decoders shared by the readers. A helper decodes a section as it
179// appears in every layout that calls it. When a new layout changes a section,
180// add a new helper instead of changing one an older reader calls.
181
182inline void
183readGlobals(const char *&Buffer,
184 std::unordered_map<std::string, ReplayGlobalVar> &GlobalVars) {
185 size_t TotalGlobals = util::extractScalar<size_t>(Buffer);
186 LOG_DEBUG("Snapshot contains {} Globals", TotalGlobals);
187 for (size_t I = 0; I < TotalGlobals; ++I) {
188 auto [Name, RGV] = readGlobalVarRecord(Buffer);
189 GlobalVars.try_emplace(Name, std::move(RGV));
190 }
191}
192
193inline void readArgs(const char *&Buffer, KernelInfo &KInfo) {
194 size_t TotalArguments = util::extractScalar<size_t>(Buffer);
195 LOG_DEBUG("Snapshot contains {} total arguments", TotalArguments);
196 KInfo.KernelArgSizes.resize(TotalArguments);
197 KInfo.ArgData.resize(TotalArguments);
198 for (size_t A = 0; A < TotalArguments; ++A) {
200 KInfo.setArgData(Buffer, A);
201 }
202}
203
204template <DeviceVendors VendorTypes>
206 const std::string &KernelName,
207 const std::string &Filename) {
208 if (Base.empty())
209 LOG_FATAL("Mneme diff snapshot " + Filename +
210 " requires a base prologue snapshot");
211 return Base.load(KernelName);
212}
213
214inline void expectCount(size_t Actual, size_t Expected,
215 const std::string &Filename, const char *What) {
216 if (Actual != Expected)
217 LOG_FATAL("Mneme diff " + Filename + " does not match prologue " + What +
218 " count");
219}
220
221// A range count followed by that many (offset, size, bytes) ranges.
222inline void applyDiffRanges(const char *&Buffer,
223 llvm::MutableArrayRef<uint8_t> Target) {
224 size_t NumRanges = util::extractScalar<size_t>(Buffer);
225 for (size_t R = 0; R < NumRanges; ++R) {
226 size_t Offset = util::extractScalar<size_t>(Buffer);
227 size_t Size = util::extractScalar<size_t>(Buffer);
228 if (Offset > Target.size() || Size > Target.size() - Offset)
229 LOG_FATAL("Malformed Mneme diff range: offset " + std::to_string(Offset) +
230 " size " + std::to_string(Size) + " exceeds target size " +
231 std::to_string(Target.size()));
232 std::memcpy(Target.data() + Offset, Buffer, Size);
233 Buffer += Size;
234 }
235}
236
237inline void
238applyGlobalDiffs(const char *&Buffer,
239 std::unordered_map<std::string, ReplayGlobalVar> &GlobalVars,
240 const std::string &Filename) {
241 size_t TotalGlobals = util::extractScalar<size_t>(Buffer);
242 expectCount(TotalGlobals, GlobalVars.size(), Filename, "global");
243 for (size_t I = 0; I < TotalGlobals; ++I) {
245 auto It = GlobalVars.find(GVH.Name);
246 if (It == GlobalVars.end())
247 LOG_FATAL("Mneme diff references global missing from prologue: " +
248 GVH.Name);
249 if (It->second.VarSize != GVH.Size)
250 LOG_FATAL("Mneme diff global size mismatch for: " + GVH.Name);
251 It->second.DevAddr = GVH.DevAddr;
252 applyDiffRanges(Buffer, llvm::MutableArrayRef<uint8_t>(
253 static_cast<uint8_t *>(It->second.HostAddr),
254 It->second.VarSize));
255 }
256}
257
258// Reads a diff blob header and returns the base blob it refers to.
259template <DeviceVendors VendorTypes>
261readDiffBlobHeader(const char *&Buffer,
262 BlobsByAddress<VendorTypes> &DeviceMemory) {
263 BlobHeader BH = BlobHeader::read(Buffer);
264 auto It = DeviceMemory.find(BH.DevAddr);
265 if (It == DeviceMemory.end())
266 LOG_FATAL("Mneme diff references device allocation missing from "
267 "prologue");
268 auto &Blob = It->second;
269 if (Blob.getActualSize() != BH.ActualSize || Blob.getSize() != BH.Size)
270 LOG_FATAL("Mneme diff memory blob size mismatch");
271 return Blob;
272}
273
274template <DeviceVendors VendorTypes>
275llvm::MutableArrayRef<uint8_t> hostBytes(MnemeMemoryBlob<VendorTypes> &Blob) {
276 return llvm::MutableArrayRef<uint8_t>(Blob.getHostData(), Blob.getSize());
277}
278
279inline void expectPayloadEnd(const char *Buffer, const llvm::MemoryBuffer &File,
280 const std::string &Filename) {
281 if (Buffer != File.getBufferEnd())
282 LOG_FATAL("Unexpected trailing bytes in Mneme snapshot " + Filename);
283}
284
285} // namespace snapshot_detail
286
287template <DeviceVendors VendorTypes>
288class BytesReaderV0 : public SnapshotReader<VendorTypes> {
289public:
290 using SnapshotReader<VendorTypes>::SnapshotReader;
291
293
294 bool requiresBaseSnapshot() const override { return false; }
295
297 read(const std::string &KernelName,
298 const BaseSnapshotSource<VendorTypes> &) const override {
300 Snap.KInfo = std::make_shared<KernelInfo>(KernelName);
301 const char *CurrentPtr = this->payload();
302
304 size_t TotalMemBlobs = util::extractScalar<size_t>(CurrentPtr);
305 for (size_t I = 0; I < TotalMemBlobs; ++I)
306 Snap.DeviceMemory.insert(
308 snapshot_detail::readArgs(CurrentPtr, *Snap.KInfo);
309 return Snap;
310 }
311};
312
313// Each blob record carries an annotation list instead of a single metadata.
314template <DeviceVendors VendorTypes>
315class BytesReaderV1 : public SnapshotReader<VendorTypes> {
316public:
317 using SnapshotReader<VendorTypes>::SnapshotReader;
318
320
321 bool requiresBaseSnapshot() const override { return false; }
322
324 read(const std::string &KernelName,
325 const BaseSnapshotSource<VendorTypes> &) const override {
327 Snap.KInfo = std::make_shared<KernelInfo>(KernelName);
328 const char *CurrentPtr = this->payload();
329
331 size_t TotalMemBlobs = util::extractScalar<size_t>(CurrentPtr);
332 for (size_t I = 0; I < TotalMemBlobs; ++I)
333 Snap.DeviceMemory.insert(
335 snapshot_detail::readArgs(CurrentPtr, *Snap.KInfo);
336 snapshot_detail::expectPayloadEnd(CurrentPtr, *this->Buffer,
337 this->Filename);
338 return Snap;
339 }
340};
341
342// A diff stores only changed ranges, so the diff readers reconstruct the full
343// base prologue first and then overlay the diff onto it.
344template <DeviceVendors VendorTypes>
345class DiffReaderV1 : public SnapshotReader<VendorTypes> {
346public:
347 using SnapshotReader<VendorTypes>::SnapshotReader;
348
350
351 bool requiresBaseSnapshot() const override { return true; }
352
354 read(const std::string &KernelName,
355 const BaseSnapshotSource<VendorTypes> &Base) const override {
357 snapshot_detail::loadDiffBase(Base, KernelName, this->Filename);
358 const char *CurrentPtr = this->payload();
359
361 this->Filename);
362 size_t TotalMemBlobs = util::extractScalar<size_t>(CurrentPtr);
363 snapshot_detail::expectCount(TotalMemBlobs, Snap.DeviceMemory.size(),
364 this->Filename, "memory blob");
365 for (size_t I = 0; I < TotalMemBlobs; ++I) {
366 auto &Blob =
368 Blob.readWholeBlobMetadata(CurrentPtr);
371 }
372 return Snap;
373 }
374};
375
376// Each blob record carries an annotation list where version 1 carried a single
377// metadata.
378template <DeviceVendors VendorTypes>
379class DiffReaderV2 : public SnapshotReader<VendorTypes> {
380public:
381 using SnapshotReader<VendorTypes>::SnapshotReader;
382
384
385 bool requiresBaseSnapshot() const override { return true; }
386
388 read(const std::string &KernelName,
389 const BaseSnapshotSource<VendorTypes> &Base) const override {
391 snapshot_detail::loadDiffBase(Base, KernelName, this->Filename);
392 const char *CurrentPtr = this->payload();
393
395 this->Filename);
396 size_t TotalMemBlobs = util::extractScalar<size_t>(CurrentPtr);
397 snapshot_detail::expectCount(TotalMemBlobs, Snap.DeviceMemory.size(),
398 this->Filename, "memory blob");
399 for (size_t I = 0; I < TotalMemBlobs; ++I) {
400 auto &Blob =
402 Blob.readAnnotations(CurrentPtr);
405 }
406 snapshot_detail::expectPayloadEnd(CurrentPtr, *this->Buffer,
407 this->Filename);
408 return Snap;
409 }
410};
411
412// Every layout Mneme has ever written needs a row here. A reader owns its
413// (kind, version) pair through its Layout member; the writer that produces
414// the current layout returns the same member from header().
415template <DeviceVendors VendorTypes> class SnapshotFormatRegistry {
416public:
417 static std::unique_ptr<SnapshotReader<VendorTypes>>
418 open(const std::string &Filename) {
419 LOG_DEBUG("Opening snapshot file {}", Filename);
420 auto Buffer = openSnapshotFile(Filename);
421 auto [Header, PayloadOffset] = SnapshotHeader::parse(Buffer->getBuffer());
422
423 size_t Count = 0;
424 const Entry *Table = table(Count);
425 for (size_t I = 0; I < Count; ++I)
426 if (Table[I].Kind == Header.Kind && Table[I].Version == Header.Version)
427 return Table[I].Make(Filename, std::move(Buffer), PayloadOffset);
428
429 LOG_FATAL("Unsupported Mneme snapshot format in " + Filename + ": kind " +
430 std::to_string(static_cast<uint32_t>(Header.Kind)) + " version " +
431 std::to_string(Header.Version));
432 }
433
434private:
435 using Factory = std::unique_ptr<SnapshotReader<VendorTypes>> (*)(
436 std::string, std::unique_ptr<llvm::MemoryBuffer>, size_t);
437
438 struct Entry {
439 SnapshotKind Kind;
440 uint32_t Version;
441 Factory Make;
442 };
443
444 template <typename ReaderT>
445 static std::unique_ptr<SnapshotReader<VendorTypes>>
446 make(std::string Filename, std::unique_ptr<llvm::MemoryBuffer> Buffer,
447 size_t PayloadOffset) {
448 return std::make_unique<ReaderT>(std::move(Filename), std::move(Buffer),
449 PayloadOffset);
450 }
451
452 template <typename ReaderT> static constexpr Entry entry() {
453 return {ReaderT::Layout.Kind, ReaderT::Layout.Version, &make<ReaderT>};
454 }
455
456 static const Entry *table(size_t &Count) {
457 static const Entry Table[] = {
458 entry<BytesReaderV0<VendorTypes>>(),
459 entry<BytesReaderV1<VendorTypes>>(),
460 entry<DiffReaderV1<VendorTypes>>(),
461 entry<DiffReaderV2<VendorTypes>>(),
462 };
463 Count = sizeof(Table) / sizeof(Table[0]);
464 return Table;
465 }
466
467 static std::unique_ptr<llvm::MemoryBuffer>
468 openSnapshotFile(const std::string &Filename) {
469 if (!std::filesystem::exists(Filename))
470 LOG_FATAL("Mneme Snapshot file does not exist");
471
472 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> BufferOrErr =
473 llvm::MemoryBuffer::getFile(Filename);
474 if (std::error_code EC = BufferOrErr.getError())
475 LOG_FATAL("Error when opening file " + EC.message());
476
477 return std::move(BufferOrErr.get());
478 }
479};
480
481template <DeviceVendors VendorTypes>
483BaseSnapshotSource<VendorTypes>::load(const std::string &KernelName) const {
484 if (empty())
485 LOG_FATAL("No base snapshot was provided");
486
487 auto Reader = SnapshotFormatRegistry<VendorTypes>::open(Filename);
488 if (Reader->requiresBaseSnapshot())
489 LOG_FATAL("Snapshot " + Filename +
490 " cannot be used as a base because it itself requires a base");
491
492 return Reader->read(KernelName, BaseSnapshotSource<VendorTypes>());
493}
494
495template <DeviceVendors VendorTypes> struct SnapshotInput {
496 const proteus::runtime::GlobalMetadataMap &GlobalVars;
498 llvm::ArrayRef<size_t> KernelArgSizes;
499 void **Args;
501};
502
503// The on-disk record prefix describing a captured global variable.
504inline GlobalVarHeader
505globalVarHeader(const std::string &Name,
506 const proteus::runtime::GlobalMetadata &GV) {
507 return GlobalVarHeader{Name, GV.VarSize, const_cast<void *>(GV.DevAddr)};
508}
509
510// The global's current contents, copied off the device.
511template <DeviceVendors VendorTypes>
512std::vector<uint8_t>
513readGlobalFromDevice(const proteus::runtime::GlobalMetadata &GV) {
514 std::vector<uint8_t> HostData(GV.VarSize);
517 HostData.data(), const_cast<void *>(GV.DevAddr), GV.VarSize,
519 if (DEC)
520 LOG_FATAL("Copying from device to host for global variable failed");
521
522 return HostData;
523}
524
525// Which writer is used is a config choice, not a property of any file.
526template <DeviceVendors VendorTypes> class SnapshotWriter {
527public:
528 virtual ~SnapshotWriter() = default;
529
530 // Returns the basename of the written file.
531 virtual std::filesystem::path
532 write(const std::filesystem::path &Filename,
533 const SnapshotInput<VendorTypes> &In) const = 0;
534
535 // The exact size write() would produce. Must not mutate any diff base.
536 virtual size_t measure(const SnapshotInput<VendorTypes> &In) const = 0;
537};
538
539// One on-disk format: a SnapshotHeader followed by a payload.
540template <DeviceVendors VendorTypes>
541class FormatWriter : public SnapshotWriter<VendorTypes> {
542public:
543 std::filesystem::path
544 write(const std::filesystem::path &Filename,
545 const SnapshotInput<VendorTypes> &In) const final {
546 LOG_DEBUG("Storing mneme snapshot: {}", Filename.string());
547 synchronize(In.Stream);
548
549 std::error_code EC;
550 llvm::raw_fd_ostream OS(Filename.string(), EC);
551 if (EC)
552 LOG_FATAL("Cannot write Mneme snapshot: " + EC.message());
553
554 header().write(OS);
555 writePayload(OS, In, /*UpdateBase=*/true);
556 return Filename.filename();
557 }
558
559 size_t measure(const SnapshotInput<VendorTypes> &In) const override {
561
562 CountingRawOStream Counter;
563 header().write(Counter);
564 writePayload(Counter, In, /*UpdateBase=*/false);
565 return Counter.bytesWritten();
566 }
567
568protected:
569 virtual SnapshotHeader header() const = 0;
570
571 // measure() passes UpdateBase=false so measuring never advances a diff base.
572 virtual void writePayload(llvm::raw_ostream &OS,
574 bool UpdateBase) const = 0;
575
576 static void
578 // Synchronize because we need a consistent GPU state. We may want to do a
579 // DeviceSynchronize().
582 if (DEC)
583 LOG_FATAL("Synchronizing stream failed before snapshot");
584 }
585
586 class CountingRawOStream : public llvm::raw_ostream {
587 uint64_t Pos = 0;
588
589 void write_impl(const char *, size_t Size) override { Pos += Size; }
590 uint64_t current_pos() const override { return Pos; }
591
592 public:
593 CountingRawOStream() : llvm::raw_ostream(/*unbuffered=*/true) {}
594 uint64_t bytesWritten() const { return tell(); }
595 };
596};
597
598template <DeviceVendors VendorTypes>
599class BytesWriter : public FormatWriter<VendorTypes> {
600public:
601 // CaptureGlobals, when set, receives the written globals as a diff base.
602 explicit BytesWriter(
603 std::shared_ptr<GlobalSnapshotData> CaptureGlobals = nullptr)
604 : CaptureGlobals(std::move(CaptureGlobals)) {}
605
606 // Computed from the layout because a counting pass would copy every blob to
607 // the host just to measure it.
608 size_t measure(const SnapshotInput<VendorTypes> &In) const override {
610 this->header().write(Counter);
611 size_t Size = Counter.bytesWritten();
612
613 Size += sizeof(size_t);
614 for (const auto &[VarName, GV] : In.GlobalVars) {
615 Size += globalVarHeader(VarName, GV).serializedSize();
616 Size += GV.VarSize;
617 }
618
619 Size += sizeof(size_t);
620 for (const auto &[Ptr, Blob] : In.DeviceMemory)
621 Size += Blob.serializedSize();
622
623 Size += sizeof(size_t);
624 for (size_t ArgSize : In.KernelArgSizes) {
625 Size += sizeof(size_t);
626 Size += ArgSize;
627 }
628 return Size;
629 }
630
631protected:
632 SnapshotHeader header() const override {
634 }
635
636 void writePayload(llvm::raw_ostream &OutBC,
637 const SnapshotInput<VendorTypes> &In, bool) const override {
638 const auto &GlobalVars = In.GlobalVars;
639 auto &DeviceMemory = In.DeviceMemory;
640 auto KernelArgSizes = In.KernelArgSizes;
641 void **Args = In.Args;
642
643 // First write Global Variables.
644 size_t TotalGlobals = GlobalVars.size();
645 OutBC << llvm::StringRef(reinterpret_cast<const char *>(&TotalGlobals),
646 sizeof(size_t));
647
648 LOG_DEBUG("Number of Globals in snapshot:{} stored at position:{}",
649 TotalGlobals, OutBC.tell());
650
651 for (const auto &[VarName, GV] : GlobalVars) {
652 std::vector<uint8_t> HostData = readGlobalFromDevice<VendorTypes>(GV);
653
654 globalVarHeader(VarName, GV).write(OutBC);
655 util::writeBytes(OutBC, llvm::ArrayRef<uint8_t>(HostData));
656 if (CaptureGlobals)
657 (*CaptureGlobals)[VarName] = std::move(HostData);
658 }
659
660 size_t TotalBlobs = DeviceMemory.size();
661 LOG_DEBUG("Number of Memory Blobs in snapshot:{} stored at position:{}",
662 TotalBlobs, OutBC.tell());
663
664 OutBC << llvm::StringRef(reinterpret_cast<const char *>(&TotalBlobs),
665 sizeof(size_t));
666
667 // Write the Device Memory
668 for (auto &[Ptr, Blob] : DeviceMemory)
669 Blob.writeWithAnnotations(OutBC);
670 // Lastly write the arguments
671 size_t NumArgs = KernelArgSizes.size();
672 LOG_DEBUG("Number of Kernel Arguments in snapshot:{} stored at position:{}",
673 NumArgs, OutBC.tell());
674
675 OutBC << llvm::StringRef(reinterpret_cast<const char *>(&NumArgs),
676 sizeof(NumArgs));
677
678 for (int I = 0; I < NumArgs; I++) {
679 OutBC << llvm::StringRef(
680 reinterpret_cast<const char *>(&KernelArgSizes[I]), sizeof(size_t));
681 OutBC << llvm::StringRef(reinterpret_cast<const char *>(Args[I]),
682 KernelArgSizes[I]);
683 }
684 }
685
686private:
687 std::shared_ptr<GlobalSnapshotData> CaptureGlobals;
688};
689
690template <DeviceVendors VendorTypes>
691class DiffWriter : public FormatWriter<VendorTypes> {
692public:
693 explicit DiffWriter(std::shared_ptr<const GlobalSnapshotData> PrologueGlobals)
694 : PrologueGlobals(std::move(PrologueGlobals)) {
695 if (!this->PrologueGlobals)
696 LOG_FATAL("A Mneme diff snapshot needs the prologue globals to diff "
697 "against");
698 }
699
700protected:
701 SnapshotHeader header() const override {
703 }
704
705 void writePayload(llvm::raw_ostream &OutBC,
707 bool UpdateBaseData) const override {
708 const auto &GlobalVars = In.GlobalVars;
709 auto &DeviceMemory = In.DeviceMemory;
710
711 size_t TotalGlobals = GlobalVars.size();
712 util::writeScalar(OutBC, TotalGlobals);
713 for (const auto &[VarName, GV] : GlobalVars) {
714 auto BaseIt = PrologueGlobals->find(VarName);
715 if (BaseIt == PrologueGlobals->end())
716 LOG_FATAL("Cannot diff global missing from prologue: " + VarName);
717 if (BaseIt->second.size() != GV.VarSize)
718 LOG_FATAL("Cannot diff global with size mismatch: " + VarName);
719
720 std::vector<uint8_t> Current = readGlobalFromDevice<VendorTypes>(GV);
721
722 globalVarHeader(VarName, GV).write(OutBC);
723
724 llvm::SmallVector<char, 0> DiffBytes;
725 llvm::raw_svector_ostream DiffOS(DiffBytes);
726 size_t NumRanges = writeChangedRanges(DiffOS, BaseIt->second, Current, 0);
727 emitRanges(OutBC, NumRanges, DiffBytes);
728 }
729
730 size_t TotalBlobs = DeviceMemory.size();
731 util::writeScalar(OutBC, TotalBlobs);
732 for (auto &[Ptr, Blob] : DeviceMemory) {
733 BlobHeader{Blob.getActualSize(), Blob.getSize(), Blob.getBlobAddr()}
734 .write(OutBC);
735 writeAnnotationsToStream(OutBC, Blob.getAnnotations());
736
737 writeCountAndWriteChangedRanges(OutBC, Blob, UpdateBaseData);
738 }
739 }
740
741private:
742 static constexpr size_t DiffChunkSize = 1 << 20;
743
744 // The reader needs the range count before the ranges themselves, so the
745 // ranges are scanned into a scratch buffer first.
746 static void emitRanges(llvm::raw_ostream &OS, size_t NumRanges,
747 const llvm::SmallVectorImpl<char> &DiffBytes) {
748 util::writeScalar(OS, NumRanges);
749 util::writeBytes(OS, llvm::StringRef(DiffBytes.data(), DiffBytes.size()));
750 }
751
752 static size_t
753 writeChangedRanges(llvm::raw_ostream &OS, llvm::ArrayRef<uint8_t> Base,
754 llvm::ArrayRef<uint8_t> Current, size_t BaseOffset,
755 llvm::MutableArrayRef<uint8_t> UpdateBase = {}) {
756 if (Base.size() != Current.size())
757 LOG_FATAL("Cannot diff buffers with different sizes");
758 if (!UpdateBase.empty() && UpdateBase.size() != Base.size())
759 LOG_FATAL("Cannot update diff base with mismatched buffer size");
760
761 // Write out the contiguous ranges that have changed between Base
762 // and Current.
763 size_t Count = 0;
764 size_t I = 0;
765 while (I < Base.size()) {
766 while (I < Base.size() && Base[I] == Current[I])
767 ++I;
768 if (I == Base.size())
769 break;
770
771 size_t Start = I;
772 while (I < Base.size() && Base[I] != Current[I])
773 ++I;
774
775 size_t Offset = BaseOffset + Start;
776 size_t Len = I - Start;
777 util::writeScalar(OS, Offset);
778 util::writeScalar(OS, Len);
779 util::writeBytes(OS, Current.slice(Start, Len));
780 if (!UpdateBase.empty())
781 std::memcpy(UpdateBase.data() + Start, Current.data() + Start, Len);
782 ++Count;
783 }
784 return Count;
785 }
786
787 static void
788 writeCountAndWriteChangedRanges(llvm::raw_ostream &OS,
789 MnemeMemoryBlob<VendorTypes> &Blob,
790 bool UpdateBaseData = true) {
791 auto Size = Blob.getSize();
792
793 // early exit
794 if (Size == 0) {
795 size_t NumRanges = 0;
796 util::writeScalar(OS, NumRanges);
797 return;
798 }
799
800 std::unique_ptr<uint8_t[]> Scratch(new uint8_t[DiffChunkSize]);
801 llvm::SmallVector<char, 0> DiffBytes;
802 llvm::raw_svector_ostream DiffOS(DiffBytes);
803 auto *Base = Blob.getHostData();
804 auto *DevAddr = static_cast<uint8_t *>(Blob.getBlobAddr());
805 size_t NumRanges = 0;
806
807 for (size_t Offset = 0; Offset < Size; Offset += DiffChunkSize) {
808 size_t ChunkSize = std::min(DiffChunkSize, Size - Offset);
809 auto EC = DeviceTraits<VendorTypes>::DeviceErrorCheck(
810 DeviceTraits<VendorTypes>::DeviceCopy(
811 Scratch.get(), DevAddr + Offset, ChunkSize,
812 DeviceTraits<VendorTypes>::MemcpyDeviceToHostKind()));
813 if (EC)
814 LOG_FATAL("Error in copying data from device when writing diff\n"
815 "Device Error Msg: " +
816 EC.value() + "\n");
817
818 llvm::ArrayRef<uint8_t> ChunkBase(Base + Offset, ChunkSize);
819 llvm::ArrayRef<uint8_t> ChunkCurrent(Scratch.get(), ChunkSize);
820 if (UpdateBaseData) {
821 llvm::MutableArrayRef<uint8_t> UpdateBase(Base + Offset, ChunkSize);
822 NumRanges += writeChangedRanges(DiffOS, ChunkBase, ChunkCurrent, Offset,
823 UpdateBase);
824 } else {
825 NumRanges +=
826 writeChangedRanges(DiffOS, ChunkBase, ChunkCurrent, Offset);
827 }
828 }
829
830 emitRanges(OS, NumRanges, DiffBytes);
831 }
832
833 std::shared_ptr<const GlobalSnapshotData> PrologueGlobals;
834};
835
836// Writes whichever of bytes or diff is smaller for this input.
837template <DeviceVendors VendorTypes>
838class BestWriter : public SnapshotWriter<VendorTypes> {
839public:
840 explicit BestWriter(std::shared_ptr<const GlobalSnapshotData> PrologueGlobals)
841 : Diff(std::move(PrologueGlobals)) {}
842
843 std::filesystem::path
844 write(const std::filesystem::path &Filename,
845 const SnapshotInput<VendorTypes> &In) const override {
846 size_t DiffSize = Diff.measure(In);
847 size_t BytesSize = Bytes.measure(In);
848
849 if (DiffSize <= BytesSize)
850 return Diff.write(Filename, In);
851
852 return Bytes.write(Filename, In);
853 }
854
855 size_t measure(const SnapshotInput<VendorTypes> &In) const override {
856 return std::min(Diff.measure(In), Bytes.measure(In));
857 }
858
859private:
862};
863
864// The only place EpilogueSnapshotType is consumed.
865template <DeviceVendors VendorTypes>
866std::unique_ptr<SnapshotWriter<VendorTypes>>
868 std::shared_ptr<const GlobalSnapshotData> PrologueGlobals) {
869 switch (Type) {
871 return std::make_unique<BytesWriter<VendorTypes>>();
873 return std::make_unique<DiffWriter<VendorTypes>>(
874 std::move(PrologueGlobals));
876 return std::make_unique<BestWriter<VendorTypes>>(
877 std::move(PrologueGlobals));
878 }
879
880 LOG_FATAL("Unknown Mneme epilogue snapshot type");
881}
882
883} // namespace mneme
#define LOG_DEBUG(...)
Definition MnemeLogger.hpp:109
#define LOG_FATAL(...)
Definition MnemeLogger.hpp:113
Definition MnemeSnapshotFormat.hpp:162
BaseSnapshotSource(std::string Filename="")
Definition MnemeSnapshotFormat.hpp:165
bool empty() const
Definition MnemeSnapshotFormat.hpp:168
Snapshot< VendorTypes > load(const std::string &KernelName) const
Definition MnemeSnapshotFormat.hpp:483
size_t measure(const SnapshotInput< VendorTypes > &In) const override
Definition MnemeSnapshotFormat.hpp:855
std::filesystem::path write(const std::filesystem::path &Filename, const SnapshotInput< VendorTypes > &In) const override
Definition MnemeSnapshotFormat.hpp:844
BestWriter(std::shared_ptr< const GlobalSnapshotData > PrologueGlobals)
Definition MnemeSnapshotFormat.hpp:840
Definition MnemeSnapshotFormat.hpp:288
static constexpr SnapshotHeader Layout
Definition MnemeSnapshotFormat.hpp:292
bool requiresBaseSnapshot() const override
Definition MnemeSnapshotFormat.hpp:294
Snapshot< VendorTypes > read(const std::string &KernelName, const BaseSnapshotSource< VendorTypes > &) const override
Definition MnemeSnapshotFormat.hpp:297
Definition MnemeSnapshotFormat.hpp:315
static constexpr SnapshotHeader Layout
Definition MnemeSnapshotFormat.hpp:319
bool requiresBaseSnapshot() const override
Definition MnemeSnapshotFormat.hpp:321
Snapshot< VendorTypes > read(const std::string &KernelName, const BaseSnapshotSource< VendorTypes > &) const override
Definition MnemeSnapshotFormat.hpp:324
Definition MnemeSnapshotFormat.hpp:599
size_t measure(const SnapshotInput< VendorTypes > &In) const override
Definition MnemeSnapshotFormat.hpp:608
BytesWriter(std::shared_ptr< GlobalSnapshotData > CaptureGlobals=nullptr)
Definition MnemeSnapshotFormat.hpp:602
SnapshotHeader header() const override
Definition MnemeSnapshotFormat.hpp:632
void writePayload(llvm::raw_ostream &OutBC, const SnapshotInput< VendorTypes > &In, bool) const override
Definition MnemeSnapshotFormat.hpp:636
Definition MnemeSnapshotFormat.hpp:345
static constexpr SnapshotHeader Layout
Definition MnemeSnapshotFormat.hpp:349
bool requiresBaseSnapshot() const override
Definition MnemeSnapshotFormat.hpp:351
Snapshot< VendorTypes > read(const std::string &KernelName, const BaseSnapshotSource< VendorTypes > &Base) const override
Definition MnemeSnapshotFormat.hpp:354
Definition MnemeSnapshotFormat.hpp:379
static constexpr SnapshotHeader Layout
Definition MnemeSnapshotFormat.hpp:383
Snapshot< VendorTypes > read(const std::string &KernelName, const BaseSnapshotSource< VendorTypes > &Base) const override
Definition MnemeSnapshotFormat.hpp:388
bool requiresBaseSnapshot() const override
Definition MnemeSnapshotFormat.hpp:385
Definition MnemeSnapshotFormat.hpp:691
DiffWriter(std::shared_ptr< const GlobalSnapshotData > PrologueGlobals)
Definition MnemeSnapshotFormat.hpp:693
SnapshotHeader header() const override
Definition MnemeSnapshotFormat.hpp:701
void writePayload(llvm::raw_ostream &OutBC, const SnapshotInput< VendorTypes > &In, bool UpdateBaseData) const override
Definition MnemeSnapshotFormat.hpp:705
Definition MnemeSnapshotFormat.hpp:586
uint64_t bytesWritten() const
Definition MnemeSnapshotFormat.hpp:594
CountingRawOStream()
Definition MnemeSnapshotFormat.hpp:593
Definition MnemeSnapshotFormat.hpp:541
virtual void writePayload(llvm::raw_ostream &OS, const SnapshotInput< VendorTypes > &In, bool UpdateBase) const =0
virtual SnapshotHeader header() const =0
size_t measure(const SnapshotInput< VendorTypes > &In) const override
Definition MnemeSnapshotFormat.hpp:559
static void synchronize(typename DeviceTraits< VendorTypes >::DeviceStream_t Stream)
Definition MnemeSnapshotFormat.hpp:577
std::filesystem::path write(const std::filesystem::path &Filename, const SnapshotInput< VendorTypes > &In) const final
Definition MnemeSnapshotFormat.hpp:544
Definition MnemeMemory.hpp:227
static std::pair< void *, MnemeMemoryBlob< VendorTypes > > readWithAnnotations(const char *&Buffer)
Definition MnemeMemory.hpp:479
uint8_t * getHostData() const
Definition MnemeMemory.hpp:547
static std::pair< void *, MnemeMemoryBlob< VendorTypes > > readWithMetadata(const char *&Buffer)
Definition MnemeMemory.hpp:468
uint64_t getSize() const
Definition MnemeMemory.hpp:545
Definition MnemeSnapshotFormat.hpp:415
static std::unique_ptr< SnapshotReader< VendorTypes > > open(const std::string &Filename)
Definition MnemeSnapshotFormat.hpp:418
SnapshotReader(std::string Filename, std::unique_ptr< llvm::MemoryBuffer > Buffer, size_t PayloadOffset)
Definition MnemeSnapshotFormat.hpp:137
virtual Snapshot< VendorTypes > read(const std::string &KernelName, const BaseSnapshotSource< VendorTypes > &Base) const =0
virtual ~SnapshotReader()=default
virtual bool requiresBaseSnapshot() const =0
std::string Filename
Definition MnemeSnapshotFormat.hpp:156
const char * payload() const
Definition MnemeSnapshotFormat.hpp:152
std::unique_ptr< llvm::MemoryBuffer > Buffer
Definition MnemeSnapshotFormat.hpp:157
size_t PayloadOffset
Definition MnemeSnapshotFormat.hpp:158
Definition MnemeSnapshotFormat.hpp:526
virtual ~SnapshotWriter()=default
virtual size_t measure(const SnapshotInput< VendorTypes > &In) const =0
virtual std::filesystem::path write(const std::filesystem::path &Filename, const SnapshotInput< VendorTypes > &In) const =0
int64_t u64 Size
Definition cupti_profile.cpp:179
Definition attribute.cpp:39
Definition MnemeSnapshotFormat.hpp:176
llvm::MutableArrayRef< uint8_t > hostBytes(MnemeMemoryBlob< VendorTypes > &Blob)
Definition MnemeSnapshotFormat.hpp:275
void applyDiffRanges(const char *&Buffer, llvm::MutableArrayRef< uint8_t > Target)
Definition MnemeSnapshotFormat.hpp:222
void expectPayloadEnd(const char *Buffer, const llvm::MemoryBuffer &File, const std::string &Filename)
Definition MnemeSnapshotFormat.hpp:279
void applyGlobalDiffs(const char *&Buffer, std::unordered_map< std::string, ReplayGlobalVar > &GlobalVars, const std::string &Filename)
Definition MnemeSnapshotFormat.hpp:238
MnemeMemoryBlob< VendorTypes > & readDiffBlobHeader(const char *&Buffer, BlobsByAddress< VendorTypes > &DeviceMemory)
Definition MnemeSnapshotFormat.hpp:261
void readGlobals(const char *&Buffer, std::unordered_map< std::string, ReplayGlobalVar > &GlobalVars)
Definition MnemeSnapshotFormat.hpp:183
void expectCount(size_t Actual, size_t Expected, const std::string &Filename, const char *What)
Definition MnemeSnapshotFormat.hpp:214
Snapshot< VendorTypes > loadDiffBase(const BaseSnapshotSource< VendorTypes > &Base, const std::string &KernelName, const std::string &Filename)
Definition MnemeSnapshotFormat.hpp:205
void readArgs(const char *&Buffer, KernelInfo &KInfo)
Definition MnemeSnapshotFormat.hpp:193
void writeBytes(llvm::raw_ostream &OS, llvm::StringRef Data)
Definition MnemeLLVMUtils.hpp:44
Ty extractScalar(const char *&Buffer)
Definition MnemeUtils.hpp:19
void writeScalar(llvm::raw_ostream &OS, const Ty &Value)
Definition MnemeLLVMUtils.hpp:40
Definition MnemeAnnotation.cpp:3
std::pair< std::string, ReplayGlobalVar > readGlobalVarRecord(const char *&Buffer)
Definition MnemeSnapshotFormat.hpp:72
void writeAnnotationsToStream(llvm::raw_ostream &OS, const std::vector< MemoryAnnotation > &Annotations)
Definition MnemeMemory.hpp:75
std::unique_ptr< SnapshotWriter< VendorTypes > > makeEpilogueWriter(EpilogueSnapshotType Type, std::shared_ptr< const GlobalSnapshotData > PrologueGlobals)
Definition MnemeSnapshotFormat.hpp:867
std::vector< uint8_t > readGlobalFromDevice(const proteus::runtime::GlobalMetadata &GV)
Definition MnemeSnapshotFormat.hpp:513
std::unordered_map< std::string, std::vector< uint8_t > > GlobalSnapshotData
Definition MnemeSnapshotFormat.hpp:84
GlobalVarHeader globalVarHeader(const std::string &Name, const proteus::runtime::GlobalMetadata &GV)
Definition MnemeSnapshotFormat.hpp:505
EpilogueSnapshotType
Definition MnemeConfig.hpp:24
@ Diff
Definition MnemeConfig.hpp:24
@ Bytes
Definition MnemeConfig.hpp:24
@ Best
Definition MnemeConfig.hpp:24
SnapshotKind
Definition MnemeSnapshotFormat.hpp:87
@ Diff
Definition MnemeSnapshotFormat.hpp:87
@ Bytes
Definition MnemeSnapshotFormat.hpp:87
std::map< void *, MnemeMemoryBlob< VendorTypes > > BlobsByAddress
Definition MnemeMemory.hpp:605
Definition MnemeSnapshotRecords.hpp:41
size_t ActualSize
Definition MnemeSnapshotRecords.hpp:42
void write(llvm::raw_ostream &OS) const
Definition MnemeSnapshotRecords.hpp:46
void * DevAddr
Definition MnemeSnapshotRecords.hpp:44
size_t Size
Definition MnemeSnapshotRecords.hpp:43
static BlobHeader read(const char *&Buffer)
Definition MnemeSnapshotRecords.hpp:52
Definition DeviceTraits.hpp:73
Definition MnemeSnapshotRecords.hpp:15
static GlobalVarHeader read(const char *&Buffer)
Definition MnemeSnapshotRecords.hpp:27
size_t serializedSize() const
Definition MnemeSnapshotRecords.hpp:34
void * DevAddr
Definition MnemeSnapshotRecords.hpp:18
void write(llvm::raw_ostream &OS) const
Definition MnemeSnapshotRecords.hpp:20
size_t Size
Definition MnemeSnapshotRecords.hpp:17
std::string Name
Definition MnemeSnapshotRecords.hpp:16
Definition MnemeKernelInfo.hpp:13
void setArgData(const char *&Data, int Index)
Definition MnemeKernelInfo.hpp:39
llvm::SmallVector< size_t > KernelArgSizes
Definition MnemeKernelInfo.hpp:17
llvm::SmallVector< std::unique_ptr< uint8_t[]> > ArgData
Definition MnemeKernelInfo.hpp:21
Definition MnemeSnapshotFormat.hpp:29
ReplayGlobalVar(void *DevAddr, uint64_t VarSize)
Definition MnemeSnapshotFormat.hpp:33
void * HostAddr
Definition MnemeSnapshotFormat.hpp:30
void * DevAddr
Definition MnemeSnapshotFormat.hpp:31
ReplayGlobalVar & operator=(const ReplayGlobalVar &)=delete
~ReplayGlobalVar()
Definition MnemeSnapshotFormat.hpp:38
ReplayGlobalVar & operator=(ReplayGlobalVar &&Other)
Definition MnemeSnapshotFormat.hpp:52
uint64_t VarSize
Definition MnemeSnapshotFormat.hpp:32
ReplayGlobalVar(const ReplayGlobalVar &)=delete
ReplayGlobalVar(ReplayGlobalVar &&Other)
Definition MnemeSnapshotFormat.hpp:46
ReplayGlobalVar(void *HostAddr, void *DevAddr, uint64_t VarSize)
Definition MnemeSnapshotFormat.hpp:35
Definition MnemeSnapshotFormat.hpp:90
static std::pair< SnapshotHeader, size_t > parse(llvm::StringRef Buffer)
Definition MnemeSnapshotFormat.hpp:108
SnapshotKind Kind
Definition MnemeSnapshotFormat.hpp:91
static constexpr size_t Size
Definition MnemeSnapshotFormat.hpp:95
static constexpr char Magic[8]
Definition MnemeSnapshotFormat.hpp:94
uint32_t Version
Definition MnemeSnapshotFormat.hpp:92
void write(llvm::raw_ostream &OS) const
Definition MnemeSnapshotFormat.hpp:126
Definition MnemeSnapshotFormat.hpp:495
const proteus::runtime::GlobalMetadataMap & GlobalVars
Definition MnemeSnapshotFormat.hpp:496
DeviceTraits< VendorTypes >::DeviceStream_t Stream
Definition MnemeSnapshotFormat.hpp:500
void ** Args
Definition MnemeSnapshotFormat.hpp:499
BlobsByAddress< VendorTypes > & DeviceMemory
Definition MnemeSnapshotFormat.hpp:497
llvm::ArrayRef< size_t > KernelArgSizes
Definition MnemeSnapshotFormat.hpp:498
Definition MnemeSnapshotFormat.hpp:65
BlobsByAddress< VendorTypes > DeviceMemory
Definition MnemeSnapshotFormat.hpp:68
std::shared_ptr< KernelInfo > KInfo
Definition MnemeSnapshotFormat.hpp:66
std::unordered_map< std::string, ReplayGlobalVar > GlobalVars
Definition MnemeSnapshotFormat.hpp:67