Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

♻️ Move templated function and methods to header files for reuse in dd sim #856

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
130 changes: 130 additions & 0 deletions include/mqt-core/dd/FunctionalityConstruction.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,10 @@

#include "dd/Package_fwd.hpp"
#include "ir/QuantumComputation.hpp"
#include "ir/operations/OpType.hpp"

#include <cstddef>
#include <stack>

Check warning on line 17 in include/mqt-core/dd/FunctionalityConstruction.hpp

View workflow job for this annotation

GitHub Actions / 🇨‌ Lint / 🚨 Lint

include/mqt-core/dd/FunctionalityConstruction.hpp:17:1 [misc-include-cleaner]

included header stack is not used directly

namespace dd {
using namespace qc;
Expand Down Expand Up @@ -74,4 +78,130 @@
MatrixDD buildFunctionalityRecursive(const QuantumComputation& qc,
Package<Config>& dd);

///-----------------------------------------------------------------------------
/// \n Method Definitions \n
///-----------------------------------------------------------------------------

template <class Config>
MatrixDD buildFunctionality(const QuantumComputation& qc, Package<Config>& dd) {
if (qc.getNqubits() == 0U) {
return MatrixDD::one();
}

auto permutation = qc.initialLayout;
auto e = dd.createInitialMatrix(qc.getAncillary());

for (const auto& op : qc) {
// SWAP gates can be executed virtually by changing the permutation
if (op->getType() == OpType::SWAP && !op->isControlled()) {
const auto& targets = op->getTargets();
std::swap(permutation.at(targets[0U]), permutation.at(targets[1U]));
continue;
}

e = applyUnitaryOperation(*op, e, dd, permutation);
}
// correct permutation if necessary
changePermutation(e, permutation, qc.outputPermutation, dd);
e = dd.reduceAncillae(e, qc.getAncillary());
e = dd.reduceGarbage(e, qc.getGarbage());

return e;
}

template <class Config>
bool buildFunctionalityRecursive(const QuantumComputation& qc,
std::size_t depth, std::size_t opIdx,
std::stack<MatrixDD>& s,
Permutation& permutation,
Package<Config>& dd) {
// base case
if (depth == 1U) {
auto e = dd.makeIdent();
if (const auto& op = qc.at(opIdx);
op->getType() == OpType::SWAP && !op->isControlled()) {
const auto& targets = op->getTargets();
std::swap(permutation.at(targets[0U]), permutation.at(targets[1U]));
} else {
e = getDD(*qc.at(opIdx), dd, permutation);
}
++opIdx;
if (opIdx == qc.size()) {
// only one element was left
s.push(e);
dd.incRef(e);
return false;
}
auto f = dd.makeIdent();
if (const auto& op = qc.at(opIdx);
op->getType() == OpType::SWAP && !op->isControlled()) {
const auto& targets = op->getTargets();
std::swap(permutation.at(targets[0U]), permutation.at(targets[1U]));
} else {
f = getDD(*qc.at(opIdx), dd, permutation);
}
s.push(dd.multiply(f, e)); // ! reverse multiplication
dd.incRef(s.top());
return (opIdx != qc.size() - 1U);
}

// in case no operations are left after the first recursive call nothing has
// to be done
const std::size_t leftIdx =
opIdx & ~(static_cast<std::size_t>(1U) << (depth - 1U));
if (!buildFunctionalityRecursive(qc, depth - 1U, leftIdx, s, permutation,
dd)) {
return false;
}

const std::size_t rightIdx =
opIdx | (static_cast<std::size_t>(1U) << (depth - 1U));
const auto success =
buildFunctionalityRecursive(qc, depth - 1U, rightIdx, s, permutation, dd);

// get latest two results from stack and push their product on the stack
auto e = s.top();
s.pop();
auto f = s.top();
s.pop();
s.push(dd.multiply(e, f)); // ordering because of stack structure

// reference counting
dd.decRef(e);
dd.decRef(f);
dd.incRef(s.top());
dd.garbageCollect();

return success;
}

template <class Config>
MatrixDD buildFunctionalityRecursive(const QuantumComputation& qc,
Package<Config>& dd) {
if (qc.getNqubits() == 0U) {
return MatrixDD::one();
}

auto permutation = qc.initialLayout;

if (qc.size() == 1U) {
auto e = getDD(*qc.front(), dd, permutation);
dd.incRef(e);
return e;
}

std::stack<MatrixDD> s{};
auto depth = static_cast<std::size_t>(std::ceil(std::log2(qc.size())));
buildFunctionalityRecursive(qc, depth, 0, s, permutation, dd);
auto e = s.top();
s.pop();

// correct permutation if necessary
changePermutation(e, permutation, qc.outputPermutation, dd);
e = dd.reduceAncillae(e, qc.getAncillary());
e = dd.reduceGarbage(e, qc.getGarbage());

return e;
}

} // namespace dd
73 changes: 73 additions & 0 deletions include/mqt-core/dd/MemoryManager.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
#include "dd/DDDefinitions.hpp"
#include "dd/statistics/MemoryManagerStatistics.hpp"

#include <cassert>
#include <cstddef>
#include <type_traits>
#include <vector>
Expand Down Expand Up @@ -177,4 +178,76 @@ template <typename T> class MemoryManager {
MemoryManagerStatistics<T> stats{};
};

///-----------------------------------------------------------------------------
/// \n Method Definitions \n
///-----------------------------------------------------------------------------

template <typename T> T* MemoryManager<T>::get() {
if (entryAvailableForReuse()) {
return getEntryFromAvailableList();
}

if (!entryAvailableInChunk()) {
allocateNewChunk();
}

return getEntryFromChunk();
}

template <typename T> void MemoryManager<T>::returnEntry(T* entry) noexcept {
assert(entry != nullptr);
assert(entry->ref == 0);
entry->next = available;
available = entry;
stats.trackReturnedEntry();
}

template <typename T>
void MemoryManager<T>::reset(const bool resizeToTotal) noexcept {
available = nullptr;

auto numAllocations = stats.numAllocations;
chunks.resize(1U);
if (resizeToTotal) {
chunks[0].resize(stats.numAllocated);
++numAllocations;
}

chunkIt = chunks[0].begin();
chunkEndIt = chunks[0].end();

stats.reset();
stats.numAllocations = numAllocations;
stats.numAllocated = chunks[0].size();
}

template <typename T>
T* MemoryManager<T>::getEntryFromAvailableList() noexcept {
assert(entryAvailableForReuse());
auto* entry = available;
available = available->next;
stats.trackReusedEntries();
return entry;
}

template <typename T> void MemoryManager<T>::allocateNewChunk() {
assert(!entryAvailableInChunk());
const auto newChunkSize = static_cast<std::size_t>(
GROWTH_FACTOR * static_cast<double>(chunks.back().size()));
chunks.emplace_back(newChunkSize);
chunkIt = chunks.back().begin();
chunkEndIt = chunks.back().end();
++stats.numAllocations;
stats.numAllocated += newChunkSize;
}

template <typename T> T* MemoryManager<T>::getEntryFromChunk() noexcept {
assert(!entryAvailableForReuse());
assert(entryAvailableInChunk());
auto* entry = &(*chunkIt);
++chunkIt;
stats.trackUsedEntries();
return entry;
}

} // namespace dd
5 changes: 0 additions & 5 deletions include/mqt-core/dd/UniqueTable.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -36,11 +36,6 @@ namespace dd {
*/
template <class Node, std::size_t NBUCKET = 32768> class UniqueTable {

static_assert(
std::disjunction_v<std::is_same<Node, vNode>, std::is_same<Node, mNode>,
std::is_same<Node, dNode>>,
"Node type must be one of vNode, mNode, dNode");

public:
/**
* @brief The initial garbage collection limit.
Expand Down
89 changes: 89 additions & 0 deletions include/mqt-core/dd/statistics/MemoryManagerStatistics.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@
#include "dd/statistics/Statistics.hpp"
#include "nlohmann/json_fwd.hpp"

#include <algorithm>
#include <cstddef>
#include <nlohmann/json.hpp>

namespace dd {

Expand Down Expand Up @@ -73,4 +75,91 @@ template <typename T> struct MemoryManagerStatistics : public Statistics {
[[nodiscard]] nlohmann::json json() const override;
};

///-----------------------------------------------------------------------------
/// \n Method Definitions \n
///-----------------------------------------------------------------------------

template <typename T>
std::size_t
MemoryManagerStatistics<T>::getNumAvailableFromChunks() const noexcept {
return getTotalNumAvailable() - numAvailableForReuse;
}

template <typename T>
std::size_t MemoryManagerStatistics<T>::getTotalNumAvailable() const noexcept {
return numAllocated - numUsed;
}

template <typename T>
double MemoryManagerStatistics<T>::getUsageRatio() const noexcept {
return static_cast<double>(numUsed) / static_cast<double>(numAllocated);
}

template <typename T>
double MemoryManagerStatistics<T>::getAllocatedMemoryMiB() const noexcept {
return static_cast<double>(numAllocated) * ENTRY_MEMORY_MIB;
}

template <typename T>
double MemoryManagerStatistics<T>::getUsedMemoryMiB() const noexcept {
return static_cast<double>(numUsed) * ENTRY_MEMORY_MIB;
}

template <typename T>
double MemoryManagerStatistics<T>::getPeakUsedMemoryMiB() const noexcept {
return static_cast<double>(peakNumUsed) * ENTRY_MEMORY_MIB;
}

template <typename T>
void MemoryManagerStatistics<T>::trackUsedEntries(
const std::size_t numEntries) noexcept {
numUsed += numEntries;
peakNumUsed = std::max(peakNumUsed, numUsed);
}

template <typename T>
void MemoryManagerStatistics<T>::trackReusedEntries(
const std::size_t numEntries) noexcept {
numUsed += numEntries;
peakNumUsed = std::max(peakNumUsed, numUsed);
numAvailableForReuse -= numEntries;
}

template <typename T>
void MemoryManagerStatistics<T>::trackReturnedEntry() noexcept {
++numAvailableForReuse;
peakNumAvailableForReuse =
std::max(peakNumAvailableForReuse, numAvailableForReuse);
--numUsed;
}

template <typename T> void MemoryManagerStatistics<T>::reset() noexcept {
numAllocations = 0U;
numAllocated = 0U;
numUsed = 0U;
numAvailableForReuse = 0U;
}

template <typename T>
nlohmann::basic_json<> MemoryManagerStatistics<T>::json() const {
if (peakNumUsed == 0) {
return "unused";
}

auto j = Statistics::json();
j["memory_allocated_MiB"] = getAllocatedMemoryMiB();
j["memory_used_MiB"] = getUsedMemoryMiB();
j["memory_used_MiB_peak"] = getPeakUsedMemoryMiB();
j["num_allocated"] = numAllocated;
j["num_allocations"] = numAllocations;
j["num_available_for_reuse"] = numAvailableForReuse;
j["num_available_for_reuse_peak"] = peakNumAvailableForReuse;
j["num_available_from_chunks"] = getNumAvailableFromChunks();
j["num_available_total"] = getTotalNumAvailable();
j["num_used"] = numUsed;
j["num_used_peak"] = peakNumUsed;
j["usage_ratio"] = getUsageRatio();
return j;
}

} // namespace dd
Loading
Loading