b644728afe8f92a75dc65f3bd200ec8aaa8e26fe
[tidl/tidl-api.git] / tidl_api / src / executor.cpp
1 /******************************************************************************
2  * Copyright (c) 2017-2018 Texas Instruments Incorporated - http://www.ti.com/
3  *  All rights reserved.
4  *
5  *  Redistribution and use in source and binary forms, with or without
6  *  modification, are permitted provided that the following conditions are met:
7  *      * Redistributions of source code must retain the above copyright
8  *        notice, this list of conditions and the following disclaimer.
9  *      * Redistributions in binary form must reproduce the above copyright
10  *        notice, this list of conditions and the following disclaimer in the
11  *        documentation and/or other materials provided with the distribution.
12  *      * Neither the name of Texas Instruments Incorporated nor the
13  *        names of its contributors may be used to endorse or promote products
14  *        derived from this software without specific prior written permission.
15  *
16  *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17  *  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  *  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  *  ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
20  *  LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21  *  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22  *  SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23  *  INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24  *  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25  *  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
26  *  THE POSSIBILITY OF SUCH DAMAGE.
27  *****************************************************************************/
29 #include <assert.h>
30 #include "executor.h"
31 #include "executor_impl.h"
32 #include "parameters.h"
33 #include "util.h"
34 #include "trace.h"
37 using namespace tidl;
39 using std::unique_ptr;
41 Executor::Executor(DeviceType core_type, const DeviceIds& ids,
42                    const Configuration& configuration, int layers_group_id)
43 {
44     pimpl_m = unique_ptr<ExecutorImpl>
45               { new ExecutorImpl(core_type, ids, layers_group_id) };
46     pimpl_m->Initialize(configuration);
47 }
51 // Pointer to implementation idiom: https://herbsutter.com/gotw/_100/:
52 // Both unique_ptr and shared_ptr can be instantiated with an incomplete type
53 // unique_ptr's destructor requires a complete type in order to invoke delete
54 // By writing it yourself in the implementation file, you force it to be
55 // defined in a place where impl is already defined, and this successfully
56 // prevents the compiler from trying to automatically generate the destructor
57 // on demand in the caller’s code where impl is not defined.
58 Executor::~Executor() = default;
60 uint32_t Executor::GetNumDevices(DeviceType device_type)
61 {
62     return Device::GetNumDevices(device_type);
63 }
65 #define STRING(S)  XSTRING(S)
66 #define XSTRING(S) #S
67 std::string Executor::GetAPIVersion()
68 {
69     static std::string version = STRING(_BUILD_VER);
70     version += ".";
71     version += STRING(_BUILD_SHA);
72     return version;
73 }
76 ExecutorImpl::ExecutorImpl(DeviceType core_type, const DeviceIds& ids,
77                            int layers_group_id):
78     configuration_m(),
79     shared_networkparam_heap_m(nullptr, &__free_ddr),
80     device_ids_m(ids),
81     core_type_m(core_type),
82     layers_group_id_m(layers_group_id)
83 {
84     std::string name;
85     if (core_type_m == DeviceType::DSP)
86         name  = "";
87     else if (core_type_m == DeviceType::EVE)
88         name = STRING(SETUP_KERNEL) ";" STRING(INIT_KERNEL) ";" STRING(PROCESS_KERNEL) ";" STRING(CLEANUP_KERNEL);
90     device_m = Device::Create(core_type_m, ids, name);
91 }
94 const ExecutionObjects& Executor::GetExecutionObjects() const
95 {
96     return pimpl_m->execution_objects_m;
97 }
99 bool ExecutorImpl::Initialize(const Configuration& configuration)
101     configuration_m = configuration;
103     // Allocate, initialize TIDL_CreateParams object
104     up_malloc_ddr<TIDL_CreateParams> shared_createparam(
105                                             malloc_ddr<TIDL_CreateParams>(),
106                                             &__free_ddr);
107     InitializeNetworkCreateParam(shared_createparam.get());
109     // Read network from file into network struct in TIDL_CreateParams
110     sTIDL_Network_t *net = &(shared_createparam.get())->net;
112     bool status = ReadBinary(configuration_m.netBinFile,
113                              reinterpret_cast<char *>(net),
114                              sizeof(sTIDL_Network_t));
115     assert(status != false);
117     // Force to run full network if runFullNet is set
118     if (configuration.runFullNet)
119     {
120         for (int i = 0; i < net->numLayers; i++)
121             if (net->TIDLLayers[i].layerType != TIDL_DataLayer)
122                 net->TIDLLayers[i].layersGroupId = layers_group_id_m;
123     }
125     // If the user has specified an override mapping, apply it
126     else if (!configuration.layerIndex2LayerGroupId.empty())
127     {
128         for (const auto &item : configuration.layerIndex2LayerGroupId)
129             if (item.first < net->numLayers)
130                 net->TIDLLayers[item.first].layersGroupId = item.second;
131     }
133     // Call a setup kernel to allocate and fill network parameters
134     InitializeNetworkParams(shared_createparam.get());
136     const ArgInfo create_arg(shared_createparam.get(),
137                              sizeof(TIDL_CreateParams));
138     const ArgInfo param_heap_arg(shared_networkparam_heap_m.get(),
139                                  configuration_m.PARAM_HEAP_SIZE);
140     for (auto ids : device_ids_m)
141     {
142         uint8_t index = static_cast<uint8_t>(ids);
143         execution_objects_m.push_back(
144              unique_ptr<ExecutionObject>
145              {new ExecutionObject(device_m.get(), index,
146                                   create_arg, param_heap_arg,
147                                   configuration_m.EXTMEM_HEAP_SIZE,
148                                   configuration_m.enableInternalInput)} );
149     }
151     if (configuration_m.enableOutputTrace)
152         for (auto &eo : execution_objects_m)
153             eo->EnableOutputBufferTrace();
155     for (auto &eo : execution_objects_m)
156         eo->RunAsync(ExecutionObject::CallType::INIT);
158     for (auto &eo : execution_objects_m)
159         eo->Wait(ExecutionObject::CallType::INIT);
161     return true;
165 bool ExecutorImpl::InitializeNetworkParams(TIDL_CreateParams *cp)
167     // Determine size of network parameters buffer, allocate it
168     size_t networkparam_size =
169                         GetBinaryFileSize(configuration_m.paramsBinFile);
171     up_malloc_ddr<char> networkparam(malloc_ddr<char>(networkparam_size),
172                                 &__free_ddr);
174     // Read network parameters from bin file into buffer
175     bool status = ReadBinary(configuration_m.paramsBinFile,
176                              networkparam.get(),
177                              networkparam_size);
178     assert(status != false);
180     // Allocate a buffer for passing parameters to the kernel
181     up_malloc_ddr<OCL_TIDL_SetupParams> setupParams(
182                                             malloc_ddr<OCL_TIDL_SetupParams>(),
183                                             &__free_ddr);
185     setupParams->enableTrace = OCL_TIDL_TRACE_OFF;
186     setupParams->networkParamHeapSize = configuration_m.PARAM_HEAP_SIZE;
187     setupParams->noZeroCoeffsPercentage = configuration_m.noZeroCoeffsPercentage;
188     setupParams->sizeofTIDL_CreateParams = sizeof(TIDL_CreateParams);
189     setupParams->offsetofNet = offsetof(TIDL_CreateParams, net);
191     // Allocate buffer for a network parameter heap. Used by the setup
192     // kernel to allocate and initialize network parameters for the layers
193     shared_networkparam_heap_m.reset(malloc_ddr<char>(setupParams->networkParamHeapSize));
195     KernelArgs args = { DeviceArgInfo(cp, sizeof(TIDL_CreateParams),
196                                       DeviceArgInfo::Kind::BUFFER),
197                         DeviceArgInfo(networkparam.get(), networkparam_size,
198                                       DeviceArgInfo::Kind::BUFFER),
199                         DeviceArgInfo(shared_networkparam_heap_m.get(),
200                                       setupParams->networkParamHeapSize,
201                                       DeviceArgInfo::Kind::BUFFER),
202                         DeviceArgInfo(setupParams.get(),
203                                       sizeof(OCL_TIDL_SetupParams),
204                                       DeviceArgInfo::Kind::BUFFER) };
206     // Execute kernel on first available device in the Executor
207     uint8_t id = static_cast<uint8_t>(*(device_ids_m.cbegin()));
208     unique_ptr<Kernel> K {new Kernel(device_m.get(), STRING(SETUP_KERNEL),
209                                      args, id)};
210     K->RunAsync();
211     K->Wait();
213     if (setupParams->errorCode != OCL_TIDL_SUCCESS)
214         throw Exception(setupParams->errorCode,
215                         __FILE__, __FUNCTION__, __LINE__);
217     return status;
221 void ExecutorImpl::Cleanup()
223     for (auto &eo : execution_objects_m)
224         eo->RunAsync(ExecutionObject::CallType::CLEANUP);
226     for (auto &eo : execution_objects_m)
227         eo->Wait(ExecutionObject::CallType::CLEANUP);
231 void ExecutorImpl::InitializeNetworkCreateParam(TIDL_CreateParams *CP)
233     CP->currCoreId           = layers_group_id_m;
234     CP->currLayersGroupId    = layers_group_id_m;
235     CP->l1MemSize            = tidl::internal::DMEM0_SIZE;
236     CP->l2MemSize            = tidl::internal::DMEM1_SIZE;
237     CP->l3MemSize            = tidl::internal::OCMC_SIZE;
239     CP->quantHistoryParam1   = tidl::internal::QUANT_HISTORY_PARAM1;
240     CP->quantHistoryParam2   = tidl::internal::QUANT_HISTORY_PARAM2;
241     CP->quantMargin          = tidl::internal::QUANT_MARGIN;
243     // If trace is enabled, setup the device TIDL library to allocate separate
244     // output buffers for each layer. This makes it possible for the host
245     // to access the output of each layer after a frame is processed.
246     if (configuration_m.enableOutputTrace)
247         CP->optimiseExtMem       = TIDL_optimiseExtMemL0;
248     else
249         CP->optimiseExtMem       = TIDL_optimiseExtMemL1;
252 Exception::Exception(const std::string& error, const std::string& file,
253                      const std::string& func, uint32_t line_no)
256     message_m = "TIDL Error: [";
257     message_m += file;
258     message_m += ", ";
259     message_m += func;
260     message_m += ", ";
261     message_m += std::to_string(line_no);
262     message_m += "]: ";
263     message_m += error;
266 Exception::Exception(int32_t errorCode, const std::string& file,
267                      const std::string& func, uint32_t line_no)
269     message_m = "TIDL Error: [";
270     message_m += file;
271     message_m += ", ";
272     message_m += func;
273     message_m += ", ";
274     message_m += std::to_string(line_no);
275     message_m += "]: ";
277     if (errorCode == OCL_TIDL_ERROR)
278         message_m += "";
279     else if (errorCode == OCL_TIDL_ALLOC_FAIL)
280         message_m += "Allocation failed on device";
281     else if (errorCode == OCL_TIDL_MEMREC_ALLOC_FAIL)
282         message_m += "Memrec allocation failed on device";
283     else if (errorCode == OCL_TIDL_PROCESS_FAIL)
284         message_m += "Process call failed on device";
285     else if (errorCode == OCL_TIDL_CREATE_PARAMS_MISMATCH)
286         message_m += "TIDL_CreateParams definition inconsistent across host"
287                      "and device.";
288     else
289         message_m += std::to_string(errorCode);
293 const char* Exception::what() const noexcept
295     return message_m.c_str();