aboutsummaryrefslogtreecommitdiff
path: root/src/backends/backendsCommon/memoryOptimizerStrategyLibrary/strategies/SingleAxisPriorityList.cpp
blob: 3afa061681ec82b50a2fd0891d26d8dd9bc70982 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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
//
// Copyright © 2021 Arm Ltd and Contributors. All rights reserved.
// SPDX-License-Identifier: MIT
//

#include "SingleAxisPriorityList.hpp"

#include <algorithm>
#include <cstdlib>



namespace armnn
{

// This strategy uses a vector of size_ts/words to represent occupancy of a memBlock in a memBin.
// Where each bit represents occupancy of a single time-step in that lifetime.
// We can then use bit masks to check for overlaps of memBlocks along the lifetime

// For more information on the algorithm itself see: https://arxiv.org/pdf/2001.03288.pdf
// This strategy is an implementation of 4.3 Greedy by Size
constexpr size_t wordSize = sizeof(size_t) * 8;

std::string SingleAxisPriorityList::GetName() const {
    return m_Name;
}

MemBlockStrategyType SingleAxisPriorityList::GetMemBlockStrategyType() const {
    return m_MemBlockStrategyType;
}

struct SingleAxisPriorityList::BinTracker
{
    // maxLifeTime is the number of operators in the model
    // We then divide that by wordSize to get the number of words we need to store all the lifetimes
    BinTracker(unsigned int maxLifeTime)
            : m_OccupiedSpaces(1 + maxLifeTime/wordSize, 0)
    {}

    // Add a block of a single word size to the bin
    void AddBlock(MemBlock* block, const size_t word, const size_t index)
    {
        m_OccupiedSpaces[index] = m_OccupiedSpaces[index] | word;

        m_PlacedBlocks.push_back(block);
        m_MemSize = std::max(m_MemSize, block->m_MemSize);
    }

    // Add a block with a word size of two or more to the bin
    void AddBlock(MemBlock* block,
                  const size_t startIndex,
                  const size_t endIndex,
                  const size_t firstWord,
                  const size_t lastWord)
    {
        m_OccupiedSpaces[startIndex] = m_OccupiedSpaces[startIndex] | firstWord;
        m_OccupiedSpaces[endIndex] = m_OccupiedSpaces[endIndex] | lastWord;

        for (size_t i = startIndex +1; i <= endIndex -1; ++i)
        {
            m_OccupiedSpaces[i] = std::numeric_limits<size_t>::max();
        }

        m_PlacedBlocks.push_back(block);
        m_MemSize = std::max(m_MemSize, block->m_MemSize);
    }

    size_t m_MemSize = 0;
    std::vector<size_t> m_OccupiedSpaces;
    std::vector<MemBlock*> m_PlacedBlocks;
};

void SingleAxisPriorityList::PlaceBlocks(const std::list<MemBlock*>& priorityList,
                                         std::vector<BinTracker>& placedBlocks,
                                         const unsigned int maxLifetime)
{
    // This function is used when the given block start and end lifetimes fit within a single word.
    auto singleWordLoop = [&](MemBlock* curBlock, const size_t firstWord, const size_t index)
    {
        bool placed = false;
        // loop through all existing bins
        for (auto& blockList : placedBlocks)
        {
            // Check if the lifetimes at the given index overlap with the lifetimes of the block
            if ((blockList.m_OccupiedSpaces[index] & firstWord) == 0)
            {
                // If the binary AND is 0 there is no overlap between the words and the block will fit
                blockList.AddBlock(curBlock, firstWord, index);
                placed = true;
                break;
            }
        }
        // No suitable bin was found, create a new bin/BinTracker and add it to the placedBlocks vector
        if (!placed)
        {
            placedBlocks.emplace_back(BinTracker{maxLifetime});
            placedBlocks.back().AddBlock(curBlock, firstWord, index);
        }
    };

    // This function is used when the given block start and end lifetimes fit within two words.
    auto doubleWordLoop =[&](MemBlock* curBlock,
                             const size_t firstWord,
                             const size_t firstIndex,
                             const size_t lastWord,
                             const size_t lastIndex)
    {
        bool placed = false;
        for (auto& blockList : placedBlocks)
        {
            // Check if the lifetimes at the given indexes overlap with the lifetimes of the block
            if ((blockList.m_OccupiedSpaces[firstIndex] & firstWord) == 0 &&
                (blockList.m_OccupiedSpaces[lastIndex] & lastWord) == 0)
            {
                blockList.AddBlock(curBlock, firstIndex, lastIndex, firstWord, lastWord);
                placed = true;
                break;
            }
        }
        // No suitable bin was found, create a new bin/BinTracker and add it to the placedBlocks vector
        if (!placed)
        {
            placedBlocks.emplace_back(BinTracker{maxLifetime});
            placedBlocks.back().AddBlock(curBlock, firstIndex, lastIndex, firstWord, lastWord);
        }
    };

    // Loop through the blocks to place
    for(const auto curBlock : priorityList)
    {
        // The lifetimes of both the block and bin are represented by single bits on a word/s
        // Each bin has maxLifetime/wordSize words
        // The number of words for a block depends on the size of the blocks lifetime
        // and the alignment of the block's lifetimes
        // This allows for checking sizeof(size_t) * 8 lifetimes at once with a binary AND
        const size_t firstWordIndex = curBlock->m_StartOfLife/wordSize;
        const size_t lastWordIndex = curBlock->m_EndOfLife/wordSize;

        // Align and right shift the first word
        // This sets the bits before curBlock->m_StartOfLife to 0
        size_t remainder = (curBlock->m_StartOfLife - firstWordIndex * wordSize);
        size_t firstWord = std::numeric_limits<size_t>::max() >> remainder;

        // If the indexes match the block can fit into a single word
        if(firstWordIndex == lastWordIndex)
        {
            // We then need to zero the bits to the right of curBlock->m_EndOfLife
            remainder += curBlock->m_EndOfLife + 1 - curBlock->m_StartOfLife;
            firstWord = firstWord >> (wordSize - remainder);
            firstWord = firstWord << (wordSize - remainder);

            singleWordLoop(curBlock, firstWord, firstWordIndex);
            continue;
        }

        // The indexes don't match we need at least two words
        // Zero the bits to the right of curBlock->m_EndOfLife
        remainder = (curBlock->m_EndOfLife +1 - lastWordIndex * wordSize);

        size_t lastWord = (1u << remainder) - 1;
        lastWord = lastWord << (wordSize - remainder);

        if(firstWordIndex + 1 == lastWordIndex)
        {
            doubleWordLoop(curBlock, firstWord, firstWordIndex, lastWord, lastWordIndex);
            continue;
        }

        // The block cannot fit into two words
        // We don't need to create any more words to represent this,
        // as any word between the first and last block would always equal the maximum value of size_t,
        // all the lifetimes would be occupied

        // Instead, we just check that the corresponding word in the bin is completely empty

        bool placed = false;
        for (auto& blockList : placedBlocks)
        {
            // Check the first and last word
            if ((blockList.m_OccupiedSpaces[firstWordIndex] & firstWord) != 0 ||
                (blockList.m_OccupiedSpaces[lastWordIndex] & lastWord) != 0)
            {
                continue;
            }

            bool fits = true;
            // Check that all spaces in between are clear
            for (size_t i = firstWordIndex +1; i <= lastWordIndex -1; ++i)
            {
                if (blockList.m_OccupiedSpaces[i] != 0)
                {
                    fits = false;
                    break;
                }
            }

            if (!fits)
            {
                continue;
            }

            blockList.AddBlock(curBlock, firstWordIndex, lastWordIndex, firstWord, lastWord);
            placed = true;
            break;
        }

        // No suitable bin was found, create a new bin/BinTracker and add it to the placedBlocks vector
        if (!placed)
        {
            placedBlocks.emplace_back(BinTracker{maxLifetime});
            placedBlocks.back().AddBlock(curBlock, firstWordIndex, lastWordIndex, firstWord, lastWord);
        }
    }
}

std::vector<MemBin> SingleAxisPriorityList::Optimize(std::vector<MemBlock>& blocks)
{
    unsigned int maxLifetime = 0;
    std::list<MemBlock*> priorityList;
    for (auto& block: blocks)
    {
        maxLifetime = std::max(maxLifetime, block.m_EndOfLife);
        priorityList.emplace_back(&block);
    }
    maxLifetime++;

    // From testing ordering by m_MemSize in non-descending order gives the best results overall
    priorityList.sort([](const MemBlock* lhs, const MemBlock* rhs)
                      {
                          return  lhs->m_MemSize > rhs->m_MemSize ;
                      });


    std::vector<BinTracker> placedBlocks;
    placedBlocks.reserve(maxLifetime);
    PlaceBlocks(priorityList, placedBlocks, maxLifetime);

    std::vector<MemBin> bins;
    bins.reserve(placedBlocks.size());
    for (auto blockList: placedBlocks)
    {
        MemBin bin;
        bin.m_MemBlocks.reserve(blockList.m_PlacedBlocks.size());
        bin.m_MemSize = blockList.m_MemSize;

        for (auto block : blockList.m_PlacedBlocks)
        {
            bin.m_MemBlocks.emplace_back(MemBlock{block->m_StartOfLife,
                                                  block->m_EndOfLife,
                                                  block->m_MemSize,
                                                  0,
                                                  block->m_Index,});
        }
        bins.push_back(std::move(bin));
    }

    return bins;
}

} // namespace armnn