]> Gitweb @ Texas Instruments - Open Source Git Repositories - git.TI.com/gitweb - tidl/tidl-api.git/blob - tidl_api/src/executor.cpp
ExecutionObjectPipeline for executing layersGroups
[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 ExecutionObject* Executor::operator[](uint32_t index) const
101     assert(index < pimpl_m->execution_objects_m.size());
102     return pimpl_m->execution_objects_m[index].get();
105 bool ExecutorImpl::Initialize(const Configuration& configuration)
107     configuration_m = configuration;
109     // Allocate, initialize TIDL_CreateParams object
110     up_malloc_ddr<TIDL_CreateParams> shared_createparam(
111                                             malloc_ddr<TIDL_CreateParams>(),
112                                             &__free_ddr);
113     InitializeNetworkCreateParam(shared_createparam.get());
115     // Read network from file into network struct in TIDL_CreateParams
116     sTIDL_Network_t *net = &(shared_createparam.get())->net;
118     bool status = ReadBinary(configuration_m.netBinFile,
119                              reinterpret_cast<char *>(net),
120                              sizeof(sTIDL_Network_t));
121     assert(status != false);
123     // Force to run full network if runFullNet is set
124     if (configuration.runFullNet)
125     {
126         for (int i = 0; i < net->numLayers; i++)
127             if (net->TIDLLayers[i].layerType != TIDL_DataLayer)
128                 net->TIDLLayers[i].layersGroupId = layers_group_id_m;
129     }
131     // If the user has specified an override mapping, apply it
132     else if (!configuration.layerIndex2LayerGroupId.empty())
133     {
134         for (const auto &item : configuration.layerIndex2LayerGroupId)
135             if (item.first < net->numLayers)
136                 net->TIDLLayers[item.first].layersGroupId = item.second;
137     }
139     // Call a setup kernel to allocate and fill network parameters
140     InitializeNetworkParams(shared_createparam.get());
142     const ArgInfo create_arg(shared_createparam.get(),
143                              sizeof(TIDL_CreateParams));
144     const ArgInfo param_heap_arg(shared_networkparam_heap_m.get(),
145                                  configuration_m.PARAM_HEAP_SIZE);
146     for (auto ids : device_ids_m)
147     {
148         uint8_t index = static_cast<uint8_t>(ids);
149         execution_objects_m.push_back(
150              unique_ptr<ExecutionObject>
151              {new ExecutionObject(device_m.get(), index,
152                                   create_arg, param_heap_arg,
153                                   configuration_m.EXTMEM_HEAP_SIZE,
154                                   layers_group_id_m,
155                                   configuration_m.enableOutputTrace,
156                                   configuration_m.enableInternalInput)} );
157     }
159     for (auto &eo : execution_objects_m)
160         eo->RunAsync(ExecutionObject::CallType::INIT);
162     for (auto &eo : execution_objects_m)
163         eo->Wait(ExecutionObject::CallType::INIT);
165     return true;
169 bool ExecutorImpl::InitializeNetworkParams(TIDL_CreateParams *cp)
171     // Determine size of network parameters buffer, allocate it
172     size_t networkparam_size =
173                         GetBinaryFileSize(configuration_m.paramsBinFile);
175     up_malloc_ddr<char> networkparam(malloc_ddr<char>(networkparam_size),
176                                 &__free_ddr);
178     // Read network parameters from bin file into buffer
179     bool status = ReadBinary(configuration_m.paramsBinFile,
180                              networkparam.get(),
181                              networkparam_size);
182     assert(status != false);
184     // Allocate a buffer for passing parameters to the kernel
185     up_malloc_ddr<OCL_TIDL_SetupParams> setupParams(
186                                             malloc_ddr<OCL_TIDL_SetupParams>(),
187                                             &__free_ddr);
189     setupParams->enableTrace = OCL_TIDL_TRACE_OFF;
190     setupParams->networkParamHeapSize = configuration_m.PARAM_HEAP_SIZE;
191     setupParams->noZeroCoeffsPercentage = configuration_m.noZeroCoeffsPercentage;
192     setupParams->sizeofTIDL_CreateParams = sizeof(TIDL_CreateParams);
193     setupParams->offsetofNet = offsetof(TIDL_CreateParams, net);
195     // Allocate buffer for a network parameter heap. Used by the setup
196     // kernel to allocate and initialize network parameters for the layers
197     shared_networkparam_heap_m.reset(malloc_ddr<char>(setupParams->networkParamHeapSize));
199     KernelArgs args = { DeviceArgInfo(cp, sizeof(TIDL_CreateParams),
200                                       DeviceArgInfo::Kind::BUFFER),
201                         DeviceArgInfo(networkparam.get(), networkparam_size,
202                                       DeviceArgInfo::Kind::BUFFER),
203                         DeviceArgInfo(shared_networkparam_heap_m.get(),
204                                       setupParams->networkParamHeapSize,
205                                       DeviceArgInfo::Kind::BUFFER),
206                         DeviceArgInfo(setupParams.get(),
207                                       sizeof(OCL_TIDL_SetupParams),
208                                       DeviceArgInfo::Kind::BUFFER) };
210     // Execute kernel on first available device in the Executor
211     uint8_t id = static_cast<uint8_t>(*(device_ids_m.cbegin()));
212     unique_ptr<Kernel> K {new Kernel(device_m.get(), STRING(SETUP_KERNEL),
213                                      args, id)};
214     K->RunAsync();
215     K->Wait();
217     if (setupParams->errorCode != OCL_TIDL_SUCCESS)
218         throw Exception(setupParams->errorCode,
219                         __FILE__, __FUNCTION__, __LINE__);
221     return status;
225 void ExecutorImpl::Cleanup()
227     for (auto &eo : execution_objects_m)
228         eo->RunAsync(ExecutionObject::CallType::CLEANUP);
230     for (auto &eo : execution_objects_m)
231         eo->Wait(ExecutionObject::CallType::CLEANUP);
235 void ExecutorImpl::InitializeNetworkCreateParam(TIDL_CreateParams *CP)
237     CP->currCoreId           = layers_group_id_m;
238     CP->currLayersGroupId    = layers_group_id_m;
239     CP->l1MemSize            = tidl::internal::DMEM0_SIZE;
240     CP->l2MemSize            = tidl::internal::DMEM1_SIZE;
241     CP->l3MemSize            = tidl::internal::OCMC_SIZE;
243     CP->quantHistoryParam1   = tidl::internal::QUANT_HISTORY_PARAM1;
244     CP->quantHistoryParam2   = tidl::internal::QUANT_HISTORY_PARAM2;
245     CP->quantMargin          = tidl::internal::QUANT_MARGIN;
247     // If trace is enabled, setup the device TIDL library to allocate separate
248     // output buffers for each layer. This makes it possible for the host
249     // to access the output of each layer after a frame is processed.
250     if (configuration_m.enableOutputTrace)
251         CP->optimiseExtMem       = TIDL_optimiseExtMemL0;
252     else
253         CP->optimiseExtMem       = TIDL_optimiseExtMemL1;
256 Exception::Exception(const std::string& error, const std::string& file,
257                      const std::string& func, uint32_t line_no)
260     message_m = "TIDL Error: [";
261     message_m += file;
262     message_m += ", ";
263     message_m += func;
264     message_m += ", ";
265     message_m += std::to_string(line_no);
266     message_m += "]: ";
267     message_m += error;
270 Exception::Exception(int32_t errorCode, const std::string& file,
271                      const std::string& func, uint32_t line_no)
273     message_m = "TIDL Error: [";
274     message_m += file;
275     message_m += ", ";
276     message_m += func;
277     message_m += ", ";
278     message_m += std::to_string(line_no);
279     message_m += "]: ";
281     if (errorCode == OCL_TIDL_ERROR)
282         message_m += "";
283     else if (errorCode == OCL_TIDL_ALLOC_FAIL)
284         message_m += "Allocation failed on device";
285     else if (errorCode == OCL_TIDL_MEMREC_ALLOC_FAIL)
286         message_m += "Memrec allocation failed on device";
287     else if (errorCode == OCL_TIDL_PROCESS_FAIL)
288         message_m += "Process call failed on device";
289     else if (errorCode == OCL_TIDL_CREATE_PARAMS_MISMATCH)
290         message_m += "TIDL_CreateParams definition inconsistent across host"
291                      "and device.";
292     else
293         message_m += std::to_string(errorCode);
297 const char* Exception::what() const noexcept
299     return message_m.c_str();