aboutsummaryrefslogtreecommitdiff
path: root/reference_model/src/main.cpp
blob: ec2fdc99a7da52f7b34e27a0fdf96801595cc188 (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

// Copyright (c) 2020, ARM Limited.
//
//    Licensed under the Apache License, Version 2.0 (the "License");
//    you may not use this file except in compliance with the License.
//    You may obtain a copy of the License at
//
//         http://www.apache.org/licenses/LICENSE-2.0
//
//    Unless required by applicable law or agreed to in writing, software
//    distributed under the License is distributed on an "AS IS" BASIS,
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//    See the License for the specific language governing permissions and
//    limitations under the License.

#include <stdio.h>

#include "flatbuffers/idl.h"
#include "flatbuffers/util.h"
#include "model_common.h"
#include "ops/op_factory.h"
#include "subgraph_traverser.h"
#include "tosa_serialization_handler.h"
#include <Eigen/CXX11/Tensor>
#include <iostream>

using namespace TosaReference;
using namespace tosa;

// Global instantiation of configuration and debug objects
func_config_t g_func_config;
func_debug_t g_func_debug;

int readInputTensors(SubgraphTraverser& gt);
int writeFinalTensors(SubgraphTraverser& gt);
int loadGraph(TosaSerializationHandler& tsh);

int main(int argc, const char** argv)
{
    // Initialize configuration and debug subsystems
    func_model_init_config();
    func_model_set_default_config(&g_func_config);
    func_init_debug(&g_func_debug, 0);
    TosaSerializationHandler tsh;

    if (func_model_parse_cmd_line(&g_func_config, &g_func_debug, argc, argv))
    {
        return 1;
    }

    if (loadGraph(tsh))
    {
        SIMPLE_FATAL_ERROR("Unable to load graph");
    }

    // load json first since it's easier debugging
    SubgraphTraverser main_gt(tsh.GetMainBlock(), &tsh);

    if (main_gt.initializeGraph())
    {
        SIMPLE_FATAL_ERROR("Unable to initialize graph traverser: \"main\"");
    }

    if (main_gt.linkTensorsAndNodes())
    {
        SIMPLE_FATAL_ERROR("Failed to link tensors and nodes");
    }

    if (main_gt.validateGraph())
    {
        SIMPLE_FATAL_ERROR("Failed to validate graph");
    }

    if (g_func_config.validate_only)
    {
        goto done;
    }

    if (readInputTensors(main_gt))
    {
        SIMPLE_FATAL_ERROR("Unable to read input tensors");
    }

    if (g_func_config.eval)
    {

        if (main_gt.evaluateAll())
        {
            SIMPLE_FATAL_ERROR("Error evaluating network.  Giving up.");
        }

        // make sure output tensor is evaluated and show its value
        int num_output_tensors = main_gt.getNumOutputTensors();
        bool all_output_valid  = true;
        for (int i = 0; i < num_output_tensors; i++)
        {
            const Tensor* ct = main_gt.getOutputTensor(i);
            ASSERT_MEM(ct);
            if (!ct->getIsValid())
            {
                ct->dumpTensorParams(g_func_debug.func_debug_file);
                if (DEBUG_ENABLED(DEBUG_VERB_HIGH, GT))
                {
                    ct->dumpTensor(g_func_debug.func_debug_file);
                }
                all_output_valid = false;
            }
        }
        if (!all_output_valid)
        {
            main_gt.dumpGraph(g_func_debug.func_debug_file);
            SIMPLE_FATAL_ERROR(
                "SubgraphTraverser \"main\" error: Output tensors are not all valid at the end of evaluation.");
        }

        if (g_func_config.output_tensors)
        {
            if (writeFinalTensors(main_gt))
            {
                WARNING("Errors encountered in saving output tensors");
            }
        }
    }

done:
    func_fini_debug(&g_func_debug);
    func_model_config_cleanup();

    return 0;
}

int loadGraph(TosaSerializationHandler& tsh)
{
    char graph_fullname[1024];

    snprintf(graph_fullname, sizeof(graph_fullname), "%s/%s", g_func_config.subgraph_dir, g_func_config.subgraph_file);

    if (strlen(graph_fullname) <= 2)
    {
        func_model_print_help(stderr);
        SIMPLE_FATAL_ERROR("Missing required argument: Check -Csubgraph_file=");
    }

    const char JSON_EXT[] = ".json";
    int is_json           = 0;
    {
        // look for JSON file extension
        size_t suffix_len = strlen(JSON_EXT);
        size_t str_len    = strlen(graph_fullname);

        if (str_len > suffix_len && strncasecmp(graph_fullname + (str_len - suffix_len), JSON_EXT, suffix_len) == 0)
        {
            is_json = 1;
        }
    }

    if (is_json)
    {
        if (tsh.LoadFileSchema(g_func_config.operator_fbs))
        {
            SIMPLE_FATAL_ERROR(
                "\nJSON file detected.  Unable to load TOSA flatbuffer schema from: %s\nCheck -Coperator_fbs=",
                g_func_config.operator_fbs);
        }

        if (tsh.LoadFileJson(graph_fullname))
        {
            SIMPLE_FATAL_ERROR("\nError loading JSON graph file: %s\nCheck -Csubgraph_file= and -Csubgraph_dir=",
                               graph_fullname);
        }
    }
    else
    {
        if (tsh.LoadFileTosaFlatbuffer(graph_fullname))
        {
            SIMPLE_FATAL_ERROR("\nError loading TOSA flatbuffer file: %s\nCheck -Csubgraph_file= and -Csubgraph_dir=",
                               graph_fullname);
        }
    }

    return 0;
}

int readInputTensors(SubgraphTraverser& gt)
{
    int tensorCount = gt.getNumInputTensors();
    Tensor* tensor;
    char filename[1024];

    // assuming filename doesn't have colons(:)
    std::map<std::string, std::string> input_tensor_map;
    std::string raw_str(g_func_config.input_tensor);
    std::string name, npy;
    bool last_pair = false;

    std::string::size_type pair_start = 0, pair_end, colons_pos;
    do
    {
        pair_end = raw_str.find(',', pair_start);
        if (pair_end == std::string::npos)
            last_pair = true;

        colons_pos = raw_str.find(':', pair_start);

        name = raw_str.substr(pair_start, colons_pos - pair_start);
        npy  = raw_str.substr(colons_pos + 1, pair_end - colons_pos - 1);

        // Empty strings can make it to here
        if (name.length() == 0 || npy.length() == 0)
            break;

        input_tensor_map[name] = npy;

        pair_start = pair_end + 1;    // skip colons
    } while (!last_pair);

    if ((size_t)tensorCount != input_tensor_map.size())
    {
        WARNING("graph has %lu input placeholders, but %lu initialized", tensorCount, input_tensor_map.size());
        return 1;
    }

    for (auto& tensor_pair : input_tensor_map)
    {
        tensor = gt.getInputTensorByName(tensor_pair.first);
        if (!tensor)
        {
            WARNING("Unable to find input tensor %s", tensor_pair.first.c_str());
            return 1;
        }

        snprintf(filename, sizeof(filename), "%s/%s", g_func_config.input_dir, tensor_pair.second.c_str());

        DEBUG_MED(GT, "Loading input tensor %s from filename: %s", tensor->getName().c_str(), filename);

        if (tensor->allocate())
        {
            WARNING("Fail to allocate tensor %s", tensor->getName().c_str());
            return 1;
        }

        if (tensor->readFromNpyFile(filename))
        {
            WARNING("Unable to read input tensor %s from filename: %s", tensor->getName().c_str(), filename);
            tensor->dumpTensorParams(g_func_debug.func_debug_file);
            return 1;
        }

        // Push ready consumers to the next node list
        for (auto gn : tensor->getConsumers())
        {
            if (gn->hasAllInputsReady() && !gn->getOnNextNodeList())
            {
                gt.addToNextNodeList(gn);
            }
        }
    }

    if (DEBUG_ENABLED(DEBUG_VERB_HIGH, GT))
    {
        gt.dumpNextNodeList(g_func_debug.func_debug_file);
    }

    return 0;
}

int writeFinalTensors(SubgraphTraverser& gt)
{
    int tensorCount = gt.getNumOutputTensors();
    const Tensor* tensor;
    char filename[1024];

    for (int i = 0; i < tensorCount; i++)
    {
        tensor = gt.getOutputTensor(i);
        if (!tensor)
        {
            WARNING("Unable to find output tensor[%d]", i);
            return 1;
        }

        snprintf(filename, sizeof(filename), "%s/%s%s.npy", g_func_config.output_dir,
                 g_func_config.output_tensor_prefix, tensor->getName().c_str());

        DEBUG_MED(GT, "Writing output tensor[%d] %s to filename: %s", i, tensor->getName().c_str(), filename);

        if (tensor->writeToNpyFile(filename))
        {
            WARNING("Unable to write output tensor[%d] %s to filename: %s", i, tensor->getName().c_str(), filename);
            return 1;
        }
    }

    return 0;
}