aboutsummaryrefslogtreecommitdiff
path: root/src/armnn/test/optimizations/PermuteAndBatchToSpaceAsDepthToSpaceTests.cpp
blob: e91e16f1329d3e91ad388d6dc8d8cd265a7828d9 (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
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
//
// Copyright © 2019 Arm Ltd. All rights reserved.
// SPDX-License-Identifier: MIT
//

#include "../TestUtils.hpp"

#include <Network.hpp>
#include <Optimizer.hpp>

#include <doctest/doctest.h>

using namespace armnn;

TEST_SUITE("Optimizer")
{
using namespace armnn::optimizations;

namespace
{

/// Shared function for the below tests, so that we test the same network in both cases.
std::unique_ptr<NetworkImpl> CreateTestNetworkImpl()
{
    std::unique_ptr<NetworkImpl> network(new NetworkImpl());

    auto input = network->AddInputLayer(0, "input");
    const TensorInfo inputInfo({ 1, 2, 3, 4 }, DataType::Float32);
    input->GetOutputSlot(0).SetTensorInfo(inputInfo);

    // Insert Permute which swaps batches and channels dimensions
    auto permute = network->AddPermuteLayer(PermuteDescriptor(PermutationVector{ 3, 1, 2, 0 }), "permute");
    const TensorInfo permuteInfo({ 4, 2, 3, 1 }, DataType::Float32);
    permute->GetOutputSlot(0).SetTensorInfo(permuteInfo);
    input->GetOutputSlot(0).Connect(permute->GetInputSlot(0));

    // Insert BatchToSpace
    BatchToSpaceNdDescriptor batchToSpaceDesc;
    batchToSpaceDesc.m_BlockShape = { 2, 2 };
    batchToSpaceDesc.m_DataLayout = DataLayout::NHWC;
    auto batchToSpace             = network->AddBatchToSpaceNdLayer(batchToSpaceDesc, "batchToSpace");
    const TensorInfo batchToSpaceInfo({ 1, 4, 6, 1 }, DataType::Float32);
    batchToSpace->GetOutputSlot(0).SetTensorInfo(batchToSpaceInfo);
    permute->GetOutputSlot(0).Connect(batchToSpace->GetInputSlot(0));

    auto output = network->AddOutputLayer(0, "output");
    batchToSpace->GetOutputSlot(0).Connect(output->GetInputSlot(0));

    return network;
}

/// Shared function for the below tests, so that we test the same network in both cases.
std::unique_ptr<NetworkImpl> CreateTransposeTestNetworkImpl()
{
    // Create a network
    std::unique_ptr<NetworkImpl> network(new NetworkImpl());

    auto input = network->AddInputLayer(0, "input");
    const TensorInfo inputInfo({ 1, 2, 3, 4 }, DataType::Float32);
    input->GetOutputSlot(0).SetTensorInfo(inputInfo);

    // Insert Permute which swaps batches and channels dimensions
    auto permute = network->AddTransposeLayer(TransposeDescriptor(PermutationVector{ 3, 1, 2, 0 }), "permute");
    const TensorInfo permuteInfo({ 4, 2, 3, 1 }, DataType::Float32);
    permute->GetOutputSlot(0).SetTensorInfo(permuteInfo);
    input->GetOutputSlot(0).Connect(permute->GetInputSlot(0));

    // Insert BatchToSpace
    BatchToSpaceNdDescriptor batchToSpaceDesc;
    batchToSpaceDesc.m_BlockShape = { 2, 2 };
    batchToSpaceDesc.m_DataLayout = DataLayout::NHWC;
    auto batchToSpace             = network->AddBatchToSpaceNdLayer(batchToSpaceDesc, "batchToSpace");
    const TensorInfo batchToSpaceInfo({ 1, 4, 6, 1 }, DataType::Float32);
    batchToSpace->GetOutputSlot(0).SetTensorInfo(batchToSpaceInfo);
    permute->GetOutputSlot(0).Connect(batchToSpace->GetInputSlot(0));

    auto output = network->AddOutputLayer(0, "output");
    batchToSpace->GetOutputSlot(0).Connect(output->GetInputSlot(0));

    return network;
}

}    // namespace

/// Tests that the optimization performed by PermuteAndBatchToSpaceAsDepthToSpace is as expected.
/// Note this does not ensure the correctness of the optimization - that is done in the below test.
TEST_CASE("PermuteAndBatchToSpaceAsDepthToSpaceOptimizerTest")
{
    std::unique_ptr<NetworkImpl> network = CreateTestNetworkImpl();
    Graph graph         = network.get()->GetGraph();

    // Confirm initial graph is as we expect
    CHECK(CheckSequence(graph.cbegin(), graph.cend(), &IsLayerOfType<InputLayer>, &IsLayerOfType<PermuteLayer>,
                             &IsLayerOfType<BatchToSpaceNdLayer>, &IsLayerOfType<OutputLayer>));

    // Perform the optimization which should merge the two layers into a DepthToSpace
    armnn::Optimizer::Pass(graph, MakeOptimizations(PermuteAndBatchToSpaceAsDepthToSpace()));

    // Check that the replacement has been made as expected
    auto checkDepthToSpace = [](const Layer* const layer) -> bool {
        return IsLayerOfType<DepthToSpaceLayer>(layer) &&
               static_cast<const DepthToSpaceLayer*>(layer)->GetParameters().m_BlockSize == 2 &&
               static_cast<const DepthToSpaceLayer*>(layer)->GetParameters().m_DataLayout == DataLayout::NHWC &&
               layer->GetOutputHandler().GetTensorInfo() == TensorInfo({ 1, 4, 6, 1 }, DataType::Float32);
    };

    CHECK(CheckSequence(graph.cbegin(), graph.cend(), &IsLayerOfType<InputLayer>, checkDepthToSpace,
                             &IsLayerOfType<OutputLayer>));

    // Check the new layer has the two merged layers listed as related layers
    std::list<std::string> testRelatedLayers = { "batchToSpace", "permute" };
    CHECK(CheckRelatedLayers<DepthToSpaceLayer>(graph, testRelatedLayers));
}

/// Tests that the optimization performed by PermuteAndBatchToSpaceAsDepthToSpace is as expected.
/// Note this does not ensure the correctness of the optimization - that is done in the below test.
TEST_CASE("TransposeAndBatchToSpaceAsDepthToSpaceOptimizerTest")
{
    std::unique_ptr<NetworkImpl> network = CreateTransposeTestNetworkImpl();
    Graph graph         = network.get()->GetGraph();

    // Confirm initial graph is as we expect
    CHECK(CheckSequence(graph.cbegin(), graph.cend(), &IsLayerOfType<InputLayer>, &IsLayerOfType<TransposeLayer>,
                             &IsLayerOfType<BatchToSpaceNdLayer>, &IsLayerOfType<OutputLayer>));

    // Perform the optimization which should merge the two layers into a DepthToSpace
    armnn::Optimizer::Pass(graph, MakeOptimizations(TransposeAndBatchToSpaceAsDepthToSpace()));

    // Check that the replacement has been made as expected
    auto checkDepthToSpace = [](const Layer* const layer) -> bool {
        return IsLayerOfType<DepthToSpaceLayer>(layer) &&
               static_cast<const DepthToSpaceLayer*>(layer)->GetParameters().m_BlockSize == 2 &&
               static_cast<const DepthToSpaceLayer*>(layer)->GetParameters().m_DataLayout == DataLayout::NHWC &&
               layer->GetOutputHandler().GetTensorInfo() == TensorInfo({ 1, 4, 6, 1 }, DataType::Float32);
    };

    CHECK(CheckSequence(graph.cbegin(), graph.cend(), &IsLayerOfType<InputLayer>, checkDepthToSpace,
                             &IsLayerOfType<OutputLayer>));

    // Check the new layer has the two merged layers listed as related layers
    std::list<std::string> testRelatedLayers = { "batchToSpace", "permute" };
    CHECK(CheckRelatedLayers<DepthToSpaceLayer>(graph, testRelatedLayers));
}

// This unit test needs the reference backend, it's not available if the reference backend is not built
#if defined(ARMNNREF_ENABLED)

/// Shared function for the below tests, so that we test the same network in both cases.
INetworkPtr CreateTestNetwork()
{
    // Create a network
    INetworkPtr network = INetwork::Create();

    auto input = network->AddInputLayer(0, "input");
    const TensorInfo inputInfo({ 1, 2, 3, 4 }, DataType::Float32);
    input->GetOutputSlot(0).SetTensorInfo(inputInfo);

    // Insert Permute which swaps batches and channels dimensions
    auto permute = network->AddPermuteLayer(PermuteDescriptor(PermutationVector{ 3, 1, 2, 0 }), "permute");
    const TensorInfo permuteInfo({ 4, 2, 3, 1 }, DataType::Float32);
    permute->GetOutputSlot(0).SetTensorInfo(permuteInfo);
    input->GetOutputSlot(0).Connect(permute->GetInputSlot(0));

    // Insert BatchToSpace
    BatchToSpaceNdDescriptor batchToSpaceDesc;
    batchToSpaceDesc.m_BlockShape = { 2, 2 };
    batchToSpaceDesc.m_DataLayout = DataLayout::NHWC;
    auto batchToSpace             = network->AddBatchToSpaceNdLayer(batchToSpaceDesc, "batchToSpace");
    const TensorInfo batchToSpaceInfo({ 1, 4, 6, 1 }, DataType::Float32);
    batchToSpace->GetOutputSlot(0).SetTensorInfo(batchToSpaceInfo);
    permute->GetOutputSlot(0).Connect(batchToSpace->GetInputSlot(0));

    auto output = network->AddOutputLayer(0, "output");
    batchToSpace->GetOutputSlot(0).Connect(output->GetInputSlot(0));

    return network;
}

/// Shared function for the below tests, so that we test the same network in both cases.
INetworkPtr CreateTransposeTestNetwork()
{
    // Create a network
    INetworkPtr network = INetwork::Create();

    auto input = network->AddInputLayer(0, "input");
    const TensorInfo inputInfo({ 1, 2, 3, 4 }, DataType::Float32);
    input->GetOutputSlot(0).SetTensorInfo(inputInfo);

    // Insert Permute which swaps batches and channels dimensions
    auto permute = network->AddTransposeLayer(TransposeDescriptor(PermutationVector{ 3, 1, 2, 0 }), "permute");
    const TensorInfo permuteInfo({ 4, 2, 3, 1 }, DataType::Float32);
    permute->GetOutputSlot(0).SetTensorInfo(permuteInfo);
    input->GetOutputSlot(0).Connect(permute->GetInputSlot(0));

    // Insert BatchToSpace
    BatchToSpaceNdDescriptor batchToSpaceDesc;
    batchToSpaceDesc.m_BlockShape = { 2, 2 };
    batchToSpaceDesc.m_DataLayout = DataLayout::NHWC;
    auto batchToSpace             = network->AddBatchToSpaceNdLayer(batchToSpaceDesc, "batchToSpace");
    const TensorInfo batchToSpaceInfo({ 1, 4, 6, 1 }, DataType::Float32);
    batchToSpace->GetOutputSlot(0).SetTensorInfo(batchToSpaceInfo);
    permute->GetOutputSlot(0).Connect(batchToSpace->GetInputSlot(0));

    auto output = network->AddOutputLayer(0, "output");
    batchToSpace->GetOutputSlot(0).Connect(output->GetInputSlot(0));

    return network;
}

/// Tests that a optimization performed by PermuteAndBatchToSpaceAsDepthToSpace does not change the behaviour
/// of the network (i.e. it still produces the correct output).
TEST_CASE("PermuteAndBatchToSpaceAsDepthToSpaceCorrectnessTest")
{
    INetworkPtr network = CreateTestNetwork();

    IRuntimePtr runtime = IRuntime::Create(IRuntime::CreationOptions());
    IOptimizedNetworkPtr optimizedNetwork = Optimize(*network, { Compute::CpuRef }, runtime->GetDeviceSpec());

    // Confirm that the optimization has actually taken place
    const Graph& optGraph = GetGraphForTesting(optimizedNetwork.get());
    CHECK(CheckSequence(optGraph.cbegin(), optGraph.cend(), &IsLayerOfType<InputLayer>,
                             &IsLayerOfType<DepthToSpaceLayer>, &IsLayerOfType<OutputLayer>));

    // Load the graph into a runtime so we can check it produces the correct output
    NetworkId netId;
    runtime->LoadNetwork(netId, std::move(optimizedNetwork));

    std::vector<float> inputData{
        // Each row here is a row of pixels where each pixel has 4 channels
        // clang-format off
        1.0f,  2.0f,  3.0f,  4.0f,      10.0f,  20.0f,  30.0f,  40.0f,      100.0f,  200.0f,  300.0f,  400.0f,
        -1.0f, -2.0f, -3.0f, -4.0f,    -10.0f, -20.0f, -30.0f, -40.0f,     -100.0f, -200.0f, -300.0f, -400.0f,
        // clang-format on
    };
    ConstTensor input(TensorInfo({ 1, 2, 3, 4 }, DataType::Float32), inputData);
    InputTensors inputs = { { 0, input } };
    std::vector<float> outputData(4 * 6);
    Tensor output(TensorInfo({ 1, 4, 6, 1 }, DataType::Float32), outputData.data());
    OutputTensors outputs = { { 0, output } };
    runtime->EnqueueWorkload(netId, inputs, outputs);

    // Check the output is as expected.
    // Note this output has been generated by running the network *without* the optimization.
    std::vector<float> expectedOutput = {
        // Rows and columns here match exactly with the tensor, as there is only 1 channel.
        // clang-format off
        1.0f,  2.0f,     10.0f,  20.0f,     100.0f,  200.0f,
        3.0f,  4.0f,     30.0f,  40.0f,     300.0f,  400.0f,

        -1.0f, -2.0f,   -10.0f, -20.0f,    -100.0f, -200.0f,
        -3.0f, -4.0f,   -30.0f, -40.0f,    -300.0f, -400.0f,
        // clang-format on
    };
    CHECK(outputData == expectedOutput);
}

/// Tests that a optimization performed by PermuteAndBatchToSpaceAsDepthToSpace does not change the behaviour
/// of the network (i.e. it still produces the correct output).
TEST_CASE("TransposeAndBatchToSpaceAsDepthToSpaceCorrectnessTest")
{
    INetworkPtr network = CreateTransposeTestNetwork();

    IRuntimePtr runtime = IRuntime::Create(IRuntime::CreationOptions());
    IOptimizedNetworkPtr optimizedNetwork = Optimize(*network, { Compute::CpuRef }, runtime->GetDeviceSpec());

    // Confirm that the optimization has actually taken place
    const Graph& optGraph = GetGraphForTesting(optimizedNetwork.get());
    CHECK(CheckSequence(optGraph.cbegin(), optGraph.cend(), &IsLayerOfType<InputLayer>,
                             &IsLayerOfType<DepthToSpaceLayer>, &IsLayerOfType<OutputLayer>));

    // Load the graph into a runtime so we can check it produces the correct output
    NetworkId netId;
    runtime->LoadNetwork(netId, std::move(optimizedNetwork));

    std::vector<float> inputData{
            // Each row here is a row of pixels where each pixel has 4 channels
            // clang-format off
            1.0f,  2.0f,  3.0f,  4.0f,      10.0f,  20.0f,  30.0f,  40.0f,      100.0f,  200.0f,  300.0f,  400.0f,
            -1.0f, -2.0f, -3.0f, -4.0f,    -10.0f, -20.0f, -30.0f, -40.0f,     -100.0f, -200.0f, -300.0f, -400.0f,
            // clang-format on
    };
    ConstTensor input(TensorInfo({ 1, 2, 3, 4 }, DataType::Float32), inputData);
    InputTensors inputs = { { 0, input } };
    std::vector<float> outputData(4 * 6);
    Tensor output(TensorInfo({ 1, 4, 6, 1 }, DataType::Float32), outputData.data());
    OutputTensors outputs = { { 0, output } };
    runtime->EnqueueWorkload(netId, inputs, outputs);

    // Check the output is as expected.
    // Note this output has been generated by running the network *without* the optimization.
    std::vector<float> expectedOutput = {
            // Rows and columns here match exactly with the tensor, as there is only 1 channel.
            // clang-format off
            1.0f,  2.0f,     10.0f,  20.0f,     100.0f,  200.0f,
            3.0f,  4.0f,     30.0f,  40.0f,     300.0f,  400.0f,

            -1.0f, -2.0f,   -10.0f, -20.0f,    -100.0f, -200.0f,
            -3.0f, -4.0f,   -30.0f, -40.0f,    -300.0f, -400.0f,
            // clang-format on
    };
    CHECK(outputData == expectedOutput);
}
#endif

}