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 TRACE::enabled = configuration.enableApiTrace;
46 TRACE::print("-> Executor::Executor()\n");
48 pimpl_m = unique_ptr<ExecutorImpl>
49 { new ExecutorImpl(core_type, ids, layers_group_id) };
50 pimpl_m->Initialize(configuration);
52 TRACE::print("<- Executor::Executor()\n");
53 }
57 // Pointer to implementation idiom: https://herbsutter.com/gotw/_100/:
58 // Both unique_ptr and shared_ptr can be instantiated with an incomplete type
59 // unique_ptr's destructor requires a complete type in order to invoke delete
60 // By writing it yourself in the implementation file, you force it to be
61 // defined in a place where impl is already defined, and this successfully
62 // prevents the compiler from trying to automatically generate the destructor
63 // on demand in the caller’s code where impl is not defined.
64 Executor::~Executor() = default;
66 uint32_t Executor::GetNumDevices(DeviceType device_type)
67 {
68 return Device::GetNumDevices(device_type);
69 }
71 #define STRING(S) XSTRING(S)
72 #define XSTRING(S) #S
73 std::string Executor::GetAPIVersion()
74 {
75 static std::string version = STRING(_BUILD_VER);
76 version += ".";
77 version += STRING(_BUILD_SHA);
78 return version;
79 }
82 ExecutorImpl::ExecutorImpl(DeviceType core_type, const DeviceIds& ids,
83 int layers_group_id):
84 configuration_m(),
85 shared_networkparam_heap_m(nullptr, &__free_ddr),
86 device_ids_m(ids),
87 core_type_m(core_type),
88 layers_group_id_m(layers_group_id)
89 {
90 std::string name;
91 if (core_type_m == DeviceType::DSP)
92 name = "";
93 else if (core_type_m == DeviceType::EVE)
94 name = STRING(SETUP_KERNEL) ";" STRING(INIT_KERNEL) ";" STRING(PROCESS_KERNEL) ";" STRING(CLEANUP_KERNEL);
96 device_m = Device::Create(core_type_m, ids, name);
97 }
99 ExecutionObject* Executor::operator[](uint32_t index) const
100 {
101 assert(index < pimpl_m->execution_objects_m.size());
102 return pimpl_m->execution_objects_m[index].get();
103 }
105 uint32_t Executor::GetNumExecutionObjects() const
106 {
107 return pimpl_m->execution_objects_m.size();
108 }
110 bool ExecutorImpl::Initialize(const Configuration& configuration)
111 {
112 configuration_m = configuration;
114 // Allocate, initialize TIDL_CreateParams object
115 up_malloc_ddr<TIDL_CreateParams> shared_createparam(
116 malloc_ddr<TIDL_CreateParams>(),
117 &__free_ddr);
118 InitializeNetworkCreateParam(shared_createparam.get(), configuration);
120 // Read network from file into network struct in TIDL_CreateParams
121 sTIDL_Network_t *net = &(shared_createparam.get())->net;
123 bool status = ReadBinary(configuration_m.netBinFile,
124 reinterpret_cast<char *>(net),
125 sizeof(sTIDL_Network_t));
126 assert(status != false);
128 // Force to run full network if runFullNet is set
129 if (configuration.runFullNet)
130 {
131 for (int i = 0; i < net->numLayers; i++)
132 if (net->TIDLLayers[i].layerType != TIDL_DataLayer)
133 net->TIDLLayers[i].layersGroupId = layers_group_id_m;
134 }
136 // If the user has specified an override mapping, apply it
137 else if (!configuration.layerIndex2LayerGroupId.empty())
138 {
139 for (const auto &item : configuration.layerIndex2LayerGroupId)
140 if (item.first < net->numLayers)
141 net->TIDLLayers[item.first].layersGroupId = item.second;
142 }
144 // Call a setup kernel to allocate and fill network parameters
145 InitializeNetworkParams(shared_createparam.get());
147 const ArgInfo create_arg(shared_createparam.get(),
148 sizeof(TIDL_CreateParams));
149 const ArgInfo param_heap_arg(shared_networkparam_heap_m.get(),
150 configuration_m.PARAM_HEAP_SIZE);
151 for (auto ids : device_ids_m)
152 {
153 uint8_t index = static_cast<uint8_t>(ids);
154 execution_objects_m.push_back(
155 unique_ptr<ExecutionObject>
156 {new ExecutionObject(device_m.get(), index,
157 create_arg, param_heap_arg,
158 configuration_m,
159 layers_group_id_m)} );
160 }
162 for (auto &eo : execution_objects_m)
163 eo->RunAsync(ExecutionObject::CallType::INIT);
165 for (auto &eo : execution_objects_m)
166 eo->Wait(ExecutionObject::CallType::INIT);
168 return true;
169 }
172 bool ExecutorImpl::InitializeNetworkParams(TIDL_CreateParams *cp)
173 {
174 // Determine size of network parameters buffer, allocate it
175 size_t networkparam_size =
176 GetBinaryFileSize(configuration_m.paramsBinFile);
178 up_malloc_ddr<char> networkparam(malloc_ddr<char>(networkparam_size),
179 &__free_ddr);
181 // Read network parameters from bin file into buffer
182 bool status = ReadBinary(configuration_m.paramsBinFile,
183 networkparam.get(),
184 networkparam_size);
185 assert(status != false);
187 // Allocate a buffer for passing parameters to the kernel
188 up_malloc_ddr<OCL_TIDL_SetupParams> setupParams(
189 malloc_ddr<OCL_TIDL_SetupParams>(),
190 &__free_ddr);
192 // Set up execution trace specified in the configuration
193 EnableExecutionTrace(configuration_m, &setupParams->enableTrace);
195 setupParams->networkParamHeapSize = configuration_m.PARAM_HEAP_SIZE;
196 setupParams->noZeroCoeffsPercentage = configuration_m.noZeroCoeffsPercentage;
197 setupParams->sizeofTIDL_CreateParams = sizeof(TIDL_CreateParams);
198 setupParams->offsetofNet = offsetof(TIDL_CreateParams, net);
200 // Allocate buffer for a network parameter heap. Used by the setup
201 // kernel to allocate and initialize network parameters for the layers
202 shared_networkparam_heap_m.reset(malloc_ddr<char>(setupParams->networkParamHeapSize));
204 KernelArgs args = { DeviceArgInfo(cp, sizeof(TIDL_CreateParams),
205 DeviceArgInfo::Kind::BUFFER),
206 DeviceArgInfo(networkparam.get(), networkparam_size,
207 DeviceArgInfo::Kind::BUFFER),
208 DeviceArgInfo(shared_networkparam_heap_m.get(),
209 setupParams->networkParamHeapSize,
210 DeviceArgInfo::Kind::BUFFER),
211 DeviceArgInfo(setupParams.get(),
212 sizeof(OCL_TIDL_SetupParams),
213 DeviceArgInfo::Kind::BUFFER) };
215 // Execute kernel on first available device in the Executor
216 uint8_t id = static_cast<uint8_t>(*(device_ids_m.cbegin()));
217 unique_ptr<Kernel> K {new Kernel(device_m.get(), STRING(SETUP_KERNEL),
218 args, id)};
219 K->RunAsync();
220 K->Wait();
222 if (setupParams->errorCode != OCL_TIDL_SUCCESS)
223 throw Exception(setupParams->errorCode,
224 __FILE__, __FUNCTION__, __LINE__);
226 return status;
227 }
230 void ExecutorImpl::Cleanup()
231 {
232 for (auto &eo : execution_objects_m)
233 eo->RunAsync(ExecutionObject::CallType::CLEANUP);
235 for (auto &eo : execution_objects_m)
236 eo->Wait(ExecutionObject::CallType::CLEANUP);
237 }
240 void ExecutorImpl::InitializeNetworkCreateParam(TIDL_CreateParams *CP,
241 const Configuration& c)
242 {
243 CP->currCoreId = layers_group_id_m;
244 CP->currLayersGroupId = layers_group_id_m;
245 CP->l1MemSize = tidl::internal::DMEM0_SIZE;
246 CP->l2MemSize = tidl::internal::DMEM1_SIZE;
247 CP->l3MemSize = tidl::internal::OCMC_SIZE;
249 CP->quantHistoryParam1 = c.quantHistoryParam1;
250 CP->quantHistoryParam2 = c.quantHistoryParam2;
251 CP->quantMargin = c.quantMargin;
253 // If trace is enabled, setup the device TIDL library to allocate separate
254 // output buffers for each layer. This makes it possible for the host
255 // to access the output of each layer after a frame is processed.
256 if (configuration_m.enableOutputTrace)
257 CP->optimiseExtMem = TIDL_optimiseExtMemL0;
258 else
259 CP->optimiseExtMem = TIDL_optimiseExtMemL1;
260 }
262 Exception::Exception(const std::string& error, const std::string& file,
263 const std::string& func, uint32_t line_no)
264 {
266 message_m = "TIDL Error: [";
267 message_m += file;
268 message_m += ", ";
269 message_m += func;
270 message_m += ", ";
271 message_m += std::to_string(line_no);
272 message_m += "]: ";
273 message_m += error;
274 }
276 // Refer ti-opencl/builtins/include/custom.h for error codes
277 Exception::Exception(int32_t errorCode, const std::string& file,
278 const std::string& func, uint32_t line_no)
279 {
280 message_m = "TIDL Error: [";
281 message_m += file;
282 message_m += ", ";
283 message_m += func;
284 message_m += ", ";
285 message_m += std::to_string(line_no);
286 message_m += "]: ";
288 switch (errorCode)
289 {
290 case OCL_TIDL_ERROR:
291 message_m += "";
292 break;
293 case OCL_TIDL_ALLOC_FAIL:
294 case OCL_TIDL_MEMREC_ALLOC_FAIL:
295 message_m += "Memory allocation failed on device";
296 break;
297 case OCL_TIDL_PROCESS_FAIL:
298 message_m += "Process call failed on device";
299 break;
300 case OCL_TIDL_CREATE_PARAMS_MISMATCH:
301 message_m += "TIDL API headers inconsistent with OpenCL";
302 break;
303 case OCL_TIDL_INIT_FAIL:
304 message_m += "Initialization failed on device";
305 break;
306 default:
307 message_m += std::to_string(errorCode);
308 break;
309 }
310 }
312 const char* Exception::what() const noexcept
313 {
314 return message_m.c_str();
315 }