summaryrefslogtreecommitdiff
path: root/contrib/TFLiteSharp/TFLiteSharp/TFLiteSharp/src/Interpreter.cs
blob: f1b4a8e07d0801042fb4e55295cc4992b61368ef (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
/*
 * 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.
 */

using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;

namespace TFLite
{

    /// <summary>
    /// Driver class to drive model inference with TensorFlow Lite. Interpreter
    /// encapsulates a pre-trained model file in whihc the operations are performed
    /// @class	Interpreter
    /// </summary>
    public class Interpreter : IDisposable
    {
        // Handle to hold the model instance
        private IntPtr m_modelHandle;
        // Handle to hold the interpreter instance
        private IntPtr m_interpreterHandle;

        /// <summary>
        /// Interpreter Constructor. Inititalizes an interpreter.     
        /// </summary>
        ///<param name="modelPath">a File of a pre-trained TF Lite model. </param>        
        public Interpreter(string modelPath)
        {
            //Constructor to initialize the interpreter with a model file
            m_modelHandle = Interop.TFLite.TFLiteFlatBufferModelBuildFromFile(modelPath);
            if(m_modelHandle == IntPtr.Zero)
            {
                //TODO: routine for handling null pointer.
            }
            m_interpreterHandle = Interop.TFLite.TFLiteBuilderInterpreterBuilder(ref m_modelHandle);
            if (m_interpreterHandle == IntPtr.Zero)
            {
                //TODO: routine for handling null pointer.
            }
        }

        /// <summary>
        /// Set the number of threads available to the interpreter.
        /// </summary>
        /// <param name="numThreads">Number of threads.</param>
        public void SetNumThreads(int numThreads)
        {
            Interop.TFLite.TFLiteInterpreterSetNumThreads(numThreads);
            return;
        }

        /// <summary>
        /// Runs model inference if the model takes only one input, and provides only
        /// one output.
        /// </summary>
        /// <param name="input">input an array or multidimensional array.</param>
        /// <param name="output">outputs a multidimensional array of output data.</param>
        public void Run(Array input, ref Array output)
        {
            Array[] inputs = { input };
            Dictionary<int, Array> outputs = new Dictionary<int, Array>();

            RunForMultipleInputsOutputs(inputs, ref outputs);
            output = outputs[0];

            return;
        }

        /// <summary>
        /// Runs model inference if the model takes multiple inputs, or returns multiple
        /// outputs.
        /// </summary>
        /// <param name="inputs">input an array of input data.</param>
        /// <param name="outputs">outputs a map mapping output indices to multidimensional
        /// arrays of output data.</param>
        public void RunForMultipleInputsOutputs(Array[] inputs, ref Dictionary<int, Array> outputs)
        {
            if(m_interpreterHandle == IntPtr.Zero)
            {
                //TODO:: exception handling
            }

            if (inputs == null || inputs.Length == 0)
            {
                //TODO::throw new IllegalArgumentException("Input error: Inputs should not be null or empty.");
            }

            DataType[] dataTypes = new DataType[inputs.Length];//To be used in multi-dimensional case

            for (int i = 0; i < inputs.Length; ++i)
            {
                dataTypes[i] = DataTypeOf(inputs[i]);
            }

            //TODO:: Support for multi dimesional array to be added.
            IntPtr pnt = Marshal.AllocHGlobal(inputs[0].Length);

            switch (dataTypes[0])
            {
                case DataType.INT32:
                    Marshal.Copy((int[])inputs[0], 0, pnt, inputs[0].Length);
                    break;
                case DataType.FLOAT32:
                    Marshal.Copy((float[])inputs[0], 0, pnt, inputs[0].Length);
                    break;
                case DataType.UINT8:
                    Marshal.Copy((byte[])inputs[0], 0, pnt, inputs[0].Length);
                    break;
                case DataType.INT64:
                    Marshal.Copy((long[])inputs[0], 0, pnt, inputs[0].Length);
                    break;
                default:
                    Marshal.Copy((byte[])inputs[0], 0, pnt, inputs[0].Length);
                    break;
            }

            //Currently this handles only single input with single dimension.
            IntPtr outputsHandles = Interop.TFLite.TFLiteInterpreterRun(ref m_interpreterHandle, pnt, inputs[0].Length, (int)dataTypes[0]);

            if (outputsHandles == null)
            {
                //throw new IllegalStateException("Internal error: Interpreter has no outputs.");
            }

            switch (dataTypes[0])
            {
                case DataType.INT32:
                    int[] managedArrayInt = new int[inputs[0].Length];
                    Marshal.Copy(outputsHandles, managedArrayInt, 0, inputs[0].Length);
                    outputs.Add(0, managedArrayInt);
                    break;
                case DataType.FLOAT32:
                    float[] managedArrayFloat = new float[inputs[0].Length];
                    Marshal.Copy(outputsHandles, managedArrayFloat, 0, inputs[0].Length);
                    outputs.Add(0, managedArrayFloat);
                    break;
                case DataType.UINT8:
                    byte[] managedArrayByte = new byte[inputs[0].Length];
                    Marshal.Copy(outputsHandles, managedArrayByte, 0, inputs[0].Length);
                    outputs.Add(0, managedArrayByte);
                    break;
                case DataType.INT64:
                    long[] managedArrayLong = new long[inputs[0].Length];
                    Marshal.Copy(outputsHandles, managedArrayLong, 0, inputs[0].Length);
                    outputs.Add(0, managedArrayLong);
                    break;
                default:
                    byte[] managedArrayDefault = new byte[inputs[0].Length];
                    Marshal.Copy(outputsHandles, managedArrayDefault, 0, inputs[0].Length);
                    outputs.Add(0, managedArrayDefault);
                    break;
            }
            return;
        }

        static DataType DataTypeOf(Array a)
        {
            if (a.GetValue(0).GetType()==typeof(int))
            {
                return DataType.INT32;
            }
            else if (a.GetValue(0).GetType() == typeof(float))
            {
                return DataType.FLOAT32;
            }
            else if (a.GetValue(0).GetType() == typeof(byte))
            {
                return DataType.UINT8;
            }
            else if(a.GetValue(0).GetType() == typeof(long))
            {
                return DataType.INT64;
            }
            else
            {
                return DataType.UINT8;
                //TODO: throw exception
            }

        }

        /// <summary>
        /// Resizes idx-th input of the native model to the given dims.
        /// </summary>
        /// <param name="idx">index of the input.</param>
        /// <param name="dims">Dimensions to which input needs to be resized.</param>
        public void ResizeInput(int idx, int[] dims)
        {
            return;
        }

        /// <summary>
        /// Gets index of an input given the tensor name of the input.
        /// </summary>
        /// <param name="tensorName">Name of the tensor.</param>
        public int GetInputIndex(string tensorName)
        {
            return 0;
        }

        /// <summary>
        /// Gets index of output given the tensor name of the input.
        /// </summary>
        /// <param name="tensorName">Name of the tensor.</param>
        public int GetOutputIndex(string tensorName)
        {
            return 0;
        }

        /// <summary>
        /// Turns on/off Android NNAPI for hardware acceleration when it is available.
        /// </summary>
        /// <param name="useNNAPI">set the boolean value to turn on/off nnapi.</param>
        public void SetUseNNAPI(bool useNNAPI)
        {
            return;
        }

        /// <summary>
        /// Release resources associated with the Interpreter.
        /// </summary>
        public void Dispose()
        {
            Dispose(true);
        }

        protected virtual void Dispose(bool bDisposing)
        {
            if (m_interpreterHandle != IntPtr.Zero)
            {
                // Call the function to dispose this class
                m_interpreterHandle = IntPtr.Zero;
            }

            if (bDisposing)
            {
                // No need to call the finalizer since we've now cleaned
                // up the unmanaged memory
                GC.SuppressFinalize(this);
            }
        }

        // This finalizer is called when Garbage collection occurs, but only if
        // the IDisposable.Dispose method wasn't already called.
        ~Interpreter()
        {
            Dispose(false);
        }
    }
}