aboutsummaryrefslogtreecommitdiff
path: root/src/armnn/optimizations/TransposeAsReshape.hpp
blob: d6fb9bc316cbe312c52faa6e19d32a8939d4f56b (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
//
// Copyright © 2020 Arm Ltd. All rights reserved.
// SPDX-License-Identifier: MIT
//
#pragma once

#include "Optimization.hpp"

namespace armnn
{
namespace optimizations
{

class TransposeAsReshapeImpl
{
public:
    /// Run for every TransposeLayer. Replaces it with a ReshapeLayer if they are equivalent.
    void Run(Graph& graph, TransposeLayer& transpose) const
    {
        if (IsReshape(transpose))
        {
            const TensorInfo& outInfo = transpose.GetOutputHandler().GetTensorInfo();

            const std::string name = std::string("as_reshape-") + transpose.GetName();
            const ReshapeDescriptor descriptor{outInfo.GetShape()};
            // Inserts NewLayer so layers don't need to be re-sorted.
            auto reshape = graph.InsertNewLayer<ReshapeLayer>(transpose.GetInputSlot(0), descriptor, name.c_str());

            // Bypass transpose. It will be deleted since it's left unconnected.
            transpose.GetOutputSlot().MoveAllConnections(reshape->GetOutputSlot());
        }
    }

protected:
    TransposeAsReshapeImpl() = default;
    ~TransposeAsReshapeImpl() = default;

private:
    static bool IsReshape(const TransposeLayer& layer)
    {
        const TensorShape& outShape = layer.GetOutputHandler().GetTensorInfo().GetShape();
        const PermutationVector& permutation = layer.GetPermutation();

        const unsigned int numDimensions = permutation.GetSize();
        std::map<unsigned int, unsigned int> permuteMappings;
        for (unsigned int i = 0; i < permutation.GetSize(); ++i)
        {
            permuteMappings[permutation[i]] = i;
        }

        std::vector<unsigned int> permuteVector;
        for (unsigned int i = 0; i < permutation.GetSize(); ++i)
        {
            permuteVector.push_back(permuteMappings.at(i));
        }

        unsigned int lastGtOne = 0;
        while ((lastGtOne < numDimensions) && (outShape[(permuteVector[lastGtOne])] == 1U))
        {
            ++lastGtOne;
        }

        bool isReshape = true;
        for (unsigned int i = lastGtOne + 1U; isReshape && (i < numDimensions); ++i)
        {
            if (outShape[permuteVector[i]] > 1U)
            {
                isReshape = permuteVector[lastGtOne] < permuteVector[i];
                lastGtOne = i;
            }
        }

        return isReshape;
    }
};

using TransposeAsReshape = OptimizeForType<TransposeLayer, TransposeAsReshapeImpl>;

} // namespace optimizations
} // namespace armnn