3 * Copyright (C) 2020 Samsung Electronics
4 * Copyright (C) 2020 Dongju Chae <dongju.chae@samsung.com>
7 * @file ne-host-handler.cc
9 * @brief Implementation of APIs to access NPU from Host
10 * @see https://code.sec.samsung.net/confluence/display/ODLC/2020+Overall+Software+Stack
11 * @author Dongju Chae <dongju.chae@samsung.com>
12 * @bug No known bugs except for NYI items
15 #include "ne-handler.h"
17 #include <libnpuhost.h>
18 #include <npubinfmt.h>
19 #include <NPUdrvAPI.h>
20 #include <CommPlugin.h>
25 #include <condition_variable>
32 #define INIT_HOST_HANDLER(handler, dev) \
33 Device *tdev = static_cast <Device *> (dev); \
34 if (tdev == nullptr) return -EINVAL; \
35 HostHandler *handler = tdev->getHostHandler (); \
36 if (handler == nullptr) return -EINVAL;
38 /** just for backward-compatability */
39 npudev_h HostHandler::latest_dev_ = nullptr;
41 /** implement libnpuhost APIs */
44 * @brief Returns the number of available NPU devices.
45 * @return @c The number of NPU devices.
46 * @retval 0 if no NPU devices available. if positive (number of NPUs) if NPU devices available. otherwise, a negative error value.
47 * @note the caller should call putNPUdevice() to release the device handle
49 int getnumNPUdeviceByType (dev_type type)
51 return HostHandler::getNumDevices (type);
55 * @brief Returns the handle of the chosen NPU devices.
56 * @param[out] dev The NPU device handle
57 * @param[in] id The NPU id to get the handle. 0 <= id < getnumNPUdeviceByType().
58 * @return @c 0 if no error. otherwise a negative error value
59 * @note the caller should call putNPUdevice() to release the device handle
61 int getNPUdeviceByType (npudev_h *dev, dev_type type, uint32_t id)
63 return HostHandler::getDevice (dev, type, id);
67 * @brief Returns the handle of an NPU device meeting the condition
68 * @param[out] dev The NPU device handle
69 * @param[in] cond The condition for device search.
70 * @return @c 0 if no error. otherwise a negative error value
71 * @note the caller should call putNPUdevice() to release the device handle
72 * @note it's not supported yet
74 int getNPUdeviceByCondition(npudev_h *dev, const npucondition *cond)
76 /** not implmeneted yet */
77 return getNPUdeviceByType (dev, NPUCOND_TRIV_CONN_SOCIP, 0);
81 * @brief release the NPU device instance obtained by getDevice ()
82 * @param[in] dev the NPU device handle
84 void putNPUdevice (npudev_h dev)
87 delete static_cast<Device *> (dev);
91 * @brief Send the NN model to NPU.
92 * @param[in] dev The NPU device handle
93 * @param[in] modelfile The filepath to the compiled NPU NN model in any buffer_type
94 * @param[out] modelid The modelid allocated for this instance of NN model.
95 * @return @c 0 if no error. otherwise a negative error value
97 * @detail For ASR devices, which do not accept models, but have models
98 * embedded in devices, you do not need to call register and
99 * register calls for ASR are ignored.
101 * @todo Add a variation: in-memory model register.
103 int registerNPUmodel (npudev_h dev, generic_buffer *modelfile, uint32_t *modelid)
105 INIT_HOST_HANDLER (host_handler, dev);
107 return host_handler->registerModel (modelfile, modelid);
111 * @brief Remove the NN model from NPU
112 * @param[in] dev The NPU device handle
113 * @param[in] modelid The model to be removed from the NPU.
114 * @return @c 0 if no error. otherwise a negative error value
115 * @detail This may incur some latency with memory compatcion.
117 int unregisterNPUmodel(npudev_h dev, uint32_t modelid)
119 INIT_HOST_HANDLER (host_handler, dev);
121 return host_handler->unregisterModel (modelid);
125 * @brief Remove all NN models from NPU
126 * @param[in] dev The NPU device handle
127 * @return @c 0 if no error. otherwise a negative error value
129 int unregisterNPUmodel_all(npudev_h dev)
131 INIT_HOST_HANDLER (host_handler, dev);
133 return host_handler->unregisterModels ();
137 * @brief [OPTIONAL] Set the data layout for input/output tensors
138 * @param[in] dev The NPU device handle
139 * @param[in] modelid The ID of model whose layouts are set
140 * @param[in] info_in the layout/type info for input tensors
141 * @param[in] info_out the layout/type info for output tensors
142 * @return @c 0 if no error. otherwise a negative error value
143 * @note if this function is not called, default layout/type will be used.
145 int setNPU_dataInfo(npudev_h dev, uint32_t modelid,
146 tensors_data_info *info_in, tensors_data_info *info_out)
148 INIT_HOST_HANDLER (host_handler, dev);
150 return host_handler->setDataInfo (modelid, info_in, info_out);
154 * @brief [OPTIONAL] Set the inference constraint for next NPU inferences
155 * @param[in] dev The NPU device handle
156 * @param[in] modelid The target model id
157 * @param[in] constraint inference constraint (e.g., timeout, priority)
158 * @return @c 0 if no error. otherwise a negative error value
159 * @note If this function is not called, default values are used.
161 int setNPU_constraint(npudev_h dev, uint32_t modelid, npuConstraint constraint)
163 INIT_HOST_HANDLER (host_handler, dev);
165 return host_handler->setConstraint (modelid, constraint);
169 * @brief Execute inference. Wait (block) until the output is available.
170 * @param[in] dev The NPU device handle
171 * @param[in] modelid The model to be inferred.
172 * @param[in] input The input data to be inferred.
173 * @param[out] output The output result. The caller MUST allocate appropriately before calling this.
174 * @return @c 0 if no error. otherwise a negative error value
176 * @detail This is a syntactic sugar of runNPU_async().
177 * CAUTION: There is a memcpy for the output buffer.
179 int runNPU_sync(npudev_h dev, uint32_t modelid, const input_buffers *input,
180 output_buffers *output)
182 INIT_HOST_HANDLER (host_handler, dev);
184 return host_handler->runSync (modelid, input, output);
188 * @brief Invoke NPU inference. Unblocking call.
189 * @param[in] dev The NPU device handle
190 * @param[in] modelid The model to be inferred.
191 * @param[in] input The input data to be inferred.
192 * @param[in] cb The output buffer handler.
193 * @param[out] sequence The sequence number returned with runNPU_async.
194 * @param[in] data The data given as a parameter to the runNPU_async call.
195 * @param[in] mode Configures how this operation works.
196 * @return @c 0 if no error. otherwise a negative error value
198 int runNPU_async(npudev_h dev, uint32_t modelid, const input_buffers *input,
199 npuOutputNotify cb, uint64_t *sequence, void *data,
202 INIT_HOST_HANDLER (host_handler, dev);
204 return host_handler->runAsync (modelid, input, cb, data, mode, sequence);
208 * @brief Allocate a buffer for NPU model with the requested buffer type.
209 * @param[in] dev The NPU device handle
210 * @param[in/out] Buffer the buffer pointer where memory is allocated.
211 * @return 0 if no error, otherwise a negative errno.
213 int allocNPU_modelBuffer (npudev_h dev, generic_buffer *buffer)
215 INIT_HOST_HANDLER (host_handler, dev);
217 return host_handler->allocGenericBuffer (buffer);
221 * @brief Free the buffer and remove the address mapping.
222 * @param[in] dev The NPU device handle
223 * @param[in] buffer the model buffer
224 * @return 0 if no error, otherwise a negative errno.
226 int cleanNPU_modelBuffer (npudev_h dev, generic_buffer *buffer)
228 INIT_HOST_HANDLER (host_handler, dev);
230 return host_handler->deallocGenericBuffer (buffer);
234 * @brief Allocate a buffer for NPU input with the requested buffer type.
235 * @param[in] dev The NPU device handle
236 * @param[in/out] Buffer the buffer pointer where memory is allocated.
237 * @return 0 if no error, otherwise a negative errno.
238 * @note please utilize allocInputBuffers() for multiple input tensors because subsequent
239 * calls of allocInputBuffer() don't gurantee contiguous allocations between them.
241 int allocNPU_inputBuffer (npudev_h dev, generic_buffer *buffer)
243 INIT_HOST_HANDLER (host_handler, dev);
245 return host_handler->allocGenericBuffer (buffer);
249 * @brief Free the buffer and remove the address mapping.
250 * @param[in] dev The NPU device handle
251 * @param[in] buffer the input buffer
252 * @return 0 if no error, otherwise a negative errno.
254 int cleanNPU_inputBuffer (npudev_h dev, generic_buffer *buffer)
256 INIT_HOST_HANDLER (host_handler, dev);
258 return host_handler->deallocGenericBuffer (buffer);
262 * @brief Allocate input buffers, which have multiple instances of generic_buffer
263 * @param[in] dev The NPU device handle
264 * @param[in/out] input input buffers.
265 * @return 0 if no error, otherwise a negative errno.
266 * @note it reuses allocInputBuffer().
267 * @details in case of BUFFER_DMABUF, this function can be used to gurantee physically-contiguous
268 * memory mapping for multiple tensors (in a single inference, not batch size).
270 int allocNPU_inputBuffers (npudev_h dev, input_buffers * input)
272 INIT_HOST_HANDLER (host_handler, dev);
274 return host_handler->allocGenericBuffer (input);
278 * @brief Free input buffers allocated by allocInputBuffers().
279 * @param[in] dev The NPU device handle
280 * @param[in/out] input input buffers.
281 * @note it reuses cleanInputbuffer().
282 * @return 0 if no error, otherwise a negative errno.
284 int cleanNPU_inputBuffers (npudev_h dev, input_buffers * input)
286 INIT_HOST_HANDLER (host_handler, dev);
288 return host_handler->deallocGenericBuffer (input);
292 * @brief Get metadata for NPU model
293 * @param[in] model The path of model binary file
294 * @param[in] need_extra whether you want to extract the extra data in metadata
295 * @return the metadata structure to be filled if no error, otherwise nullptr
297 * @note For most npu-engine users, the extra data is not useful because it will be
298 * used for second-party users (e.g., compiler, simulator).
299 * Also, the caller needs to free the metadata.
301 * @note the caller needs to free the metadata
303 npubin_meta * getNPUmodel_metadata (const char *model, bool need_extra)
312 fp = fopen (model, "rb");
314 logerr (TAG, "Failed to open the model binary: %d\n", -errno);
318 meta = (npubin_meta *) malloc (NPUBIN_META_SIZE);
320 logerr (TAG, "Failed to allocate metadata\n");
324 ret = fread (meta, 1, NPUBIN_META_SIZE, fp);
325 if (ret != NPUBIN_META_SIZE) {
326 logerr (TAG, "Failed to read the metadata\n");
330 if (!CHECK_NPUBIN (meta->magiccode)) {
331 logerr (TAG, "Invalid metadata provided\n");
335 if (need_extra && NPUBIN_META_EXTRA (meta->magiccode) > 0) {
336 npubin_meta *new_meta;
338 new_meta = (npubin_meta *) realloc (meta, NPUBIN_META_TOTAL_SIZE(meta->magiccode));
340 logerr (TAG, "Failed to allocate extra metadata\n");
344 ret = fread (new_meta->reserved_extra, 1, NPUBIN_META_EXTRA_SIZE (meta->magiccode), fp);
345 if (ret != NPUBIN_META_EXTRA_SIZE (meta->magiccode)) {
346 logerr (TAG, "Invalid extra metadata provided\n");
366 /** deprecated buffer APIs; please use the above APIs */
369 * @brief Returns the number of NPU devices (TRIV).
371 int getnumNPUdevice (void)
373 logwarn (TAG, "deprecated. Please use getnumNPUdeviceByType ()\n");
374 return getnumNPUdeviceByType (NPUCOND_TRIV_CONN_SOCIP);
378 * @brief Returns the list of ASR devices (TRIA)
380 int getnumASRdevice (void)
382 logwarn (TAG, "deprecated. Please use getnumNPUdeviceByType ()\n");
383 return getnumNPUdeviceByType (NPUCOND_TRIA_CONN_SOCIP);
387 * @brief Returns the handle of the chosen TRIV device.
389 int getNPUdevice (npudev_h *dev, uint32_t id)
391 logwarn (TAG, "deprecated. Please use getNPUdeviceByType ()\n");
392 return getNPUdeviceByType (dev, NPUCOND_TRIV_CONN_SOCIP, id);
396 * @brief Returns the handle of the chosen TRIA device.
398 int getASRdevice (npudev_h *dev, uint32_t id)
400 logwarn (TAG, "deprecated. Please use getNPUdeviceByType ()\n");
401 return getNPUdeviceByType (dev, NPUCOND_TRIA_CONN_SOCIP, id);
404 /** @brief deprecated */
405 int allocModelBuffer (generic_buffer *buffer)
407 logwarn (TAG, "deprecated. Please use allocNPU_modelBuffer\n");
408 return allocNPU_modelBuffer (HostHandler::getLatestDevice(), buffer);
411 /** @brief deprecated */
412 int cleanModelBuffer (generic_buffer *buffer)
414 logwarn (TAG, "deprecated. Please use cleanNPU_modelBuffer\n");
415 return allocNPU_modelBuffer (HostHandler::getLatestDevice(), buffer);
418 /** @brief deprecated */
419 int allocInputBuffer (generic_buffer *buffer)
421 logwarn (TAG, "deprecated. Please use allocNPU_inputBuffer\n");
422 return allocNPU_inputBuffer (HostHandler::getLatestDevice(), buffer);
425 /** @brief deprecated */
426 int cleanInputBuffer (generic_buffer *buffer)
428 logwarn (TAG, "deprecated. Please use cleanNPU_inputBuffer\n");
429 return cleanNPU_inputBuffer (HostHandler::getLatestDevice(), buffer);
432 /** @brief deprecated */
433 int allocInputBuffers (input_buffers * input)
435 logwarn (TAG, "deprecated. Please use allocNPU_inputBuffers\n");
436 return allocNPU_inputBuffers (HostHandler::getLatestDevice(), input);
439 /** @brief deprecated */
440 int cleanInputBuffers (input_buffers * input)
442 logwarn (TAG, "deprecated. Please use cleanNPU_inputBuffers\n");
443 return cleanNPU_inputBuffers (HostHandler::getLatestDevice(), input);
446 /** @brief deprecated */
447 int allocNPUBuffer (uint64_t size, buffer_types type,
448 const char * filepath, generic_buffer *buffer)
453 buffer->filepath = filepath;
456 logwarn (TAG, "deprecated. Please use allocNPU_* APIs\n");
457 return allocModelBuffer (buffer);
460 /** @brief deprecated */
461 int cleanNPUBuffer (generic_buffer * buffer)
463 logwarn (TAG, "deprecated. Please use cleanNPU_* APIs\n");
464 return cleanModelBuffer (buffer);
467 /** implement methods of HostHandler class */
469 /** @brief host handler constructor */
470 HostHandler::HostHandler (Device *device)
472 /* ignored as we don't use double buffering anymore, but for backward-compatibility */
473 async_mode_ (NPUASYNC_WAIT)
477 /** @brief host handler destructor */
478 HostHandler::~HostHandler ()
483 * @brief register model from generic buffer
484 * @param[in] model_buf model buffer
485 * @param[out] modelid model id
486 * @return 0 if no error. otherwise a negative errno
489 HostHandler::registerModel (generic_buffer *model_buf, uint32_t *modelid)
491 if (model_buf == nullptr || modelid == nullptr) {
492 logerr (TAG, "Invalid arguments given\n");
496 Model *model = nullptr;
497 int status = device_->setModel (model_buf, &model);
499 logerr (TAG, "Failed to set model: %d\n", status);
503 assert (model != nullptr);
505 status = models_.insert (model->getID(), model);
507 logerr (TAG, "Failed to insert model id\n");
512 *modelid = model->getID();
517 * @brief remove the registered model
518 * @param[in] modelid model id
519 * @return 0 if no error. otherwise a negative errno
522 HostHandler::unregisterModel (uint32_t modelid)
524 return models_.remove (modelid);
528 * @brief remove all registered models
532 HostHandler::unregisterModels ()
539 * @brief Set the data layout for input/output tensors
540 * @param[in] modelid The ID of model whose layouts are set
541 * @param[in] in the layout/type info for input tensors
542 * @param[in] out the layout/type info for output tensors
543 * @return @c 0 if no error. otherwise a negative error value
544 * @note if this function is not called, default layout/type will be used.
547 HostHandler::setDataInfo (uint32_t modelid, tensors_data_info *in,
548 tensors_data_info *out)
550 Model *model = models_.find (modelid);
551 if (model == nullptr)
554 return model->setDataInfo (in, out);
558 * @brief Set the inference constraint for next NPU inferences
559 * @param[in] modelid The target model id
560 * @param[in] constraint inference constraint (e.g., timeout, priority)
561 * @return @c 0 if no error. otherwise a negative error value
562 * @note If this function is not called, default values are used.
565 HostHandler::setConstraint (uint32_t modelid, npuConstraint constraint)
567 Model *model = models_.find (modelid);
568 if (model == nullptr)
571 model->setConstraint (constraint);
577 * @brief find and return model instance
578 * @param[in] modelid model id
579 * @return model instance if found. otherwise nullptr
582 HostHandler::getModel (uint32_t modelid)
584 return models_.find (modelid);
587 /** @brief dummay callback for runSync. */
590 callbackSync (output_buffers *output) : output_(output), done_(false) {}
592 static void callback (output_buffers *output, uint64_t sequence, void *data) {
593 callbackSync *sync = static_cast<callbackSync *>(data);
594 sync->callback (output, sequence);
597 void callback (output_buffers *output, uint64_t sequence) {
598 if (output_ != nullptr) {
599 /** just copy internal variables of output buffers */
600 memcpy (output_, output, sizeof (output_buffers));
607 std::unique_lock<std::mutex> lock (m_);
608 cv_.wait (lock, [this]() { return done_; });
613 std::condition_variable cv_;
614 output_buffers *output_;
619 * @brief Execute inference. Wait (block) until the output is available.
620 * @param[in] modelid The model to be inferred.
621 * @param[in] input The input data to be inferred.
622 * @param[out] output The output result.
623 * @return @c 0 if no error. otherwise a negative error value
626 HostHandler::runSync (uint32_t modelid, const input_buffers *input,
627 output_buffers *output)
629 callbackSync sync (output);
630 int status = runAsync (modelid, input, callbackSync::callback,
631 static_cast <void*> (&sync), NPUASYNC_DROP_OLD, nullptr);
633 /** sync needs to wait callback */
640 * @brief Invoke NPU inference. Unblocking call.
641 * @param[in] modelid The model to be inferred.
642 * @param[in] input The input data to be inferred.
643 * @param[in] cb The output buffer handler.
644 * @param[in] cb_data The data given as a parameter to the runNPU_async call.
645 * @param[in] mode Configures how this operation works.
646 * @param[out] sequence The sequence number returned with runNPU_async.
647 * @return @c 0 if no error. otherwise a negative error value
650 HostHandler::runAsync (uint32_t modelid, const input_buffers *input,
651 npuOutputNotify cb, void *cb_data, npu_async_mode mode, uint64_t *sequence)
653 Model *model = nullptr;
655 if (device_->needModel()) {
656 model = getModel (modelid);
657 if (model == nullptr)
661 device_->setAsyncMode (mode);
662 return device_->run (NPUINPUT_HOST, model, input, cb, cb_data, sequence);
666 * @brief get number of available devices
667 * @param[in] type device type
668 * @return number of devices
671 HostHandler::getNumDevices (dev_type type)
673 return DriverAPI::getNumDevices (type);
677 * @brief get device instance
678 * @param[out] dev device instance
679 * @param[in] type device type
680 * @param[in] id device id
681 * @return 0 if no error. otherwise a negative errno
684 HostHandler::getDevice (npudev_h *dev, dev_type type, uint32_t id)
686 int num_devices = getNumDevices (type);
688 /** check the validity of device id */
689 if (!(num_devices > 0 && id < static_cast<uint32_t>(num_devices))) {
690 logerr (TAG, "Invalid arguments provided\n");
694 Device *device = Device::createInstance (type, id);
695 if (device == nullptr) {
696 logerr (TAG, "Failed to create a device with the given type\n");
701 /** This is just for backward-compatility; we don't guarantee its corresness */
708 * @brief allocate generic buffer (just for users)
709 * @param[out] buffer buffer instance
710 * @return 0 if no error. otherwise a negative errno
713 HostHandler::allocGenericBuffer (generic_buffer *buffer)
718 if (buffer->size == 0) {
719 logerr (TAG, "Invalid size\n");
723 if (buffer->size > UINT32_MAX) {
724 logerr (TAG, "Don't support such a large size");
728 switch (buffer->type) {
731 if (buffer->filepath == nullptr)
737 /* now, npu-engine always provides dmabuf-based allocation */
739 int status = device_->allocMemory (buffer->size, &hwmem);
743 buffer->dmabuf = hwmem->getDmabuf();
744 buffer->offset = hwmem->getOffset();
745 buffer->addr = hwmem->getData();
755 * @brief deallocate generic buffer (just for users)
756 * @param[in] buffer buffer instance
757 * @return 0 if no error. otherwise a negative errno
760 HostHandler::deallocGenericBuffer (generic_buffer *buffer)
766 switch (buffer->type) {
768 status = 0; /** always true cuz nothing to do */
772 status = device_->deallocMemory (buffer->dmabuf);
783 * @brief allocate multiple generic buffers (just for users)
784 * @param[out] buffers multi-buffer instance
785 * @return 0 if no error. otherwise a negative errno
788 HostHandler::allocGenericBuffer (generic_buffers *buffers)
790 if (buffers == NULL || buffers->num_buffers < 1)
793 buffer_types type = buffers->bufs[0].type;
794 if (type == BUFFER_FILE)
797 uint64_t total_size = 0;
798 for (uint32_t idx = 0; idx < buffers->num_buffers; idx++)
799 total_size += buffers->bufs[idx].size;
801 uint64_t first_size = buffers->bufs[0].size;
802 buffers->bufs[0].size = total_size;
803 int status = allocGenericBuffer (&buffers->bufs[0]);
807 uint64_t offset = first_size;
808 for (uint32_t idx = 1; idx < buffers->num_buffers; idx++) {
809 buffers->bufs[idx].dmabuf = buffers->bufs[0].dmabuf;
810 buffers->bufs[idx].offset = buffers->bufs[0].offset + offset;
811 buffers->bufs[idx].addr = static_cast<char*>(buffers->bufs[0].addr) + offset;
812 buffers->bufs[idx].type = type;
814 offset += buffers->bufs[idx].size;
817 buffers->bufs[0].size = first_size;
823 * @brief deallocate multiple generic buffers (just for users)
824 * @param[in] buffers multi-buffer instance
825 * @return 0 if no error. otherwise a negative errno
828 HostHandler::deallocGenericBuffer (generic_buffers *buffers)
830 if (buffers == NULL || buffers->num_buffers < 1)
833 return deallocGenericBuffer (&buffers->bufs[0]);
836 /** implement methods of Device class */
838 /** @brief constructor of device */
839 Device::Device (dev_type type, int id, bool need_model)
840 : comm_ (CommPlugin::getCommPlugin()), type_ (type), id_ (id), need_model_ (true),
841 mode_ (NPUASYNC_WAIT), initialized_ (false), atomic_flag_ (ATOMIC_FLAG_INIT)
846 * @brief create device instance depending on device type and id
847 * @param[in] type device type
848 * @param[in] id device id
849 * @return device instance
852 Device::createInstance (dev_type type, int id)
854 Device *device = nullptr;
856 switch (type & DEVICETYPE_MASK) {
857 case DEVICETYPE_TRIV:
858 device = new TrinityVision (id);
860 case DEVICETYPE_TRIV2:
861 device = new TrinityVision2 (id);
863 case DEVICETYPE_TRIA:
864 device = new TrinityAsr (id);
870 if (device != nullptr && device->init () != 0) {
879 * @brief device initialization
880 * @return 0 if no error, otherwise a negative errno
881 * @note Init failures come from createDriverAPI() only.
886 /** should be initilizaed only once */
887 if (!atomic_flag_.test_and_set()) {
888 /** create the corresponding driver API */
889 api_ = DriverAPI::createDriverAPI (type_, id_);
890 if (api_.get() == nullptr) {
891 atomic_flag_.clear();
892 logerr (TAG, "Failed to create driver API\n");
896 handler_.reset (new HostHandler (this));
897 scheduler_.reset (new Scheduler (api_.get()));
898 mem_ = MemAllocator::createInstance (api_.get());
900 initialized_ = true; /** c++11 does not provide test() of atomic flag */
907 * @brief stop all requests from this device
908 * @param[in] force_stop indicate the schedduler waits until to handle previous requests
909 * @return 0 if no error, otherwise a negative errno
912 Device::stop (bool force_stop)
914 if (!initialized ()) {
915 logerr (TAG, "Uninitialized device; should use libnpuhost APIs\n");
919 Request *req = new Request (NPUINPUT_STOP);
920 req->setForceStop (force_stop);
921 return scheduler_->submitRequest (req);
925 * @brief allocate generic memory buffer
926 * @param[out] hwmem_ptr hwmem instance pointer
927 * @return 0 if no error, otherwise a negative errno
930 Device::allocMemory (size_t size, HWmem ** hwmem_ptr)
932 if (!initialized ()) {
933 logerr (TAG, "Uninitialized device; should use libnpuhost APIs\n");
937 if (size == 0 || hwmem_ptr == nullptr)
940 HWmem *hwmem = mem_->allocMemory (size);
941 if (hwmem == nullptr)
949 * @brief deallocate generic memory buffer
950 * @param[in] dmabuf_fd dmabuf file descriptor
951 * @return 0 if no error, otherwise a negative errno
954 Device::deallocMemory (int dmabuf_fd)
956 if (!initialized ()) {
957 logerr (TAG, "Uninitialized device; should use libnpuhost APIs\n");
961 return mem_->deallocMemory (dmabuf_fd);
965 * @brief extract the buffer instance from input generic buffers
966 * @param[in] meta the model metadata
967 * @param[in] input the input generic buffers
968 * @return the buffer instance
971 TrinityVision::prepareInputBuffers (const Metadata *meta, const input_buffers *input)
973 if (meta == nullptr ||
974 meta->getInputNum() != input->num_buffers) {
975 logerr (TAG, "Invalid metadata info provided\n");
979 Buffer * buffer = mem_->allocBuffer ();
980 if (buffer != nullptr) {
981 const generic_buffer *first = &input->bufs[0];
982 if (first->type == BUFFER_DMABUF) {
983 buffer->setDmabuf (first->dmabuf);
984 buffer->setOffset (first->offset);
985 buffer->setSize (meta->getBufferSize());
987 int status = buffer->alloc (meta->getBufferSize ());
989 logerr (TAG, "Failed to allocate buffer: %d\n", status);
997 buffer->createTensors (meta);
998 } catch (std::bad_alloc& bad) {
999 logerr (TAG, "Failed to allocate buffer: No enough memory\n");
1002 } catch (std::exception& exp) {
1003 logerr (TAG, "Failed to allocate buffer: %s\n", exp.what());
1011 * @brief implementation of TRIV's setModel ()
1012 * @param[in] model_buf the model generic buffer
1013 * @param[out] model the model instance
1014 * @return 0 if no error, otherwise a negative errno
1017 TrinityVision::setModel (const generic_buffer *model_buf, Model ** model_ptr)
1019 if (!initialized ()) {
1020 logerr (TAG, "Uninitialized device; should use libnpuhost APIs\n");
1024 if (model_buf == nullptr || model_ptr == nullptr)
1027 Model *model = mem_->allocModel ();
1028 if (model == nullptr) {
1029 logerr (TAG, "Failed to allocate model\n");
1034 switch (model_buf->type) {
1036 model->setDmabuf (model_buf->dmabuf);
1037 model->setOffset (model_buf->offset);
1038 model->setSize (model_buf->size);
1042 status = model->alloc (model_buf->size);
1044 logerr (TAG, "Failed to allocate model: %d\n", status);
1048 status = comm_.extractGenericBuffer (model_buf, model->getData(), nullptr);
1050 logerr (TAG, "Failed to extract generic buffer: %d\n", status);
1059 status = model->setMetadata (model->getData());
1063 model_config_t config;
1064 config.dmabuf_id = model->getDmabuf();
1065 config.program_size = model->getMetadata()->getProgramSize();
1066 config.program_offset_addr = model->getOffset() + model->getMetadata()->getMetaSize();
1067 config.weight_offset_addr = config.program_offset_addr + config.program_size;
1069 status = api_->setModel (&config);
1083 * @brief implementation of TRIV's run()
1084 * @param[in] opmode input opmode
1085 * @param[in] model the model instance
1086 * @param[in] input generic buffers of input data
1087 * @param[in] cb the output callback
1088 * @param[in] cb_data the output callback data
1089 * @param[out] sequence The sequence number returned with runNPU_async.
1092 TrinityVision::run (npu_input_opmode opmode, const Model *model,
1093 const input_buffers *input, npuOutputNotify cb, void *cb_data,
1096 if (!initialized ()) {
1097 logerr (TAG, "Uninitialized device; should use libnpuhost APIs\n");
1101 if (opmode != NPUINPUT_HOST) {
1102 logerr (TAG, "TRIV supports only host inputservice\n");
1106 if (model == nullptr || input == nullptr) {
1107 logerr (TAG, "TRIV requires both model and input buffers\n");
1111 Buffer *buffer = prepareInputBuffers (model->getMetadata(), input);
1112 if (buffer == nullptr) {
1113 logerr (TAG, "Failed to extract buffer instance\n");
1117 for (uint32_t idx = 0; idx < input->num_buffers; idx++) {
1118 auto func = std::bind (TrinityVision::manipulateData, model, idx, true,
1119 std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
1120 int status = comm_.extractGenericBuffer (&input->bufs[idx],
1121 buffer->getInputTensor(idx)->getData(), func);
1123 logerr (TAG, "Failed to feed input buffer: %d\n", status);
1128 /** this device uses CMA buffer */
1130 Request *req = new Request (opmode);
1131 req->setModel (model);
1132 req->setBuffer (buffer);
1135 req->setCallback (std::bind (&TrinityVision::callback, this, req, cb, cb_data));
1137 if (sequence != nullptr)
1138 *sequence = req->getID();
1140 return scheduler_->submitRequest (req);
1144 * @brief callback of TRIV2 request
1145 * @param[in] req the request instance
1146 * @param[in] cb callback for completion
1147 * @param[in] cb_data callback data
1148 * @note The callback invoke does not gurantee the request was successful
1149 * @todo Check the request failures
1152 TrinityVision::callback (Request *req, npuOutputNotify cb, void *cb_data)
1154 const Model *model = req->getModel ();
1155 Buffer *buffer = req->getBuffer ();
1156 output_buffers output = {
1157 .num_buffers = buffer->getOutputNum ()
1160 for (uint32_t idx = 0; idx < output.num_buffers; idx++) {
1161 uint32_t output_tensor_size = model->getOutputTensorSize (idx);
1163 output.bufs[idx].type = BUFFER_MAPPED;
1164 output.bufs[idx].size = output_tensor_size;
1165 /** user needs to free this */
1166 output.bufs[idx].addr = malloc (output_tensor_size);
1168 auto func = std::bind (TrinityVision::manipulateData, model, idx, false,
1169 std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
1170 int status = comm_.insertGenericBuffer (buffer->getOutputTensor(idx)->getData(),
1171 &output.bufs[idx], func);
1173 logerr (TAG, "Failed to return output buffer: %d\n", status);
1177 cb (&output, req->getID(), cb_data);
1180 /** @brief implementation of TRIV2's setModel (): WIP */
1182 TrinityVision2::setModel (const generic_buffer *model_buf, Model ** model_ptr)
1184 if (!initialized ()) {
1185 logerr (TAG, "Uninitialized device; should use libnpuhost APIs\n");
1189 /** TODO: model's weight values are stored in segments */
1190 *model_ptr = nullptr;
1194 /** @brief implementation of TRIV2's run(): WIP */
1196 TrinityVision2::run (npu_input_opmode opmode, const Model *model,
1197 const input_buffers *input, npuOutputNotify cb, void *cb_data,
1200 if (!initialized ()) {
1201 logerr (TAG, "Uninitialized device; should use libnpuhost APIs\n");
1205 if (opmode != NPUINPUT_HOST && opmode != NPUINPUT_HW_RECURRING)
1208 /** this device uses segment table */
1210 Request *req = new Request (opmode);
1211 req->setModel (model);
1213 req->setSegmentTable (segt);
1215 req->setCallback (std::bind (&TrinityVision2::callback, this, req, cb, cb_data));
1218 *sequence = req->getID();
1220 return scheduler_->submitRequest (req);
1223 /** @brief callback of TRIV2 request: WIP */
1225 TrinityVision2::callback (Request *req, npuOutputNotify cb, void *cb_data)
1229 /** @brief implementation of TRIA's run(): WIP */
1231 TrinityAsr::run (npu_input_opmode opmode, const Model *model,
1232 const input_buffers *input, npuOutputNotify cb, void *cb_data,
1235 if (!initialized ()) {
1236 logerr (TAG, "Uninitialized device; should use libnpuhost APIs\n");
1240 if (opmode != NPUINPUT_HOST)
1243 /** ASR does not require model and support only a single tensor */
1244 const generic_buffer *first_buf = &input->bufs[0];
1245 Buffer * buffer = mem_->allocBuffer ();
1247 if (first_buf->type == BUFFER_DMABUF) {
1248 buffer->setDmabuf (first_buf->dmabuf);
1249 buffer->setOffset (first_buf->offset);
1250 buffer->setSize (first_buf->size);
1252 status = buffer->alloc (first_buf->size);
1258 buffer->createTensors ();
1260 status = comm_.extractGenericBuffer (first_buf,
1261 buffer->getInputTensor(0)->getData(), nullptr);
1265 Request *req = new Request (opmode);
1266 req->setBuffer (buffer);
1267 req->setCallback (std::bind (&TrinityAsr::callback, this, req, cb, cb_data));
1270 *sequence = req->getID();
1272 return scheduler_->submitRequest (req);
1275 /** @brief callback of TRIA request: WIP */
1277 TrinityAsr::callback (Request *req, npuOutputNotify cb, void *cb_data)
1281 /** Implement data manipulation (each device may have different impl.) */
1285 #define do_quantized_memcpy(type) do {\
1288 while (idx < num_elems) {\
1289 val = ((type *) src)[idx];\
1290 val = val / _scale;\
1291 val += _zero_point;\
1292 val = (val > 255.0) ? 255.0 : 0.0;\
1293 ((uint8_t *) dst)[idx++] = (uint8_t) val;\
1296 while (idx < num_elems) {\
1297 val = *(uint8_t *) src;\
1298 val -= _zero_point;\
1300 ((type *) dst)[idx++] = (type) val;\
1301 dst = (void*)(((uint8_t *) dst) + data_size);\
1302 src = (void*)(((uint8_t *) src) + 1);\
1308 * @brief memcpy during quantization
1310 static void memcpy_with_quant (bool quant, data_type type, float scale, uint32_t zero_point,
1311 void *dst, const void *src, uint32_t num_elems)
1313 double _scale = (double) scale;
1314 double _zero_point = (double) zero_point;
1316 uint32_t data_size = get_data_size (type);
1320 case DATA_TYPE_INT8:
1321 do_quantized_memcpy (int8_t);
1323 case DATA_TYPE_UINT8:
1324 do_quantized_memcpy (uint8_t);
1326 case DATA_TYPE_INT16:
1327 do_quantized_memcpy (int16_t);
1329 case DATA_TYPE_UINT16:
1330 do_quantized_memcpy (uint16_t);
1332 case DATA_TYPE_INT32:
1333 do_quantized_memcpy (int32_t);
1335 case DATA_TYPE_UINT32:
1336 do_quantized_memcpy (uint32_t);
1338 case DATA_TYPE_INT64:
1339 do_quantized_memcpy (int64_t);
1341 case DATA_TYPE_UINT64:
1342 do_quantized_memcpy (uint64_t);
1344 case DATA_TYPE_FLOAT32:
1345 do_quantized_memcpy (float);
1347 case DATA_TYPE_FLOAT64:
1348 do_quantized_memcpy (double);
1351 logerr (TAG, "Unsupported datatype %d\n", type);
1356 * @brief perform data manipulation
1357 * @param[in] model model instance
1358 * @param[in] idx tensor index
1359 * @param[in] is_input indicate it's input manipulation
1360 * @param[out] dst destination buffer
1361 * @param[in] src source buffer (feature map)
1362 * @param[in] size size to be copied
1363 * @return size of memory copy if no error, otherwise zero
1365 * @note the input data format should be NHWC
1366 * @detail rules for the memory address of activations in NPU HW.
1367 * (https://code.sec.samsung.net/confluence/pages/viewpage.action?pageId=146491864)
1369 * 1) Special case (depth == 3)
1370 * - addr(x,y,z) = addr(0,0,0) + (z) + 3 * (x + width * y)
1373 * - addr(x,y,z) = addr(0,0,0) + (z % MPA_L) + MPA_L * (x + width * (y + height * (z / MPA_L)))
1375 * Thus, if depth is not a multiple of MPA_L (i.e., 64), zero padding is required
1378 TrinityVision::manipulateData (const Model *model, uint32_t idx, bool is_input,
1379 void *dst, void *src, size_t size)
1381 const Metadata *meta = model->getMetadata();
1382 const tensor_data_info* info;
1383 const uint32_t *dims;
1384 uint32_t zero_point;
1387 /** extract required information from the metadata */
1389 if (idx >= meta->getInputNum()) {
1390 logerr (TAG, "Wrong information for input tensors in metadata\n");
1394 info = model->getInputDataInfo (idx);
1395 dims = meta->getInputDims (idx);
1396 zero_point = meta->getInputQuantZero (idx);
1397 scale = meta->getInputQuantScale (idx);
1399 if (idx >= meta->getOutputNum()) {
1400 logerr (TAG, "Wrong information for output tensors in metadata\n");
1404 info = model->getOutputDataInfo (idx);
1405 dims = meta->getOutputDims (idx);
1406 zero_point = meta->getOutputQuantZero (idx);
1407 scale = meta->getOutputQuantScale (idx);
1410 if (info == nullptr) {
1411 logerr (TAG, "Unmatched tensors info\n");
1415 uint32_t batch = dims[0];
1416 uint32_t height = dims[1];
1417 uint32_t width = dims[2];
1418 uint32_t depth = dims[3];
1420 uint32_t data_size = get_data_size (info->type);
1421 if (data_size == 0) {
1422 logerr (TAG, "Invalid data size\n");
1426 bool need_quantization = false;
1428 * note that we assume DATA_TYPE_SRNPU is the smallest data type that we consider.
1429 * Also, DATA_TYPE_SRNPU and uint8_t may be regarded as the same in the view of apps.
1431 if (info->type != DATA_TYPE_SRNPU) {
1432 assert (data_size >= get_data_size (DATA_TYPE_SRNPU));
1434 if (data_size > get_data_size (DATA_TYPE_SRNPU) ||
1435 !(zero_point == DEFAULT_ZERO_POINT && scale == DEFAULT_SCALE))
1436 need_quantization = true;
1439 /** check data manipulation is required */
1440 if (depth != 3 && depth != 64 && info->layout != DATA_LAYOUT_SRNPU) {
1441 uint32_t MPA_L = DATA_GRANULARITY;
1442 uint32_t n, h, w, d;
1443 uint32_t std_offset; /* standard offset in NHWC data format */
1444 uint32_t npu_offset; /* npu offset in NPU HW data format*/
1445 uint32_t src_offset;
1446 uint32_t dst_offset;
1447 uint32_t slice_size;
1449 /* @todo we currently support only NHWC */
1450 if (info->layout != DATA_LAYOUT_NHWC) {
1451 logerr (TAG, "data manipulation is supported for NHWC only\n");
1455 for (n = 0; n < batch; n++) {
1456 for (h = 0; h < height; h++) {
1457 for (w = 0; w < width; w++) {
1458 for (d = 0; d < depth; d += MPA_L) {
1459 std_offset = d + depth * (w + width * (h + n * height));
1460 npu_offset = MPA_L * (w + width * (h + (n + d / MPA_L) * height));
1461 slice_size = (depth - d >= MPA_L) ? MPA_L : depth - d;
1464 src_offset = std_offset * data_size;
1465 dst_offset = npu_offset;
1467 src_offset = npu_offset;
1468 dst_offset = std_offset * data_size;
1471 /* if depth is not a multiple of MPA_L, add zero paddings (not exact values) */
1472 if (need_quantization) {
1473 memcpy_with_quant (is_input, info->type, scale, zero_point,
1474 static_cast<char*>(dst) + dst_offset,
1475 static_cast<char*>(src) + src_offset,
1479 static_cast<char*>(dst) + dst_offset,
1480 static_cast<char*>(src) + src_offset,
1487 } else if (need_quantization) {
1488 /** depth == 3 || depth == 64; special cases which can directly copy input tensor data */
1489 memcpy_with_quant (is_input, info->type, scale, zero_point,
1490 dst, src, is_input ? size / data_size : size);
1492 memcpy (dst, src, size);
1501 TrinityVision::manipulateData (const Model *model, uint32_t idx, bool is_input,
1502 void *dst, void *src, size_t size)
1504 memcpy (dst, src, size);
1510 /** other device types don't have data manip impl. yet */
1513 TrinityVision2::manipulateData (const Model *model, uint32_t idx, bool is_input,
1514 void *dst, void *src, size_t size)
1516 memcpy (dst, src, size);
1521 TrinityAsr::manipulateData (const Model *model, uint32_t idx, bool is_input,
1522 void *dst, void *src, size_t size)
1524 memcpy (dst, src, size);