summaryrefslogtreecommitdiff
path: root/runtimes/neurun/src/frontend/model.cc
blob: 3aa2aa2ffda52f2f6cfee111bcddd2e82a2320d9 (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
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
/*
 * Copyright (c) 2018 Samsung Electronics Co., Ltd. All Rights Reserved
 *
 * 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 <NeuralNetworks.h>
#include <NeuralNetworksEx.h>

#include <cassert>
#include <stdexcept>
#include <new>

#include "cpp14/memory.h"

#include "graph/Graph.h"
#include "frontend/wrapper/model.h"
#include "frontend/wrapper/memory.h"
#include "model/operation/Node.Include.h"

int ANeuralNetworksModel_create(ANeuralNetworksModel **model)
{
  if (model == nullptr)
  {
    return ANEURALNETWORKS_UNEXPECTED_NULL;
  }

  *model = new (std::nothrow) ANeuralNetworksModel{};
  if (*model == nullptr)
  {
    return ANEURALNETWORKS_OUT_OF_MEMORY;
  }

  return ANEURALNETWORKS_NO_ERROR;
}

void ANeuralNetworksModel_free(ANeuralNetworksModel *model) { delete model; }

int ANeuralNetworksModel_addOperand(ANeuralNetworksModel *model,
                                    const ANeuralNetworksOperandType *type)
{
  if ((model == nullptr) || (type == nullptr))
  {
    return ANEURALNETWORKS_UNEXPECTED_NULL;
  }

  if (model->isFinished())
  {
    return ANEURALNETWORKS_BAD_STATE;
  }

  // scale and zeroPoint should be zero for scalars and non-fixed point tensors
  // Quantized:
  //  scale: a 32 bit floating point value greater than zero
  //  zeroPoint: a 32 bit integer, in range [0, 255]
  if (type->type == ANEURALNETWORKS_TENSOR_QUANT8_ASYMM)
  {
    if (!(type->scale > 0.0f))
    {
      return ANEURALNETWORKS_BAD_DATA;
    }

    if ((type->zeroPoint < 0) || (type->zeroPoint > 255))
    {
      return ANEURALNETWORKS_BAD_DATA;
    }
  }
  else if ((type->scale != 0.0f) || (type->zeroPoint != 0))
  {
    return ANEURALNETWORKS_BAD_DATA;
  }

  // dimensionCount should be zero for scalars
  if ((type->dimensionCount != 0) &&
      ((type->type == ANEURALNETWORKS_FLOAT32) || (type->type == ANEURALNETWORKS_INT32) ||
       (type->type == ANEURALNETWORKS_UINT32)))
  {
    return ANEURALNETWORKS_BAD_DATA;
  }

  ::neurun::model::operand::Shape shape(type->dimensionCount);
  ::neurun::model::operand::TypeInfo typeInfo((OperandCode)(type->type), type->scale,
                                              type->zeroPoint);

  for (uint32_t axis = 0; axis < type->dimensionCount; ++axis)
  {
    shape.dim(axis) = type->dimensions[axis];
  }

  model->deref().addOperand(shape, typeInfo);

  // NOTE We do NOT allocate CLTensor here as we do not how to interpret this one.
  //      TensorFlow Lite may interpret a rank-4 tensor either as a feature map (with batch) or
  //      a convolution kernel.

  return ANEURALNETWORKS_NO_ERROR;
}

int ANeuralNetworksModel_setOperandValue(ANeuralNetworksModel *model, int32_t index,
                                         const void *buffer, size_t length)
{
  const bool isOptional = ((buffer == nullptr) && (length == 0));

  if ((model == nullptr) || ((buffer == nullptr) && (length != 0)))
  {
    return ANEURALNETWORKS_UNEXPECTED_NULL;
  }

  if (model->isFinished())
  {
    return ANEURALNETWORKS_BAD_STATE;
  }

  // Negative index value is not allowed
  if (index < 0)
  {
    return ANEURALNETWORKS_BAD_DATA;
  }
  const neurun::model::operand::Index ind{static_cast<uint32_t>(index)};

  if (!model->deref().operands().exist(ind))
  {
    return ANEURALNETWORKS_BAD_DATA;
  }

  auto &obj = model->deref().operands().at(ind);
  if ((obj.operandSize() != length) && !isOptional)
  {
    return ANEURALNETWORKS_BAD_DATA;
  }
  if (!obj.setAsConstant())
  {
    return ANEURALNETWORKS_BAD_DATA;
  }

  using ::neurun::model::operand::CachedData;
  using ::neurun::model::operand::ExternalData;

  // Remain operands.at(ind).data()->base() as nullptr for optional operand
  // This will be filled when model finished
  if (isOptional)
  {
    model->setOptionalOperand(ind);
  }

  // NNAPI spec in NeuralNetworks.h
  // For values of length greater than ANEURALNETWORKS_MAX_SIZE_OF_IMMEDIATELY_COPIED_VALUES,
  // the application is responsible for not changing the content of this region
  // until all executions using this model have completed
  if (length <= ANEURALNETWORKS_MAX_SIZE_OF_IMMEDIATELY_COPIED_VALUES)
  {
    model->deref().setOperandValue(ind, nnfw::cpp14::make_unique<CachedData>(
                                            reinterpret_cast<const uint8_t *>(buffer), length));
  }
  else
  {
    model->deref().setOperandValue(ind, nnfw::cpp14::make_unique<ExternalData>(
                                            reinterpret_cast<const uint8_t *>(buffer), length));
  }

  return ANEURALNETWORKS_NO_ERROR;
}

int ANeuralNetworksModel_setOperandValueFromMemory(ANeuralNetworksModel *model, int32_t index,
                                                   const ANeuralNetworksMemory *memory,
                                                   size_t offset, size_t length)
{
  if ((model == nullptr) || (memory == nullptr))
  {
    return ANEURALNETWORKS_UNEXPECTED_NULL;
  }

  if (model->isFinished())
  {
    return ANEURALNETWORKS_BAD_STATE;
  }

  // Negative index value is not allowed
  if (index < 0)
  {
    return ANEURALNETWORKS_BAD_DATA;
  }
  const neurun::model::operand::Index ind{static_cast<uint32_t>(index)};

  if (!model->deref().operands().exist(ind))
  {
    return ANEURALNETWORKS_BAD_DATA;
  }

  auto &obj = model->deref().operands().at(ind);
  if ((obj.operandSize() != length) || (memory->size() < (offset + length)))
  {
    return ANEURALNETWORKS_BAD_DATA;
  }
  if (!obj.setAsConstant())
  {
    return ANEURALNETWORKS_BAD_DATA;
  }

  using ::neurun::model::operand::ExternalData;

  model->deref().setOperandValue(
      ind, nnfw::cpp14::make_unique<ExternalData>(
               reinterpret_cast<const uint8_t *>(memory->base() + offset), length));

  return ANEURALNETWORKS_NO_ERROR;
}

int ANeuralNetworksModel_addOperation(ANeuralNetworksModel *model,
                                      ANeuralNetworksOperationType type, uint32_t inputCount,
                                      const uint32_t *inputs, uint32_t outputCount,
                                      const uint32_t *outputs)
{
  if ((model == nullptr) || (inputs == nullptr) || (outputs == nullptr))
  {
    return ANEURALNETWORKS_UNEXPECTED_NULL;
  }

  const ANeuralNetworksOperationType FIRST_OPERATION = ANEURALNETWORKS_ADD;
  const ANeuralNetworksOperationType LAST_OPERATION = ANEURALNETWORKS_TRANSPOSE;
  if ((type < FIRST_OPERATION) || (type > LAST_OPERATION))
  {
    return ANEURALNETWORKS_BAD_DATA;
  }

  if (model->isFinished())
  {
    return ANEURALNETWORKS_BAD_STATE;
  }

  for (uint32_t i = 0; i < outputCount; i++)
  {
    const ::neurun::model::operand::Index ind{outputs[i]};
    auto &obj = model->deref().operands().at(ind);

    if (!obj.setAsOperationOutput())
    {
      return ANEURALNETWORKS_BAD_DATA;
    }
  }

  auto &graph = model->deref();

  auto node_param =
      neurun::model::operation::Node::InitParam{inputCount, inputs, outputCount, outputs};

  try
  {
    switch (type)
    {
      case ANEURALNETWORKS_CONV_2D:
      {
        // inputCount is either 7 or 10 acccording to NN API specification.
        //  - Padding is implicit when inputCount is 7
        //  - Padding is explicit when inputCount is 10
        assert(inputCount == 7 || inputCount == 10);
        assert(outputCount == 1);

        if (inputCount == 7)
        {
          using GraphNode = neurun::model::operation::Conv2DNode;

          graph.addOperation(nnfw::cpp14::make_unique<GraphNode>(node_param));
        }
        else
        {
          throw std::runtime_error{"Explicit padding in Conv2D is not supported, yet"};
        }

        break;
      }
      case ANEURALNETWORKS_MAX_POOL_2D:
      {
        // inputCount is either 7 or 10 acccording to NN API specification.
        //  - Padding is implicit when inputCount is 7
        //  - Padding is explicit when inputCount is 10
        assert(inputCount == 7 || inputCount == 10);
        assert(outputCount == 1);

        if (inputCount == 7)
        {
          using GraphNode = neurun::model::operation::MaxPool2DNode;

          graph.addOperation(nnfw::cpp14::make_unique<GraphNode>(node_param));
        }
        else
        {
          throw std::runtime_error{"Explicit padding in MaxPool2D is not supported, yet"};
        }

        break;
      }
      case ANEURALNETWORKS_AVERAGE_POOL_2D:
      {
        // inputCount is either 7 or 10 acccording to NN API specification.
        //  - Padding is implicit when inputCount is 7
        //  - Padding is explicit when inputCount is 10
        assert(inputCount == 7 || inputCount == 10);
        assert(outputCount == 1);

        if (inputCount == 7)
        {
          using GraphNode = neurun::model::operation::AvgPool2DNode;

          graph.addOperation(nnfw::cpp14::make_unique<GraphNode>(node_param));
        }
        else
        {
          throw std::runtime_error{"Explicit padding in AvgPool2D is not supported, yet"};
        }

        break;
      }
      case ANEURALNETWORKS_CONCATENATION:
      {
        using GraphNode = neurun::model::operation::ConcatNode;

        graph.addOperation(nnfw::cpp14::make_unique<GraphNode>(node_param));

        break;
      }
      case ANEURALNETWORKS_RESHAPE:
      {
        using GraphNode = neurun::model::operation::ReshapeNode;

        graph.addOperation(nnfw::cpp14::make_unique<GraphNode>(node_param));

        break;
      }
      case ANEURALNETWORKS_FULLY_CONNECTED:
      {
        using GraphNode = neurun::model::operation::FullyConnectedNode;

        graph.addOperation(nnfw::cpp14::make_unique<GraphNode>(node_param));

        break;
      }
      case ANEURALNETWORKS_SOFTMAX:
      {
        using GraphNode = neurun::model::operation::SoftmaxNode;

        graph.addOperation(nnfw::cpp14::make_unique<GraphNode>(node_param));

        break;
      }
      default:
        throw std::runtime_error{"Not supported operation"};
    };
  }
  catch (const std::exception &e)
  {
    return ANEURALNETWORKS_BAD_STATE;
  }

  return ANEURALNETWORKS_NO_ERROR;
}

int ANeuralNetworksModel_addOperationEx(ANeuralNetworksModel *model,
                                        ANeuralNetworksOperationTypeEx type, uint32_t inputCount,
                                        const uint32_t *inputs, uint32_t outputCount,
                                        const uint32_t *outputs)
{
  if ((model == nullptr) || (inputs == nullptr) || (outputs == nullptr))
  {
    return ANEURALNETWORKS_UNEXPECTED_NULL;
  }

  if (model->isFinished())
  {
    return ANEURALNETWORKS_BAD_STATE;
  }

  const ANeuralNetworksOperationTypeEx FIRST_OPERATION = ANEURALNETWORKS_GATHER_EX;
  const ANeuralNetworksOperationTypeEx LAST_OPERATION = ANEURALNETWORKS_PRELU_EX;
  if ((type < FIRST_OPERATION) || (type > LAST_OPERATION))
  {
    return ANEURALNETWORKS_BAD_DATA;
  }

  for (uint32_t i = 0; i < outputCount; i++)
  {
    const ::neurun::model::operand::Index ind{outputs[i]};
    auto &obj = model->deref().operands().at(ind);

    if (!obj.setAsOperationOutput())
    {
      return ANEURALNETWORKS_BAD_DATA;
    }
  }

  // Workaround: to avoid compile error by unused-parameter, use inputCount
  if (inputCount == 0)
  {
    return ANEURALNETWORKS_BAD_DATA;
  }

  try
  {
    switch (type)
    {
      default:
        throw std::runtime_error{"Not supported operation"};
    }
  }
  catch (const std::exception &e)
  {
    return ANEURALNETWORKS_BAD_STATE;
  }

  return ANEURALNETWORKS_NO_ERROR;
}

int ANeuralNetworksModel_identifyInputsAndOutputs(ANeuralNetworksModel *model, uint32_t inputCount,
                                                  const uint32_t *inputs, uint32_t outputCount,
                                                  const uint32_t *outputs)
{
  if ((model == nullptr) || (inputs == nullptr) || (outputs == nullptr))
  {
    return ANEURALNETWORKS_UNEXPECTED_NULL;
  }

  if (model->isFinished())
  {
    return ANEURALNETWORKS_BAD_STATE;
  }

  // NOTE ::neurun::model::operand::Index uses int as its underlying type as various NNAPI
  //      functions such as ANeuralNetworksModel_setOperandValue use int to represent operand index
  //
  //      ANeuralNetworksModel_identifyInputsAndOutputs, however, uses uint32_t to represent operand
  //      index.
  //
  //      Below, static_cast<int>(...) is introduced to eliminate compiler warning.
  for (uint32_t n = 0; n < inputCount; ++n)
  {
    const neurun::model::operand::Index ind{static_cast<uint32_t>(inputs[n])};
    model->deref().addInput(ind);

    auto &obj = model->deref().operands().at(ind);
    if (!obj.setAsModelInput())
    {
      return ANEURALNETWORKS_BAD_DATA;
    }
  }

  for (uint32_t n = 0; n < outputCount; ++n)
  {
    const neurun::model::operand::Index ind{static_cast<uint32_t>(outputs[n])};
    model->deref().addOutput(ind);

    auto &obj = model->deref().operands().at(ind);
    // Model output cannot become model input
    if (obj.isModelInput())
    {
      return ANEURALNETWORKS_BAD_DATA;
    }
  }

  return ANEURALNETWORKS_NO_ERROR;
}

int ANeuralNetworksModel_finish(ANeuralNetworksModel *model)
{
  if (model == nullptr)
  {
    return ANEURALNETWORKS_UNEXPECTED_NULL;
  }

  return model->finish();
}