Skip to content
Snippets Groups Projects
MemoryManager.cpp 32.4 KiB
Newer Older
/********************************************************************************
 * Copyright (c) 2023 CEA-List
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License 2.0 which is available at
 * http://www.eclipse.org/legal/epl-2.0.
 *
 * SPDX-License-Identifier: EPL-2.0
 *
 ********************************************************************************/

#include <fmt/format.h>

#include "aidge/scheduler/MemoryManager.hpp"
#include "aidge/utils/ErrorHandling.hpp"

Aidge::MemoryManager::~MemoryManager() noexcept = default;

19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916
std::shared_ptr<Aidge::MemoryManager::MemorySpace> Aidge::MemoryManager::reserve(
    unsigned int size,
    const std::set<std::shared_ptr<Node> >& dependencies)
{
    const unsigned int offset = onStack(size);

    std::shared_ptr<MemorySpace> memSpace
        = std::make_shared<MemorySpace>(mClock, offset, size, dependencies);
    mMemSpaces.push_back(memSpace);
    return memSpace;
}

void Aidge::MemoryManager::expand(
    std::shared_ptr<MemorySpace> memSpace,
    unsigned int requiredSize)
{
    assert(std::find(mMemSpaces.begin(), mMemSpaces.end(), memSpace)
            != mMemSpaces.end());

    memSpace->size = std::max(memSpace->size, requiredSize);

    // Rebuild the stack from the beginning, taking into account the new size.
    // Everything else stay the same.
    mMemStack.clear();

    for (Clock_T clock = 0; clock <= mClock; ++clock) {
        for (std::vector<std::shared_ptr<MemorySpace> >::iterator
            it = mMemSpaces.begin(), itEnd = mMemSpaces.end(); it != itEnd;
            ++it)
        {
            if ((*it)->allocated == clock)
                (*it)->offset = onStack((*it)->size);
        }

        // MemorySpace released at clock are still valid until the next tick;
        // make sure offStack() only append after all onStack() are done.
        for (std::vector<std::shared_ptr<MemorySpace> >::iterator
            it = mMemSpaces.begin(), itEnd = mMemSpaces.end(); it != itEnd;
            ++it)
        {
            if ((*it)->released == clock && (*it)->dependencies.empty())
                offStack((*it)->offset);
        }
    }
}

Aidge::MemoryManager::MemoryPlane Aidge::MemoryManager::allocate(
    unsigned int size,
    const std::set<std::shared_ptr<Node> >& dependencies,
    unsigned int stride,
    unsigned int length,
    unsigned int count)
{
    const unsigned int fullSize = std::max(size, stride) * length * count;
    return MemoryPlane(reserve(fullSize, dependencies),
                       mClock, 0, size, stride, length, count);
}

unsigned int Aidge::MemoryManager::allocate(
    const std::shared_ptr<Node>& node,
    unsigned int size,
    const std::set<std::shared_ptr<Node> >& dependencies,
    unsigned int stride,
    unsigned int length,
    unsigned int count)
{
    std::map<std::shared_ptr<Node>, std::vector<MemoryPlane> >::iterator it;
    std::tie(it, std::ignore) = mMemPlanes.insert(std::make_pair(node,
                                                std::vector<MemoryPlane>()));

    (*it).second.push_back(allocate(size, dependencies, stride, length, count));
    return ((*it).second.size() - 1);
}

bool Aidge::MemoryManager::isWrapAround(
    std::shared_ptr<MemorySpace> memSpace,
    unsigned int offset,
    unsigned int size,
    unsigned int stride,
    unsigned int length,
    unsigned int count) const
{
    const unsigned int fullSize = std::max(size, stride) * length * count;
    return (offset + fullSize > memSpace->size);
}

Aidge::MemoryManager::MemoryPlane Aidge::MemoryManager::reallocate(
    std::shared_ptr<MemorySpace> memSpace,
    unsigned int offset,
    unsigned int size,
    bool wrapAround,
    unsigned int extraSize,
    const std::set<std::shared_ptr<Node> >& additionalDependencies,
    unsigned int stride,
    unsigned int length,
    unsigned int count)
{
    const unsigned int fullSize = std::max(size, stride) * length * count;
    unsigned int requiredSize = offset + fullSize;

    if (wrapAround) {
        requiredSize = fullSize + extraSize;

        if (count > 1) {
            // (requiredSize - offset) must be a multiple of (stride * length)
            requiredSize = offset
                + std::ceil((requiredSize - offset)
                    / static_cast<double>(std::max(size, stride) * length))
                        * (std::max(size, stride) * length);
        }
        else if (length > 1) {
            // (requiredSize - offset) must be a multiple of stride
            requiredSize = offset
                + std::ceil((requiredSize - offset)
                    / static_cast<double>(std::max(size, stride)))
                        * std::max(size, stride);
        }
    }

    if (requiredSize > memSpace->size || memSpace->released >= 0) {
        // Expand in size and/or duration.
        // If memSpace was already released, put it back on the stack
        memSpace->released = -1;
        expand(memSpace, requiredSize);
    }

    memSpace->dependencies.insert(additionalDependencies.begin(),
                                  additionalDependencies.end());

    return MemoryPlane(memSpace, mClock, offset, size, stride, length, count);
}

Aidge::MemoryManager::MemoryPlane Aidge::MemoryManager::reallocate(
    const MemoryPlane& memPlane,
    unsigned int extraOffset,
    unsigned int size,
    bool wrapAround,
    unsigned int extraSize,
    const std::set<std::shared_ptr<Node> >& additionalDependencies,
    unsigned int stride,
    unsigned int length,
    unsigned int count)
{
    const unsigned int initialOffset = memPlane.getFinalOffset()
        - memPlane.memSpace->offset + extraOffset;
    const unsigned int fullSize = std::max(size, stride) * length * count;
    unsigned int requiredSize = initialOffset + fullSize;

    if (wrapAround) {
        requiredSize = fullSize + extraSize;

        if (count > 1) {
            // (requiredSize - offset) must be a multiple of (stride * length)
            requiredSize = initialOffset
                + std::ceil((requiredSize - initialOffset)
                    / static_cast<double>(std::max(size, stride) * length))
                        * (std::max(size, stride) * length);
        }
        else if (length > 1) {
            // (requiredSize - offset) must be a multiple of stride
            requiredSize = initialOffset
                + std::ceil((requiredSize - initialOffset)
                    / static_cast<double>(std::max(size, stride)))
                        * std::max(size, stride);
        }

        // Make sure that the intended margin with previous memPlane will be
        // respected, as it may actually be lower because of the floor()
        // in the memPlane getLimit() function.
        if (memPlane.count > 1) {
            requiredSize = memPlane.offset
                + std::ceil((requiredSize - memPlane.offset)
                    / static_cast<double>(memPlane.stride * memPlane.length))
                        * (memPlane.stride * memPlane.length);
        }
        else if (memPlane.length > 1) {
            requiredSize = memPlane.offset
                + std::ceil((requiredSize - memPlane.offset)
                    / static_cast<double>(memPlane.stride))
                        * memPlane.stride;
        }
    }

    if (requiredSize > memPlane.memSpace->size
        || memPlane.memSpace->released >= 0)
    {
        // Expand in size and/or duration.
        // If memSpace was already released, put it back on the stack
        memPlane.memSpace->released = -1;
        expand(memPlane.memSpace, requiredSize);
    }

    memPlane.memSpace->dependencies.insert(
        additionalDependencies.begin(),
        additionalDependencies.end());

    const unsigned int finalOffset = memPlane.getFinalOffset()
        - memPlane.memSpace->offset + extraOffset;

    return MemoryPlane(memPlane.memSpace, mClock,
                       finalOffset, size, stride, length, count);
}

unsigned int Aidge::MemoryManager::reallocate(
    const MemoryPlane& memPlane,
    const std::shared_ptr<Node>& node,
    unsigned int extraOffset,
    unsigned int size,
    bool wrapAround,
    unsigned int extraSize,
    const std::set<std::shared_ptr<Node> >& additionalDependencies,
    unsigned int stride,
    unsigned int length,
    unsigned int count)
{
    std::map<std::shared_ptr<Node>, std::vector<MemoryPlane> >::iterator it;
    std::tie(it, std::ignore) = mMemPlanes.insert(std::make_pair(node,
                                                std::vector<MemoryPlane>()));

    (*it).second.push_back(reallocate(memPlane, extraOffset, size, wrapAround,
                                      extraSize, additionalDependencies,
                                      stride, length, count));
    return ((*it).second.size() - 1);
}

unsigned int Aidge::MemoryManager::reallocate(
    std::shared_ptr<MemorySpace> memSpace,
    const std::shared_ptr<Node>& node,
    unsigned int offset,
    unsigned int size,
    bool wrapAround,
    unsigned int extraSize,
    const std::set<std::shared_ptr<Node> >& additionalDependencies,
    unsigned int stride,
    unsigned int length,
    unsigned int count)
{
    std::map<std::shared_ptr<Node>, std::vector<MemoryPlane> >::iterator it;
    std::tie(it, std::ignore) = mMemPlanes.insert(std::make_pair(node,
                                                std::vector<MemoryPlane>()));

    (*it).second.push_back(reallocate(memSpace, offset, size, wrapAround,
                                      extraSize, additionalDependencies,
                                      stride, length, count));
    return ((*it).second.size() - 1);
}

unsigned int Aidge::MemoryManager::release(std::shared_ptr<MemorySpace> memSpace)
{
    if (memSpace->released == -1) {
        memSpace->released = mClock;

        if (memSpace->dependencies.empty())
            return offStack(memSpace->offset);
    }

    return 0;
}

unsigned int Aidge::MemoryManager::release(const std::shared_ptr<Node>& node)
{
    const std::map<std::shared_ptr<Node>, std::vector<MemoryPlane> >
        ::iterator it = mMemPlanes.find(node);

    if (it == mMemPlanes.end()) {
        fmt::print("Warning: release(): there is no allocated memory for node {}\n", node->name());
        return 0;
    }

    unsigned int releasedMemSize = 0;

    for (std::vector<MemoryPlane>::iterator itPlanes = (*it).second.begin(),
        itPlanesEnd = (*it).second.end(); itPlanes != itPlanesEnd; ++itPlanes)
    {
        releasedMemSize += release((*itPlanes).memSpace);
    }

    // Remove dependencies
    releasedMemSize += releaseDependencies(node);

    return releasedMemSize;
}

unsigned int Aidge::MemoryManager::releaseDependencies(
    const std::shared_ptr<Node>& node)
{
    unsigned int releasedMemSize = 0;

    for (std::vector<std::shared_ptr<MemorySpace> >::iterator
        it = mMemSpaces.begin(), itEnd = mMemSpaces.end(); it != itEnd;
        ++it)
    {
        if (!(*it)->dependencies.empty()) {
            (*it)->dependencies.erase(node);

            if ((*it)->released <= mClock
                && (*it)->dependencies.empty())
            {
                (*it)->released = mClock;
                releasedMemSize += offStack((*it)->offset);
            }
        }
    }

    return releasedMemSize;
}

bool Aidge::MemoryManager::MaxLifetimeMinSizeFirst::operator()(
    const std::shared_ptr<MemorySpace>& p0,
    const std::shared_ptr<MemorySpace>& p1)
{
    const Clock_T lifetime0
        = ((p0->released >= 0) ? p0->released : maxLifetime) - p0->allocated;
    const Clock_T lifetime1
        = ((p1->released >= 0) ? p1->released : maxLifetime) - p1->allocated;

    return (lifetime0 > lifetime1
            || (lifetime0 == lifetime1 && p0->size < p1->size));
}

bool Aidge::MemoryManager::MaxLifetimeMaxSizeFirst::operator()(
    const std::shared_ptr<MemorySpace>& p0,
    const std::shared_ptr<MemorySpace>& p1)
{
    const Clock_T lifetime0
        = ((p0->released >= 0) ? p0->released : maxLifetime) - p0->allocated;
    const Clock_T lifetime1
        = ((p1->released >= 0) ? p1->released : maxLifetime) - p1->allocated;

    return (lifetime0 > lifetime1
            || (lifetime0 == lifetime1 && p0->size > p1->size));
}

bool Aidge::MemoryManager::MaxHoleMaxLifetimeFirst::operator()(
    const std::shared_ptr<MemorySpace>& p0,
    const std::shared_ptr<MemorySpace>& p1)
{
    const Clock_T lifetime0
        = ((p0->released >= 0) ? p0->released : maxLifetime) - p0->allocated;
    const Clock_T lifetime1
        = ((p1->released >= 0) ? p1->released : maxLifetime) - p1->allocated;

    const std::pair<Clock_T, unsigned int> maxHole0 = inst->getMaxHole(p0);
    const std::pair<Clock_T, unsigned int> maxHole1 = inst->getMaxHole(p1);

    return (maxHole0.second > maxHole1.second
            || (maxHole0.second == maxHole1.second && lifetime0 > lifetime1));
}

void Aidge::MemoryManager::optimize(OptimizeStrategy strategy) {
    if (strategy == None)
        return;

    const unsigned int maxLifetime = getMaxLifetime();

    if (strategy == OptimizeMaxLifetimeMinSizeFirst) {
        std::stable_sort(mMemSpaces.begin(), mMemSpaces.end(),
                        MemoryManager::MaxLifetimeMinSizeFirst(maxLifetime));
    }
    else if (strategy == OptimizeMaxLifetimeMaxSizeFirst) {
        std::stable_sort(mMemSpaces.begin(), mMemSpaces.end(),
                        MemoryManager::MaxLifetimeMaxSizeFirst(maxLifetime));
    }
    else if (strategy == OptimizeMaxHoleMaxLifetimeFirst) {
        std::stable_sort(mMemSpaces.begin(), mMemSpaces.end(),
                        MemoryManager::MaxHoleMaxLifetimeFirst(maxLifetime, this));
    }

    std::vector<std::map<unsigned int, unsigned int> > stacks(maxLifetime + 1,
                                        std::map<unsigned int, unsigned int>());

    for (std::vector<std::shared_ptr<MemorySpace> >::const_iterator
        it = mMemSpaces.begin(), itEnd = mMemSpaces.end(); it != itEnd; ++it)
    {
        const Clock_T maxT = ((*it)->released >= 0
                                && (*it)->dependencies.empty())
                                    ? (*it)->released : maxLifetime;

        // Merge stacks over memSpace lifetime
        std::map<unsigned int, unsigned int> mergedStacks;

        for (Clock_T t = (*it)->allocated; t <= maxT; ++t) {
            for (std::map<unsigned int, unsigned int>::iterator itMem
                = stacks[t].begin(), itMemEnd = stacks[t].end();
                itMem != itMemEnd; ++itMem)
            {
                bool newInsert;
                std::map<unsigned int, unsigned int>::iterator itMergedMem;
                std::tie(itMergedMem, newInsert) = mergedStacks.insert(
                    std::make_pair((*itMem).first, (*itMem).second));

                if (!newInsert) {
                    (*itMergedMem).second = std::max((*itMergedMem).second,
                                                     (*itMem).second);
                }
            }
        }

        std::map<unsigned int, unsigned int> mergedStack;

        if (!mergedStacks.empty()) {
            std::map<unsigned int, unsigned int>::iterator itMem
                = mergedStacks.begin();

            mergedStack.insert(*itMem);
            ++itMem;

            while (itMem != mergedStacks.end()) {
                std::map<unsigned int, unsigned int>::reverse_iterator
                    itMergedMem = mergedStack.rbegin();
                const unsigned int nextOffset = (*itMergedMem).first
                                                + (*itMergedMem).second;

                if ((*itMem).first <= nextOffset) {
                    (*itMergedMem).second
                        = std::max((*itMem).first + (*itMem).second, nextOffset)
                            - (*itMergedMem).first;
                }
                else
                    mergedStack.insert(*itMem);

                ++itMem;
            }
        }

        // Allocate in merged stack
        unsigned int offset = 0;
        std::map<unsigned int, unsigned int>::iterator itMem
            = mergedStack.begin();

        while (true) {
            if (itMem == mergedStack.end()
                || (*itMem).first - offset >= (*it)->size)
            {
                mergedStack.insert(std::make_pair(offset, (*it)->size));
                break;
            }
            else {
                offset = (*itMem).first + (*itMem).second;
                ++itMem;
            }
        }

        (*it)->offset = offset;

        for (Clock_T t = (*it)->allocated; t <= maxT; ++t) {
            const std::map<unsigned int, unsigned int> stack
                = getStack((*it), t);
            stacks[t].insert(stack.begin(), stack.end());

            //stacks[t].insert(std::make_pair(offset, (*it)->size));
        }
    }
}

unsigned int Aidge::MemoryManager::getOffset(const std::shared_ptr<Node>& node,
                                            unsigned int plane) const
{
    const std::map<std::shared_ptr<Node>, std::vector<MemoryPlane> >
        ::const_iterator it = mMemPlanes.find(node);

    if (it == mMemPlanes.end()) {
        AIDGE_THROW_OR_ABORT(std::runtime_error,
            "getOffset(): no memory allocated for node name {}", node->name());
    }

    if (plane >= (*it).second.size()) {
        AIDGE_THROW_OR_ABORT(std::runtime_error,
            "getOffset(): plane out of range for node name {}", node->name());
    }

    return ((*it).second[plane].memSpace->offset + (*it).second[plane].offset);
}

unsigned int Aidge::MemoryManager::getSize(const std::shared_ptr<Node>& node,
                                          unsigned int plane) const
{
    const std::map<std::shared_ptr<Node>, std::vector<MemoryPlane> >
        ::const_iterator it = mMemPlanes.find(node);

    if (it == mMemPlanes.end()) {
        AIDGE_THROW_OR_ABORT(std::runtime_error,
            "getSize(): no memory allocated for node name {}", node->name());
    }

    if (plane >= (*it).second.size()) {
        AIDGE_THROW_OR_ABORT(std::runtime_error,
            "getSize(): plane out of range for node name {}", node->name());
    }

    return (*it).second[plane].getSize();
}

unsigned int Aidge::MemoryManager::getSize(const std::shared_ptr<Node>& node)
    const
{
    const std::map<std::shared_ptr<Node>, std::vector<MemoryPlane> >
        ::const_iterator it = mMemPlanes.find(node);

    if (it == mMemPlanes.end()) {
        AIDGE_THROW_OR_ABORT(std::runtime_error,
            "getSize(): no memory allocated for node name {}", node->name());
    }

    unsigned int size = 0;

    for (std::vector<MemoryPlane>::const_iterator itPlanes
        = (*it).second.begin(), itPlanesEnd = (*it).second.end();
        itPlanes != itPlanesEnd; ++itPlanes)
    {
        size += (*itPlanes).getSize();
    }

    return size;
}

unsigned int Aidge::MemoryManager::getNbPlanes(const std::shared_ptr<Node>& node)
    const
{
    const std::map<std::shared_ptr<Node>, std::vector<MemoryPlane> >
        ::const_iterator it = mMemPlanes.find(node);
    return (it == mMemPlanes.end()) ? 0 : (*it).second.size();
}

unsigned int Aidge::MemoryManager::getPeakUsage() const {
    unsigned int peakUsage = 0;

    for (std::vector<std::shared_ptr<MemorySpace> >::const_iterator
        it = mMemSpaces.begin(), itEnd = mMemSpaces.end(); it != itEnd; ++it)
    {
        peakUsage = std::max(peakUsage,
                             (*it)->offset + (*it)->size);
    }

    return peakUsage;
}

Aidge::MemoryManager::Clock_T Aidge::MemoryManager::getMaxLifetime() const {
    Clock_T maxLifetime = 0;

    for (std::vector<std::shared_ptr<MemorySpace> >::const_iterator
        it = mMemSpaces.begin(), itEnd = mMemSpaces.end(); it != itEnd; ++it)
    {
        maxLifetime = std::max(maxLifetime,
            std::max((*it)->allocated, (*it)->released));
    }

    return maxLifetime;
}

const std::vector<Aidge::MemoryManager::MemoryPlane>&
Aidge::MemoryManager::getPlanes(const std::shared_ptr<Node>& node) const
{
    const std::map<std::shared_ptr<Node>, std::vector<MemoryPlane> >
        ::const_iterator it = mMemPlanes.find(node);

    if (it == mMemPlanes.end()) {
        AIDGE_THROW_OR_ABORT(std::runtime_error,
            "getSize(): no memory allocated for node name {}", node->name());
    }

    return (*it).second;
}

Aidge::MemoryManager::MemMap_T
Aidge::MemoryManager::getPlanes(std::shared_ptr<MemorySpace> memSpace)
    const
{
    MemMap_T planes;

    for (MemMap_T::const_iterator itNode = mMemPlanes.begin(),
        itNodeEnd = mMemPlanes.end(); itNode != itNodeEnd; ++itNode)
    {
        for (std::vector<MemoryPlane>::const_iterator itPlane
             = (*itNode).second.begin(), itPlaneEnd = (*itNode).second.end();
             itPlane != itPlaneEnd; ++itPlane)
        {
            if ((*itPlane).memSpace == memSpace) {
                std::map<std::shared_ptr<Node>, std::vector<MemoryPlane> >
                    ::iterator it;
                std::tie(it, std::ignore) = planes.insert(
                    std::make_pair((*itNode).first,
                                   std::vector<MemoryPlane>()));

                (*it).second.push_back((*itPlane));
            }
        }
    }

    return planes;
}

unsigned int Aidge::MemoryManager::getNbPlanes(
    std::shared_ptr<MemorySpace> memSpace) const
{
    unsigned int count = 0;

    for (std::map<std::shared_ptr<Node>, std::vector<MemoryPlane> >
        ::const_iterator itNode = mMemPlanes.begin(),
        itNodeEnd = mMemPlanes.end(); itNode != itNodeEnd; ++itNode)
    {
        for (std::vector<MemoryPlane>::const_iterator itPlane
             = (*itNode).second.begin(), itPlaneEnd = (*itNode).second.end();
             itPlane != itPlaneEnd; ++itPlane)
        {
            if ((*itPlane).memSpace == memSpace)
                ++count;
        }
    }

    return count;
}

void Aidge::MemoryManager::tick()
{
    ++mClock;
}

void Aidge::MemoryManager::log(const std::string& fileName) const
{
    auto memData = std::unique_ptr<FILE, decltype(&std::fclose)>(std::fopen(fileName.c_str(), "w"), &std::fclose);

    if (!memData) {
        AIDGE_THROW_OR_ABORT(std::runtime_error,
            "Could not create memory layout log file: {}", fileName);
    }

    auto gnuplot = std::unique_ptr<FILE, decltype(&std::fclose)>(std::fopen((fileName + "_plot.gnu").c_str(), "w"), &std::fclose);

    if (!gnuplot) {
        AIDGE_THROW_OR_ABORT(std::runtime_error,
            "Could not create memory layout log file: {}", (fileName + "_plot.gnu"));
    }

    const Clock_T maxLifetime = getMaxLifetime();
    const unsigned int peakUsage = getPeakUsage();

    fmt::print(gnuplot.get(), "#!/usr/bin/gnuplot\n");
    fmt::print(gnuplot.get(), "set term pngcairo size 1280,768 noenhanced\n");
    fmt::print(gnuplot.get(), "set output \"{}\"\n", fileName + "_plot.png");
    fmt::print(gnuplot.get(), "set xrange [{}:{}]\n", 0, maxLifetime + 1);
    fmt::print(gnuplot.get(), "set yrange [{}:{}]\n", 0, 1.05 * (peakUsage / 1024.0));
    fmt::print(gnuplot.get(), "set xlabel \"Time\"\n");
    fmt::print(gnuplot.get(), "set ylabel \"Memory usage (KWords)\"\n");
    fmt::print(gnuplot.get(), "set grid\n");
    fmt::print(gnuplot.get(), "set xtics 1\n");
    fmt::print(gnuplot.get(), "unset key\n");
    fmt::print(gnuplot.get(), "set palette rgbformulae 30,31,32\n");
    fmt::print(gnuplot.get(), "unset colorbox\n");
    fmt::print(gnuplot.get(), "N={}\n", mMemPlanes.size() + 1);

    unsigned int objectId = 1;
    unsigned int labelId = 1;

    for (std::map<std::shared_ptr<Node>, std::vector<MemoryPlane> >
        ::const_iterator it = mMemPlanes.begin(), itEnd = mMemPlanes.end();
        it != itEnd; ++it)
    {
        const std::string name = (*it).first->name();
        fmt::print(memData.get(), "{}\n", name);

        double minX = -1;
        unsigned int maxY = 0;

        for (std::vector<MemoryPlane>::const_iterator itPlanes
             = (*it).second.begin(), itPlanesBegin = (*it).second.begin(),
            itPlanesEnd = (*it).second.end(); itPlanes != itPlanesEnd;
            ++itPlanes)
        {
            const unsigned int contiguousOffset
                = (*itPlanes).getContiguousOffset();
            const unsigned int contiguousSize = (*itPlanes).getContiguousSize();
            const unsigned int wrappedOffset = (*itPlanes).getWrappedOffset();
            const unsigned int wrappedSize = (*itPlanes).getWrappedSize();

            const Clock_T allocated = (*itPlanes).allocated;
            const Clock_T released = (*itPlanes).memSpace->released;
            const bool isReleased = (released >= 0
                                && (*itPlanes).memSpace->dependencies.empty());

            fmt::print(memData.get(), "  {} {} ({:#08x}U) -> {} ({:#08x}U)",
                (itPlanes - itPlanesBegin), contiguousOffset, contiguousOffset,
                (contiguousOffset + contiguousSize), (contiguousOffset + contiguousSize));

            if (wrappedSize > 0) {
                fmt::print(memData.get(), " + {} ({:#08x}U) -> {} ({:#08x}U)",
                    wrappedOffset, wrappedOffset,
                    (wrappedOffset + wrappedSize), (wrappedOffset + wrappedSize));
            }

            fmt::print(memData.get(), " [{}] @ {}", (*itPlanes).getSize(), allocated);

            if (isReleased) {
                fmt::print(memData.get(), " to {}", released);
            }

            fmt::print(memData.get(), "\n");

            // Gnuplot
            const double startX = allocated;

            if (startX < minX || minX < 0) {
                minX = startX;
                maxY = contiguousOffset + contiguousSize;
            }

            if ((*itPlanes).size != (*itPlanes).stride) {
                for (unsigned int offset = contiguousOffset;
                    offset < contiguousOffset + contiguousSize;
                    offset += (*itPlanes).stride)
                {
                    fmt::print(gnuplot.get(), "set object {} rectangle from {},{} to {},{} fc palette frac ({} * 1./N)\n",
                        (allocated * 100 + objectId), startX, (offset / 1024.0),
                        (((isReleased) ? released : maxLifetime) + 1),
                        (std::min((offset + (*itPlanes).size),
                                        contiguousOffset + contiguousSize) / 1024.0),
                        labelId);
                    ++objectId;
                }
            }
            else {
                fmt::print(gnuplot.get(), "set object {} rectangle from {},{} to {},{} fc palette frac ({} * 1./N)\n",
                    (allocated * 100 + objectId), startX, (contiguousOffset / 1024.0),
                    (((isReleased) ? released : maxLifetime) + 1),
                    ((contiguousOffset + contiguousSize) / 1024.0),
                    labelId);
                ++objectId;
            }

            if (wrappedSize > 0) {
                fmt::print(gnuplot.get(), "set object {} rectangle from {},{} to {},{} fc palette frac ({} * 1./N)\n",
                    (allocated * 100 + objectId), startX, (wrappedOffset / 1024.0),
                    (((isReleased) ? released : maxLifetime) + 1),
                    ((wrappedOffset + contiguousSize) / 1024.0),
                    labelId);
                ++objectId;

                fmt::print(gnuplot.get(), "set arrow from {},{} to {},{} nohead\n",
                    startX, (contiguousOffset / 1024.0),
                    (startX + 0.1), (contiguousOffset / 1024.0));

                fmt::print(gnuplot.get(), "set arrow from {},{} to {},{} nohead\n",
                    (startX + 0.05), ((contiguousOffset + contiguousSize) / 1024.0),
                    (startX + 0.05), (wrappedOffset / 1024.0));
            }
        }

        fmt::print(gnuplot.get(), "set label {} '{}' at {},{} rotate by 30 font \",8\" offset char 0.5,0.5\n",
            labelId, name, minX, (maxY / 1024.0));
        ++labelId;

        fmt::print(memData.get(), "\n");
    }

    fmt::print(gnuplot.get(), "set arrow from 0,{} to {},{} nohead lc rgb \"red\"\n",
        (peakUsage / 1024.0), (maxLifetime + 1),
        (peakUsage / 1024.0));

    fmt::print(gnuplot.get(), "set label {} 'Peak usage = {} KWords' at 0,{} textcolor rgb \"red\" offset char 0.5,0.5\n",
        labelId, (peakUsage / 1024.0), (peakUsage / 1024.0));

    fmt::print(gnuplot.get(), "plot 0\n");
}

unsigned int Aidge::MemoryManager::onStack(unsigned int size)
{
    unsigned int offset = 0;
    std::map<unsigned int, unsigned int>::iterator itMem = mMemStack.begin();

    while (true) {
        if (itMem == mMemStack.end()
            || (*itMem).first - offset >= size)
        {
            mMemStack.insert(std::make_pair(offset, size));
            break;
        }
        else {
            offset = (*itMem).first + (*itMem).second;
            ++itMem;
        }
    }

    return offset;
}

unsigned int Aidge::MemoryManager::offStack(unsigned int offset)
{
    std::map<unsigned int, unsigned int>::iterator itMem
        = mMemStack.find(offset);

    if (itMem == mMemStack.end()) {
        AIDGE_THROW_OR_ABORT(std::runtime_error,
            "offStack(): offset not found in stack");
    }
    else {
        const unsigned int size = (*itMem).second;
        mMemStack.erase(offset);
        return size;
    }
}

std::map<unsigned int, unsigned int> Aidge::MemoryManager::getStack(
    std::shared_ptr<MemorySpace> memSpace,
    Clock_T clock) const
{
    // Find all planes associated to memSpace and index them by their allocated
    // value in a map
    std::map<Clock_T, std::vector<MemoryPlane> > planes;

    for (std::map<std::shared_ptr<Node>, std::vector<MemoryPlane> >
        ::const_iterator itNode = mMemPlanes.begin(),
        itNodeEnd = mMemPlanes.end(); itNode != itNodeEnd; ++itNode)
    {
        for (std::vector<MemoryPlane>::const_iterator itPlane
             = (*itNode).second.begin(), itPlaneEnd = (*itNode).second.end();
             itPlane != itPlaneEnd; ++itPlane)
        {
            if ((*itPlane).memSpace == memSpace) {
                std::map<Clock_T, std::vector<MemoryPlane> >::iterator it;
                std::tie(it, std::ignore) = planes.insert(
                    std::make_pair((*itPlane).allocated,
                                   std::vector<MemoryPlane>()));

                (*it).second.push_back((*itPlane));
            }
        }
    }

    // Find the planes allocated at time clock or the one just before
    // => obtain all the planes that are considered valid at the time clock
    Clock_T c = clock;
    std::map<Clock_T, std::vector<MemoryPlane> >::iterator itPlanes;

    do
        itPlanes = planes.find(c);
    while (itPlanes == planes.end() && (c--) > 0);

    assert(itPlanes != planes.end());

    // Fill the stack at time clock
    std::map<unsigned int, unsigned int> stack;

    for (std::vector<MemoryPlane>::const_iterator
        it = (*itPlanes).second.begin(), itEnd = (*itPlanes).second.end();
        it != itEnd; ++it)
    {
        stack.insert(std::make_pair((*it).getContiguousOffset(),
                                    (*it).getContiguousSize()));

        if ((*it).getWrappedSize() > 0) {
            stack.insert(std::make_pair((*it).getWrappedOffset(),
                                        (*it).getWrappedSize()));
        }
    }

    return stack;
}

std::pair<Aidge::MemoryManager::Clock_T, unsigned int>
Aidge::MemoryManager::getMaxHole(std::shared_ptr<MemorySpace> memSpace) const
{
    std::map<Clock_T, unsigned int> holesSize;

    for (std::map<std::shared_ptr<Node>, std::vector<MemoryPlane> >
        ::const_iterator itNode = mMemPlanes.begin(),
        itNodeEnd = mMemPlanes.end(); itNode != itNodeEnd; ++itNode)
    {
        for (std::vector<MemoryPlane>::const_iterator itPlane
             = (*itNode).second.begin(), itPlaneEnd = (*itNode).second.end();
             itPlane != itPlaneEnd; ++itPlane)
        {
            if ((*itPlane).memSpace == memSpace) {
                const unsigned int holeSize = memSpace->size
                    - (*itPlane).getContiguousSize()
                    - (*itPlane).getWrappedSize();

                std::map<Clock_T, unsigned int>::iterator it;
                bool newInsert;
                std::tie(it, newInsert) = holesSize.insert(
                    std::make_pair((*itPlane).allocated, holeSize));

                if (!newInsert) {
                    // Another plane exists at the same time, one must substract
                    // the size of this other plane from the hole size
                    (*it).second = std::max(0, static_cast<int>((*it).second)
                        - static_cast<int>((*itPlane).getContiguousSize())
                        - static_cast<int>((*itPlane).getWrappedSize()));
                }
            }
        }
    }

    return *std::max_element(holesSize.begin(),
                             holesSize.end(),
                             [](const auto& left, const auto& right) {
                                return std::max(left.second, right.second);
                             });
}