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 release the NPU device instance obtained by getDevice ()
68 * @param[in] dev the NPU device handle
70 void putNPUdevice (npudev_h dev)
73 delete static_cast<Device *> (dev);
77 * @brief Send the NN model to NPU.
78 * @param[in] dev The NPU device handle
79 * @param[in] modelfile The filepath to the compiled NPU NN model in any buffer_type
80 * @param[out] modelid The modelid allocated for this instance of NN model.
81 * @return @c 0 if no error. otherwise a negative error value
83 * @detail For ASR devices, which do not accept models, but have models
84 * embedded in devices, you do not need to call register and
85 * register calls for ASR are ignored.
87 * @todo Add a variation: in-memory model register.
89 int registerNPUmodel (npudev_h dev, generic_buffer *modelfile, uint32_t *modelid)
91 INIT_HOST_HANDLER (host_handler, dev);
93 return host_handler->registerModel (modelfile, modelid);
97 * @brief Remove the NN model from NPU
98 * @param[in] dev The NPU device handle
99 * @param[in] modelid The model to be removed from the NPU.
100 * @return @c 0 if no error. otherwise a negative error value
101 * @detail This may incur some latency with memory compatcion.
103 int unregisterNPUmodel(npudev_h dev, uint32_t modelid)
105 INIT_HOST_HANDLER (host_handler, dev);
107 return host_handler->unregisterModel (modelid);
111 * @brief Remove all NN models from NPU
112 * @param[in] dev The NPU device handle
113 * @return @c 0 if no error. otherwise a negative error value
115 int unregisterNPUmodel_all(npudev_h dev)
117 INIT_HOST_HANDLER (host_handler, dev);
119 return host_handler->unregisterModels ();
123 * @brief [OPTIONAL] Set the data layout for input/output tensors
124 * @param[in] dev The NPU device handle
125 * @param[in] modelid The ID of model whose layouts are set
126 * @param[in] info_in the layout/type info for input tensors
127 * @param[in] info_out the layout/type info for output tensors
128 * @return @c 0 if no error. otherwise a negative error value
129 * @note if this function is not called, default layout/type will be used.
131 int setNPU_dataInfo(npudev_h dev, uint32_t modelid,
132 tensors_data_info *info_in, tensors_data_info *info_out)
134 INIT_HOST_HANDLER (host_handler, dev);
136 return host_handler->setDataInfo (modelid, info_in, info_out);
140 * @brief [OPTIONAL] Set the inference constraint for next NPU inferences
141 * @param[in] dev The NPU device handle
142 * @param[in] modelid The target model id
143 * @param[in] constraint inference constraint (e.g., timeout, priority)
144 * @return @c 0 if no error. otherwise a negative error value
145 * @note If this function is not called, default values are used.
147 int setNPU_constraint(npudev_h dev, uint32_t modelid, npuConstraint constraint)
149 INIT_HOST_HANDLER (host_handler, dev);
151 return host_handler->setConstraint (modelid, constraint);
155 * @brief Execute inference. Wait (block) until the output is available.
156 * @param[in] dev The NPU device handle
157 * @param[in] modelid The model to be inferred.
158 * @param[in] input The input data to be inferred.
159 * @param[out] output The output result. The caller MUST allocate appropriately before calling this.
160 * @return @c 0 if no error. otherwise a negative error value
162 * @detail This is a syntactic sugar of runNPU_async().
163 * CAUTION: There is a memcpy for the output buffer.
165 int runNPU_sync(npudev_h dev, uint32_t modelid, const input_buffers *input,
166 output_buffers *output)
168 INIT_HOST_HANDLER (host_handler, dev);
170 return host_handler->runSync (modelid, input, output);
174 * @brief Invoke NPU inference. Unblocking call.
175 * @param[in] dev The NPU device handle
176 * @param[in] modelid The model to be inferred.
177 * @param[in] input The input data to be inferred.
178 * @param[in] cb The output buffer handler.
179 * @param[out] sequence The sequence number returned with runNPU_async.
180 * @param[in] data The data given as a parameter to the runNPU_async call.
181 * @param[in] mode Configures how this operation works.
182 * @return @c 0 if no error. otherwise a negative error value
184 int runNPU_async(npudev_h dev, uint32_t modelid, const input_buffers *input,
185 npuOutputNotify cb, uint64_t *sequence, void *data,
188 INIT_HOST_HANDLER (host_handler, dev);
190 return host_handler->runAsync (modelid, input, cb, data, mode, sequence);
194 * @brief Allocate a buffer for NPU model with the requested buffer type.
195 * @param[in] dev The NPU device handle
196 * @param[in/out] Buffer the buffer pointer where memory is allocated.
197 * @return 0 if no error, otherwise a negative errno.
199 int allocNPU_modelBuffer (npudev_h dev, generic_buffer *buffer)
201 INIT_HOST_HANDLER (host_handler, dev);
203 return host_handler->allocGenericBuffer (buffer);
207 * @brief Free the buffer and remove the address mapping.
208 * @param[in] dev The NPU device handle
209 * @param[in] buffer the model buffer
210 * @return 0 if no error, otherwise a negative errno.
212 int cleanNPU_modelBuffer (npudev_h dev, generic_buffer *buffer)
214 INIT_HOST_HANDLER (host_handler, dev);
216 return host_handler->deallocGenericBuffer (buffer);
220 * @brief Allocate a buffer for NPU input with the requested buffer type.
221 * @param[in] dev The NPU device handle
222 * @param[in/out] Buffer the buffer pointer where memory is allocated.
223 * @return 0 if no error, otherwise a negative errno.
224 * @note please utilize allocInputBuffers() for multiple input tensors because subsequent
225 * calls of allocInputBuffer() don't gurantee contiguous allocations between them.
227 int allocNPU_inputBuffer (npudev_h dev, generic_buffer *buffer)
229 INIT_HOST_HANDLER (host_handler, dev);
231 return host_handler->allocGenericBuffer (buffer);
235 * @brief Free the buffer and remove the address mapping.
236 * @param[in] dev The NPU device handle
237 * @param[in] buffer the input buffer
238 * @return 0 if no error, otherwise a negative errno.
240 int cleanNPU_inputBuffer (npudev_h dev, generic_buffer *buffer)
242 INIT_HOST_HANDLER (host_handler, dev);
244 return host_handler->deallocGenericBuffer (buffer);
248 * @brief Allocate input buffers, which have multiple instances of generic_buffer
249 * @param[in] dev The NPU device handle
250 * @param[in/out] input input buffers.
251 * @return 0 if no error, otherwise a negative errno.
252 * @note it reuses allocInputBuffer().
253 * @details in case of BUFFER_DMABUF, this function can be used to gurantee physically-contiguous
254 * memory mapping for multiple tensors (in a single inference, not batch size).
256 int allocNPU_inputBuffers (npudev_h dev, input_buffers * input)
258 INIT_HOST_HANDLER (host_handler, dev);
260 return host_handler->allocGenericBuffer (input);
264 * @brief Free input buffers allocated by allocInputBuffers().
265 * @param[in] dev The NPU device handle
266 * @param[in/out] input input buffers.
267 * @note it reuses cleanInputbuffer().
268 * @return 0 if no error, otherwise a negative errno.
270 int cleanNPU_inputBuffers (npudev_h dev, input_buffers * input)
272 INIT_HOST_HANDLER (host_handler, dev);
274 return host_handler->deallocGenericBuffer (input);
278 * @brief get the current memory status for the given device
279 * @param[in] dev The NPU device handle
280 * @param[out] alloc_total The size of allocated memory until now
281 * @param[out] free_total The size of freed memory until now
282 * @return @c 0 if no error. otherwise a negatice error value
284 int getNPU_memoryStatus(npudev_h dev, size_t *alloc_total, size_t *free_total)
286 INIT_HOST_HANDLER (host_handler, dev);
288 return host_handler->getMemoryStatus (alloc_total, free_total);
292 * @brief Get the current device status to be used
293 * @param[in] dev The NPU device handle
294 * @param[out] status the device status
295 * @param[out] num_requests the number of running requests (or pending)
296 * @return 0 if no error, otherwise a negative errno.
298 int getNPU_deviceStatus(npudev_h dev, npu_status *status, uint32_t *num_requests)
300 INIT_HOST_HANDLER (host_handler, dev);
302 return host_handler->getDeviceStatus (status, num_requests);
306 * @brief Get metadata for NPU model
307 * @param[in] model The path of model binary file
308 * @param[in] need_extra whether you want to extract the extra data in metadata
309 * @return the metadata structure to be filled if no error, otherwise nullptr
311 * @note For most npu-engine users, the extra data is not useful because it will be
312 * used for second-party users (e.g., compiler, simulator).
313 * Also, the caller needs to free the metadata.
315 * @note the caller needs to free the metadata
317 npubin_meta * getNPUmodel_metadata (const char *model, bool need_extra)
326 fp = fopen (model, "rb");
328 logerr (TAG, "Failed to open the model binary: %d\n", -errno);
332 meta = (npubin_meta *) malloc (NPUBIN_META_SIZE);
334 logerr (TAG, "Failed to allocate metadata\n");
338 ret = fread (meta, 1, NPUBIN_META_SIZE, fp);
339 if (ret != NPUBIN_META_SIZE) {
340 logerr (TAG, "Failed to read the metadata\n");
344 if (!CHECK_NPUBIN (meta->magiccode)) {
345 logerr (TAG, "Invalid metadata provided\n");
349 if (need_extra && NPUBIN_META_EXTRA (meta->magiccode) > 0) {
350 npubin_meta *new_meta;
352 new_meta = (npubin_meta *) realloc (meta, NPUBIN_META_TOTAL_SIZE(meta->magiccode));
354 logerr (TAG, "Failed to allocate extra metadata\n");
358 ret = fread (new_meta->reserved_extra, 1, NPUBIN_META_EXTRA_SIZE (meta->magiccode), fp);
359 if (ret != NPUBIN_META_EXTRA_SIZE (meta->magiccode)) {
360 logerr (TAG, "Invalid extra metadata provided\n");
380 /** implement methods of HostHandler class */
382 /** @brief host handler constructor */
383 HostHandler::HostHandler (Device *device)
385 /* ignored as we don't use double buffering anymore, but for backward-compatibility */
386 async_mode_ (NPUASYNC_WAIT)
390 /** @brief host handler destructor */
391 HostHandler::~HostHandler ()
396 * @brief register model from generic buffer
397 * @param[in] model_buf model buffer
398 * @param[out] modelid model id
399 * @return 0 if no error. otherwise a negative errno
402 HostHandler::registerModel (generic_buffer *model_buf, uint32_t *modelid)
404 if (model_buf == nullptr || modelid == nullptr) {
405 logerr (TAG, "Invalid arguments given\n");
409 Model *model = nullptr;
410 int status = device_->setModel (model_buf, &model);
412 logerr (TAG, "Failed to set model: %d\n", status);
416 assert (model != nullptr);
418 status = models_.insert (model->getID(), model);
420 logerr (TAG, "Failed to insert model id\n");
425 *modelid = model->getID();
430 * @brief remove the registered model
431 * @param[in] modelid model id
432 * @return 0 if no error. otherwise a negative errno
435 HostHandler::unregisterModel (uint32_t modelid)
437 Model *model = models_.find (modelid);
438 if (model == nullptr)
441 int status = device_->unsetModel (model);
443 logerr (TAG, "Failed to unset model: %d\n", status);
447 return models_.remove (modelid);
451 * @brief remove all registered models
455 HostHandler::unregisterModels ()
462 * @brief Set the data layout for input/output tensors
463 * @param[in] modelid The ID of model whose layouts are set
464 * @param[in] in the layout/type info for input tensors
465 * @param[in] out the layout/type info for output tensors
466 * @return @c 0 if no error. otherwise a negative error value
467 * @note if this function is not called, default layout/type will be used.
470 HostHandler::setDataInfo (uint32_t modelid, tensors_data_info *in,
471 tensors_data_info *out)
473 Model *model = models_.find (modelid);
474 if (model == nullptr)
477 return model->setDataInfo (in, out);
481 * @brief Set the inference constraint for next NPU inferences
482 * @param[in] modelid The target model id
483 * @param[in] constraint inference constraint (e.g., timeout, priority)
484 * @return @c 0 if no error. otherwise a negative error value
485 * @note If this function is not called, default values are used.
488 HostHandler::setConstraint (uint32_t modelid, npuConstraint constraint)
490 Model *model = models_.find (modelid);
491 if (model == nullptr)
494 model->setConstraint (constraint);
500 * @brief find and return model instance
501 * @param[in] modelid model id
502 * @return model instance if found. otherwise nullptr
505 HostHandler::getModel (uint32_t modelid)
507 return models_.find (modelid);
510 /** @brief dummay callback for runSync. */
513 callbackSync (output_buffers *output) : output_(output), done_(false) {}
515 static void callback (output_buffers *output, uint64_t sequence, void *data) {
516 callbackSync *sync = static_cast<callbackSync *>(data);
517 sync->callback (output, sequence);
520 void callback (output_buffers *output, uint64_t sequence) {
521 if (output_ != nullptr) {
522 /** just copy internal variables of output buffers */
523 memcpy (output_, output, sizeof (output_buffers));
530 std::unique_lock<std::mutex> lock (m_);
531 cv_.wait (lock, [this]() { return done_; });
536 std::condition_variable cv_;
537 output_buffers *output_;
542 * @brief Execute inference. Wait (block) until the output is available.
543 * @param[in] modelid The model to be inferred.
544 * @param[in] input The input data to be inferred.
545 * @param[out] output The output result.
546 * @return @c 0 if no error. otherwise a negative error value
549 HostHandler::runSync (uint32_t modelid, const input_buffers *input,
550 output_buffers *output)
552 callbackSync sync (output);
553 int status = runAsync (modelid, input, callbackSync::callback,
554 static_cast <void*> (&sync), NPUASYNC_DROP_OLD, nullptr);
556 /** sync needs to wait callback */
563 * @brief Invoke NPU inference. Unblocking call.
564 * @param[in] modelid The model to be inferred.
565 * @param[in] input The input data to be inferred.
566 * @param[in] cb The output buffer handler.
567 * @param[in] cb_data The data given as a parameter to the runNPU_async call.
568 * @param[in] mode Configures how this operation works.
569 * @param[out] sequence The sequence number returned with runNPU_async.
570 * @return @c 0 if no error. otherwise a negative error value
573 HostHandler::runAsync (uint32_t modelid, const input_buffers *input,
574 npuOutputNotify cb, void *cb_data, npu_async_mode mode, uint64_t *sequence)
576 Model *model = nullptr;
578 if (device_->needModel()) {
579 model = getModel (modelid);
580 if (model == nullptr)
584 /* check the given model before running */
585 if (!model->finalize ()) {
586 logerr (TAG, "Failed to finalize the model. Please see the log messages\n");
590 device_->setAsyncMode (mode);
591 return device_->run (NPUINPUT_HOST, model, input, cb, cb_data, sequence);
595 * @brief get number of available devices
596 * @param[in] type device type
597 * @return number of devices
600 HostHandler::getNumDevices (dev_type type)
602 return DriverAPI::getNumDevices (type);
606 * @brief get device instance
607 * @param[out] dev device instance
608 * @param[in] type device type
609 * @param[in] id device id
610 * @return 0 if no error. otherwise a negative errno
613 HostHandler::getDevice (npudev_h *dev, dev_type type, uint32_t id)
615 int num_devices = getNumDevices (type);
617 /** check the validity of device id */
618 if (!(num_devices > 0 && id < static_cast<uint32_t>(num_devices))) {
619 logerr (TAG, "Invalid arguments provided\n");
623 Device *device = Device::createInstance (type, id);
624 if (device == nullptr) {
625 logerr (TAG, "Failed to create a device with the given type\n");
630 /** This is just for backward-compatility; we don't guarantee its corresness */
637 * @brief allocate generic buffer (just for users)
638 * @param[out] buffer buffer instance
639 * @return 0 if no error. otherwise a negative errno
642 HostHandler::allocGenericBuffer (generic_buffer *buffer)
647 if (buffer->size == 0) {
648 logerr (TAG, "Invalid size\n");
652 if (buffer->size > UINT32_MAX) {
653 logerr (TAG, "Don't support such a large size");
657 switch (buffer->type) {
660 if (buffer->filepath == nullptr)
666 /* now, npu-engine always provides dmabuf-based allocation */
667 void *addr = nullptr;
668 int dmabuf = device_->allocMemory (buffer->size, &addr);
672 buffer->dmabuf = dmabuf;
684 * @brief deallocate generic buffer (just for users)
685 * @param[in] buffer buffer instance
686 * @return 0 if no error. otherwise a negative errno
689 HostHandler::deallocGenericBuffer (generic_buffer *buffer)
695 switch (buffer->type) {
697 status = 0; /** always true cuz nothing to do */
701 status = device_->deallocMemory (buffer->dmabuf, buffer->size, buffer->addr);
712 * @brief allocate multiple generic buffers (just for users)
713 * @param[out] buffers multi-buffer instance
714 * @return 0 if no error. otherwise a negative errno
717 HostHandler::allocGenericBuffer (generic_buffers *buffers)
719 if (buffers == NULL || buffers->num_buffers < 1)
722 buffer_types type = buffers->bufs[0].type;
723 if (type == BUFFER_FILE)
726 uint64_t total_size = 0;
727 for (uint32_t idx = 0; idx < buffers->num_buffers; idx++)
728 total_size += buffers->bufs[idx].size;
730 uint64_t first_size = buffers->bufs[0].size;
731 buffers->bufs[0].size = total_size;
732 int status = allocGenericBuffer (&buffers->bufs[0]);
736 uint64_t offset = first_size;
737 for (uint32_t idx = 1; idx < buffers->num_buffers; idx++) {
738 buffers->bufs[idx].dmabuf = buffers->bufs[0].dmabuf;
739 buffers->bufs[idx].offset = buffers->bufs[0].offset + offset;
740 buffers->bufs[idx].addr = static_cast<char*>(buffers->bufs[0].addr) + offset;
741 buffers->bufs[idx].type = type;
743 offset += buffers->bufs[idx].size;
746 buffers->bufs[0].size = first_size;
752 * @brief deallocate multiple generic buffers (just for users)
753 * @param[in] buffers multi-buffer instance
754 * @return 0 if no error. otherwise a negative errno
757 HostHandler::deallocGenericBuffer (generic_buffers *buffers)
759 if (buffers == NULL || buffers->num_buffers < 1)
762 return deallocGenericBuffer (&buffers->bufs[0]);
766 * @brief get the current memory status
767 * @param[out] alloc_total The size of allocated memory until now
768 * @param[out] free_total The size of freed memory until now
769 * @return 0 if no error. otherwise a negatice error value
772 HostHandler::getMemoryStatus (size_t *alloc_total, size_t *free_total)
774 /** API is always set in initialize () */
775 const DriverAPI * api = device_->getDriverAPI ();
776 assert (api != nullptr);
778 return api->getMemoryStatus (alloc_total, free_total);
782 * @brief Get the current device status to be used
783 * @param[out] status the device status
784 * @param[out] num_requests the number of running requests (or pending)
785 * @return 0 if no error, otherwise a negative errno.
788 HostHandler::getDeviceStatus (npu_status *status, uint32_t *num_requests)
790 /** API is always set in initialize () */
791 const DriverAPI * api = device_->getDriverAPI ();
792 assert (api != nullptr);
794 device_state_t state = api->isReady ();
795 if (state == device_state_t::STATE_READY) {
796 *num_requests = api->numRequests ();
797 if (*num_requests > 0)
809 /** implement methods of Device class */
811 /** @brief constructor of device */
812 Device::Device (dev_type type, int id, bool need_model)
813 : comm_ (CommPlugin::getCommPlugin()), type_ (type), id_ (id), need_model_ (true),
814 mode_ (NPUASYNC_WAIT), initialized_ (false), atomic_flag_ (ATOMIC_FLAG_INIT)
819 * @brief create device instance depending on device type and id
820 * @param[in] type device type
821 * @param[in] id device id
822 * @return device instance
825 Device::createInstance (dev_type type, int id)
827 Device *device = nullptr;
829 switch (type & DEVICETYPE_MASK) {
830 case DEVICETYPE_TRIV:
831 device = new TrinityVision (id);
833 case DEVICETYPE_TRIV2:
834 device = new TrinityVision2 (id);
836 case DEVICETYPE_TRIA:
837 device = new TrinityAsr (id);
843 if (device != nullptr && device->init () != 0) {
852 * @brief device initialization
853 * @return 0 if no error, otherwise a negative errno
854 * @note Init failures come from createDriverAPI() only.
859 /** should be initilizaed only once */
860 if (!atomic_flag_.test_and_set()) {
861 /** create the corresponding driver API */
862 api_ = DriverAPI::createDriverAPI (type_, id_);
863 if (api_.get() == nullptr) {
864 atomic_flag_.clear();
865 logerr (TAG, "Failed to create driver API\n");
869 handler_.reset (new HostHandler (this));
870 scheduler_.reset (new Scheduler (api_.get()));
871 mem_ = MemAllocator::createInstance (api_.get());
873 initialized_ = true; /** c++11 does not provide test() of atomic flag */
880 * @brief stop all requests from this device
881 * @param[in] force_stop indicate the schedduler waits until to handle previous requests
882 * @return 0 if no error, otherwise a negative errno
885 Device::stop (bool force_stop)
887 if (!initialized ()) {
888 logerr (TAG, "Uninitialized device; should use libnpuhost APIs\n");
892 Request *req = new Request (NPUINPUT_STOP);
893 req->setForceStop (force_stop);
894 return scheduler_->submitRequest (req);
898 * @brief allocate generic memory buffer
899 * @param[in] size the size to allocate
900 * @param[out] addr the mapped address
901 * @return dmabuf fd if no error, otherwise a negative errno
904 Device::allocMemory (size_t size, void **addr)
906 if (!initialized ()) {
907 logerr (TAG, "Uninitialized device; should use libnpuhost APIs\n");
911 if (size == 0 || addr == nullptr) {
912 logerr (TAG, "Invalid arguments\n");
916 return mem_->allocMemory (size, addr);
920 * @brief deallocate generic memory buffer
921 * @param[in] dmabuf_fd dmabuf file descriptor
922 * @param[in] size buffer size
923 * @param[in] addr mapped addr
924 * @return 0 if no error, otherwise a negative errno
927 Device::deallocMemory (int dmabuf_fd, size_t size, void * addr)
929 if (!initialized ()) {
930 logerr (TAG, "Uninitialized device; should use libnpuhost APIs\n");
934 if (dmabuf_fd < 0 || size == 0 || addr == nullptr) {
935 logerr (TAG, "Invalid arguments\n");
939 return mem_->deallocMemory (dmabuf_fd, size, addr);
943 * @brief extract the buffer instance from input generic buffers
944 * @param[in] meta the model metadata
945 * @param[in] input the input generic buffers
946 * @return the buffer instance
949 TrinityVision::prepareInputBuffers (const Metadata *meta, const input_buffers *input)
951 if (meta == nullptr || input == nullptr ||
952 meta->getInputNum() != input->num_buffers) {
953 logerr (TAG, "Invalid metadata info provided\n");
958 const generic_buffer *first = &input->bufs[0];
959 if (first->type == BUFFER_DMABUF) {
960 buffer = mem_->allocBuffer (new HWmemExternal);
961 if (buffer == nullptr)
964 buffer->setDmabuf (first->dmabuf);
965 buffer->setOffset (first->offset);
966 buffer->setSize (meta->getBufferSize());
968 buffer = mem_->allocBuffer (new HWmemDevice);
969 if (buffer == nullptr)
972 int status = buffer->alloc (meta->getBufferSize ());
974 logerr (TAG, "Failed to allocate buffer: %d\n", status);
980 int status = buffer->createTensors (meta);
982 logerr (TAG, "Failed to create tensors: %d\n", status);
991 * @brief implementation of TRIV's setModel ()
992 * @param[in] model_buf the model generic buffer
993 * @param[out] model the model instance
994 * @return 0 if no error, otherwise a negative errno
997 TrinityVision::setModel (const generic_buffer *model_buf, Model ** model_ptr)
999 if (!initialized ()) {
1000 logerr (TAG, "Uninitialized device; should use libnpuhost APIs\n");
1004 if (model_buf == nullptr || model_ptr == nullptr)
1007 Model *model = nullptr;
1008 HWmem * hwmem_prog = nullptr;
1009 HWmem * hwmem_weight = nullptr;
1012 /** In TRIV1, model data (including program/weight) should be contiguous */
1014 switch (model_buf->type) {
1017 model = mem_->allocModel (new HWmemDevice);
1018 if (model == nullptr) {
1019 logerr (TAG, "Failed to allocate model\n");
1023 status = model->alloc (model_buf->size);
1025 logerr (TAG, "Failed to allocate model: %d\n", status);
1029 /** extract the whole model data */
1030 status = comm_.extractGenericBuffer (model_buf, model->getData(), nullptr);
1032 logerr (TAG, "Failed to extract generic buffer: %d\n", status);
1040 status = model->setMetadata (model->getData());
1044 /** allocate program (optional; NOP) */
1045 if (model->getMetadata()->getProgramSize() > 0) {
1046 hwmem_prog = new HWmem (new HWmemChunk);
1047 model->setProgramData (hwmem_prog);
1049 hwmem_prog->setParent (model);
1050 hwmem_prog->setOffset (model->getMetadata()->getMetaSize());
1051 status = hwmem_prog->alloc (model->getMetadata()->getProgramSize());
1053 logerr (TAG, "Failed to allocate program\n");
1058 /** allocate weight (optional) */
1059 if (model->getMetadata()->getWeightSize() > 0) {
1060 hwmem_weight = new HWmem (new HWmemChunk);
1061 model->setWeightData (hwmem_weight);
1063 hwmem_weight->setParent (model);
1064 hwmem_weight->setOffset (model->getMetadata()->getMetaSize() +
1065 model->getMetadata()->getProgramSize());
1066 status = hwmem_weight->alloc (model->getMetadata()->getWeightSize());
1068 logerr (TAG, "Failed to allocate program\n");
1073 if (hwmem_prog != nullptr) {
1074 /** register this model to the driver */
1075 model_config_t config;
1076 config.dbuf_fd = hwmem_prog->getDmabuf ();
1077 config.program_size = hwmem_prog->getSize ();
1078 config.program_offset_addr = hwmem_prog->getOffset ();
1079 if (hwmem_weight != nullptr)
1080 config.weight_offset_addr = hwmem_weight->getOffset ();
1082 status = api_->registerModel (&config);
1086 model->setInternalID(config.id);
1098 * @brief implementation of TRIV's unsetModel ()
1099 * @param[in] model the model instance
1100 * @return 0 if no error, otherwise a negative errno
1103 TrinityVision::unsetModel (Model * model)
1105 if (!initialized ()) {
1106 logerr (TAG, "Uninitialized device; should use libnpuhost APIs\n");
1110 if (model == nullptr) {
1111 logerr (TAG, "Invalid model instance\n");
1115 if (model->getMetadata()->getProgramSize() > 0)
1116 return api_->deregisterModel (model->getInternalID ());
1122 * @brief implementation of TRIV's run()
1123 * @param[in] opmode input opmode
1124 * @param[in] model the model instance
1125 * @param[in] input generic buffers of input data
1126 * @param[in] cb the output callback
1127 * @param[in] cb_data the output callback data
1128 * @param[out] sequence The sequence number returned with runNPU_async.
1131 TrinityVision::run (npu_input_opmode opmode, const Model *model,
1132 const input_buffers *input, npuOutputNotify cb, void *cb_data,
1135 if (!initialized ()) {
1136 logerr (TAG, "Uninitialized device; should use libnpuhost APIs\n");
1140 if (opmode != NPUINPUT_HOST) {
1141 logerr (TAG, "TRIV supports only host inputservice\n");
1145 if (model == nullptr || input == nullptr) {
1146 logerr (TAG, "TRIV requires both model and input buffers\n");
1150 Buffer *buffer = prepareInputBuffers (model->getMetadata(), input);
1151 if (buffer == nullptr) {
1152 logerr (TAG, "Failed to extract buffer instance\n");
1156 if (!buffer->isExternal ()) {
1157 for (uint32_t idx = 0; idx < input->num_buffers; idx++) {
1158 auto func = std::bind (TrinityVision::manipulateData, model, idx, true,
1159 std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
1160 int status = comm_.extractGenericBuffer (&input->bufs[idx],
1161 buffer->getInputTensor(idx)->getData(), func);
1163 logerr (TAG, "Failed to feed input buffer: %d\n", status);
1169 /** this device uses CMA buffer */
1171 Request *req = new Request (opmode);
1172 req->setModel (model);
1173 req->setBuffer (buffer);
1176 req->setCallback (std::bind (&TrinityVision::callback, this, req, cb, cb_data));
1178 if (sequence != nullptr)
1179 *sequence = req->getID();
1181 return scheduler_->submitRequest (req);
1185 * @brief callback of TRIV2 request
1186 * @param[in] req the request instance
1187 * @param[in] cb callback for completion
1188 * @param[in] cb_data callback data
1189 * @note The callback invoke does not gurantee the request was successful
1190 * @todo Check the request failures
1193 TrinityVision::callback (Request *req, npuOutputNotify cb, void *cb_data)
1195 const Model *model = req->getModel ();
1196 Buffer *buffer = req->getBuffer ();
1197 output_buffers output = {
1198 .num_buffers = buffer->getOutputNum ()
1201 for (uint32_t idx = 0; idx < output.num_buffers; idx++) {
1202 uint32_t output_tensor_size = model->getOutputTensorSize (idx);
1204 if (buffer->isExternal ()) {
1205 output.bufs[idx].type = BUFFER_DMABUF;
1206 output.bufs[idx].size = output_tensor_size;
1207 output.bufs[idx].addr = buffer->getOutputTensor(idx)->getData();
1209 output.bufs[idx].type = BUFFER_MAPPED;
1210 output.bufs[idx].size = output_tensor_size;
1211 /** user needs to free this */
1212 output.bufs[idx].addr = malloc (output_tensor_size);
1214 auto func = std::bind (TrinityVision::manipulateData, model, idx, false,
1215 std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
1216 int status = comm_.insertGenericBuffer (buffer->getOutputTensor(idx)->getData(),
1217 &output.bufs[idx], func);
1219 logerr (TAG, "Failed to return output buffer: %d\n", status);
1224 cb (&output, req->getID(), cb_data);
1230 * @brief extract the segment table instance from input generic buffers
1231 * @param[in] model the model instance
1232 * @param[in] input the input generic buffers
1233 * @return the segment table instance
1236 TrinityVision2::prepareSegmentTable (const Model *model, const input_buffers *input)
1238 if (model == nullptr || input == nullptr) {
1239 logerr (TAG, "Invalid arguments provided\n");
1243 const Metadata *meta = model->getMetadata ();
1244 if (meta == nullptr ||
1245 meta->getInputNum() != input->num_buffers) {
1246 logerr (TAG, "Invalid metadata info provided\n");
1250 SegmentTable * segt = mem_->allocSegmentTable (new HWmemDevice);
1251 int status = segt->alloc ();
1253 logerr (TAG, "Failed to allocate segment table: %d\n", status);
1257 status = segt->createSegments (model, input);
1259 logerr (TAG, "Failed to create segments: %d\n", status);
1271 * @brief implementation of TRIV2's setModel ()
1272 * @param[in] model_buf the model generic buffer
1273 * @param[out] model the model instance
1274 * @return 0 if no error, otherwise a negative errno
1277 TrinityVision2::setModel (const generic_buffer *model_buf, Model ** model_ptr)
1279 if (!initialized ()) {
1280 logerr (TAG, "Uninitialized device; should use libnpuhost APIs\n");
1284 if (model_buf == nullptr || model_ptr == nullptr)
1290 switch (model_buf->type) {
1293 model = mem_->allocModel (new HWmemDevice);
1294 if (model == nullptr) {
1295 logerr (TAG, "Failed to allocate model\n");
1299 status = model->alloc (NPUBIN_META_SIZE);
1301 logerr (TAG, "Failed to allocate model: %d\n", status);
1305 status = comm_.extractGenericBuffer (model_buf, model->getData(), nullptr,
1306 0, NPUBIN_META_SIZE);
1308 logerr (TAG, "Failed to extract generic buffer: %d\n", status);
1316 status = model->setMetadata (model->getData());
1320 /** allocate program (optional; NOP) */
1321 if (model->getMetadata()->getProgramSize() > 0) {
1322 HWmem * hwmem_prog = new HWmem (new HWmemDevice);
1323 hwmem_prog->setDriverAPI (api_.get());
1325 model->setProgramData (hwmem_prog);
1327 status = hwmem_prog->alloc (model->getMetadata()->getProgramSize());
1329 logerr (TAG, "Failed to allocate program\n");
1333 status = comm_.extractGenericBuffer (model_buf, hwmem_prog->getData(), nullptr,
1334 model->getMetadata()->getMetaSize(),
1335 model->getMetadata()->getProgramSize());
1337 logerr (TAG, "Failed to extract generic buffer: %d\n", status);
1341 /** register this model to the driver */
1342 model_config_t config;
1343 config.dbuf_fd = hwmem_prog->getDmabuf ();
1344 config.program_size = hwmem_prog->getSize ();
1345 config.program_offset_addr = 0;
1347 status = api_->registerModel (&config);
1351 model->setInternalID(config.id);
1354 /** allocate weight (optional) */
1355 if (model->getMetadata()->getWeightSize() > 0) {
1356 HWmem * hwmem_weight = new HWmem (new HWmemDevice);
1357 hwmem_weight->setDriverAPI (api_.get());
1359 model->setWeightData (hwmem_weight);
1361 status = hwmem_weight->alloc (model->getMetadata()->getWeightSize());
1363 logerr (TAG, "Failed to allocate program\n");
1367 status = comm_.extractGenericBuffer (model_buf, hwmem_weight->getData(), nullptr,
1368 model->getMetadata()->getMetaSize() + model->getMetadata()->getProgramSize(),
1369 model->getMetadata()->getWeightSize());
1371 logerr (TAG, "Failed to extract generic buffer: %d\n", status);
1385 * @brief implementation of TRIV2's unsetModel ()
1386 * @param[in] model the model instance
1387 * @return 0 if no error, otherwise a negative errno
1390 TrinityVision2::unsetModel (Model * model)
1392 if (!initialized ()) {
1393 logerr (TAG, "Uninitialized device; should use libnpuhost APIs\n");
1397 if (model == nullptr) {
1398 logerr (TAG, "Invalid model instance\n");
1402 if (model->getMetadata()->getProgramSize() > 0)
1403 return api_->deregisterModel (model->getInternalID ());
1408 /** @brief implementation of TRIV2's run() */
1410 TrinityVision2::run (npu_input_opmode opmode, const Model *model,
1411 const input_buffers *input, npuOutputNotify cb, void *cb_data,
1414 if (!initialized ()) {
1415 logerr (TAG, "Uninitialized device; should use libnpuhost APIs\n");
1419 if (opmode != NPUINPUT_HOST && opmode != NPUINPUT_HW_RECURRING)
1422 /** this device uses segment table */
1423 SegmentTable * segt = prepareSegmentTable (model, input);
1424 if (segt == nullptr) {
1425 logerr (TAG, "Failed to create segment table instance\n");
1429 /** extract input data */
1430 for (uint32_t idx = 0; idx < input->num_buffers; idx++) {
1431 size_t max_seg_size = segt->getInputSegment(idx)->getSize();
1432 uint32_t seg_offset = segt->getInputSegmentOffset(idx);
1434 if (input->bufs[idx].size + seg_offset > max_seg_size) {
1435 logerr (TAG, "Too large input data provided: max segment size (%zu)\n",
1440 if (!segt->getInputSegment(idx)->isExternal ()) {
1441 auto func = std::bind (TrinityVision2::manipulateData, model, idx, true,
1442 std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
1443 int status = comm_.extractGenericBuffer (
1445 segt->getInputSegment(idx)->getData() + seg_offset,
1448 logerr (TAG, "Failed to feed input segment: %d\n", status);
1454 Request *req = new Request (opmode);
1455 req->setModel (model);
1456 req->setSegmentTable (segt);
1457 req->setCallback (std::bind (&TrinityVision2::callback, this, req, cb, cb_data));
1460 *sequence = req->getID();
1462 return scheduler_->submitRequest (req);
1465 /** @brief callback of TRIV2 request */
1467 TrinityVision2::callback (Request *req, npuOutputNotify cb, void *cb_data)
1469 const Model *model = req->getModel ();
1470 SegmentTable *segt = req->getSegmentTable ();
1471 output_buffers output = {
1472 .num_buffers = segt->getNumOutputSegments ()
1475 for (uint32_t idx = 0; idx < output.num_buffers; idx++) {
1476 uint32_t output_tensor_size = model->getOutputTensorSize (idx);
1478 output.bufs[idx].type = BUFFER_MAPPED;
1479 output.bufs[idx].size = output_tensor_size;
1480 /** user needs to free this */
1481 output.bufs[idx].addr = calloc (1, output_tensor_size);
1483 auto func = std::bind (TrinityVision2::manipulateData, model, idx, false,
1484 std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
1485 int status = comm_.insertGenericBuffer (
1486 segt->getOutputSegment(idx)->getData() + segt->getOutputSegmentOffset(idx),
1487 &output.bufs[idx], func);
1490 logerr (TAG, "Failed to return output buffer: %d\n", status);
1494 cb (&output, req->getID(), cb_data);
1499 /** @brief implementation of TRIA's run(): WIP */
1501 TrinityAsr::run (npu_input_opmode opmode, const Model *model,
1502 const input_buffers *input, npuOutputNotify cb, void *cb_data,
1505 if (!initialized ()) {
1506 logerr (TAG, "Uninitialized device; should use libnpuhost APIs\n");
1510 if (opmode != NPUINPUT_HOST)
1515 /** ASR does not require model and support only a single tensor */
1516 const generic_buffer *first_buf = &input->bufs[0];
1517 if (first_buf->type == BUFFER_DMABUF) {
1518 buffer = mem_->allocBuffer (new HWmemExternal);
1519 if (buffer == nullptr)
1522 buffer->setDmabuf (first_buf->dmabuf);
1523 buffer->setOffset (first_buf->offset);
1524 buffer->setSize (first_buf->size);
1526 buffer = mem_->allocBuffer (new HWmemDevice);
1527 if (buffer == nullptr)
1530 status = buffer->alloc (first_buf->size);
1537 status = buffer->createTensors ();
1539 logerr (TAG, "Failed to create tensors: %d\n", status);
1544 if (!buffer->isExternal ()) {
1545 status = comm_.extractGenericBuffer (first_buf,
1546 buffer->getInputTensor(0)->getData(), nullptr);
1551 Request *req = new Request (opmode);
1552 req->setBuffer (buffer);
1553 req->setCallback (std::bind (&TrinityAsr::callback, this, req, cb, cb_data));
1556 *sequence = req->getID();
1558 return scheduler_->submitRequest (req);
1561 /** @brief callback of TRIA request: WIP */
1563 TrinityAsr::callback (Request *req, npuOutputNotify cb, void *cb_data)
1567 /** Implement data manipulation (each device may have different impl.) */
1571 #define do_quantized_memcpy(type) do {\
1574 while (idx < num_elems) {\
1575 val = ((type *) src)[idx];\
1576 val = val / _scale;\
1577 val += _zero_point;\
1578 val = (val > 255.0) ? 255.0 : 0.0;\
1579 ((uint8_t *) dst)[idx++] = (uint8_t) val;\
1582 while (idx < num_elems) {\
1583 val = *(uint8_t *) src;\
1584 val -= _zero_point;\
1586 ((type *) dst)[idx++] = (type) val;\
1587 dst = (void*)(((uint8_t *) dst) + data_size);\
1588 src = (void*)(((uint8_t *) src) + 1);\
1594 * @brief memcpy during quantization
1596 static void memcpy_with_quant (bool quant, data_type type, float scale, uint32_t zero_point,
1597 void *dst, const void *src, uint32_t num_elems)
1599 double _scale = (double) scale;
1600 double _zero_point = (double) zero_point;
1602 uint32_t data_size = get_data_size (type);
1606 case DATA_TYPE_INT8:
1607 do_quantized_memcpy (int8_t);
1609 case DATA_TYPE_UINT8:
1610 do_quantized_memcpy (uint8_t);
1612 case DATA_TYPE_INT16:
1613 do_quantized_memcpy (int16_t);
1615 case DATA_TYPE_UINT16:
1616 do_quantized_memcpy (uint16_t);
1618 case DATA_TYPE_INT32:
1619 do_quantized_memcpy (int32_t);
1621 case DATA_TYPE_UINT32:
1622 do_quantized_memcpy (uint32_t);
1624 case DATA_TYPE_INT64:
1625 do_quantized_memcpy (int64_t);
1627 case DATA_TYPE_UINT64:
1628 do_quantized_memcpy (uint64_t);
1630 case DATA_TYPE_FLOAT32:
1631 do_quantized_memcpy (float);
1633 case DATA_TYPE_FLOAT64:
1634 do_quantized_memcpy (double);
1637 logerr (TAG, "Unsupported datatype %d\n", type);
1642 * @brief perform data manipulation
1643 * @param[in] model model instance
1644 * @param[in] idx tensor index
1645 * @param[in] is_input indicate it's input manipulation
1646 * @param[out] dst destination buffer
1647 * @param[in] src source buffer (feature map)
1648 * @param[in] size size to be copied
1649 * @return size of memory copy if no error, otherwise zero
1651 * @note the input data format should be NHWC
1652 * @detail rules for the memory address of activations in NPU HW.
1653 * (https://code.sec.samsung.net/confluence/pages/viewpage.action?pageId=146491864)
1655 * 1) Special case (depth == 3)
1656 * - addr(x,y,z) = addr(0,0,0) + (z) + 3 * (x + width * y)
1659 * - addr(x,y,z) = addr(0,0,0) + (z % MPA_L) + MPA_L * (x + width * (y + height * (z / MPA_L)))
1661 * Thus, if depth is not a multiple of MPA_L (i.e., 64), zero padding is required
1664 TrinityVision::manipulateData (const Model *model, uint32_t idx, bool is_input,
1665 void *dst, void *src, size_t size)
1667 const Metadata *meta = model->getMetadata();
1668 const tensor_data_info* info;
1669 const uint32_t *dims;
1670 uint32_t zero_point;
1673 /** extract required information from the metadata */
1675 if (idx >= meta->getInputNum()) {
1676 logerr (TAG, "Wrong information for input tensors in metadata\n");
1680 info = model->getInputDataInfo (idx);
1681 dims = meta->getInputDims (idx);
1682 zero_point = meta->getInputQuantZero (idx);
1683 scale = meta->getInputQuantScale (idx);
1685 if (idx >= meta->getOutputNum()) {
1686 logerr (TAG, "Wrong information for output tensors in metadata\n");
1690 info = model->getOutputDataInfo (idx);
1691 dims = meta->getOutputDims (idx);
1692 zero_point = meta->getOutputQuantZero (idx);
1693 scale = meta->getOutputQuantScale (idx);
1696 if (info == nullptr) {
1697 logerr (TAG, "Unmatched tensors info\n");
1701 uint32_t batch = dims[0];
1702 uint32_t height = dims[1];
1703 uint32_t width = dims[2];
1704 uint32_t depth = dims[3];
1706 uint32_t data_size = get_data_size (info->type);
1707 if (data_size == 0) {
1708 logerr (TAG, "Invalid data size\n");
1712 bool need_quantization = false;
1714 * note that we assume DATA_TYPE_SRNPU is the smallest data type that we consider.
1715 * Also, DATA_TYPE_SRNPU and uint8_t may be regarded as the same in the view of apps.
1717 if (info->type != DATA_TYPE_SRNPU) {
1718 assert (data_size >= get_data_size (DATA_TYPE_SRNPU));
1720 if (data_size > get_data_size (DATA_TYPE_SRNPU) ||
1721 !(zero_point == default_quant_zero && scale == default_quant_scale))
1722 need_quantization = true;
1725 /** check data manipulation is required */
1726 if (depth != 3 && depth != 64 && info->layout != DATA_LAYOUT_SRNPU) {
1727 uint32_t MPA_L = DATA_GRANULARITY;
1728 uint32_t n, h, w, d;
1729 uint32_t std_offset; /* standard offset in NHWC data format */
1730 uint32_t npu_offset; /* npu offset in NPU HW data format*/
1731 uint32_t src_offset;
1732 uint32_t dst_offset;
1733 uint32_t slice_size;
1735 /* @todo we currently support only NHWC */
1736 if (info->layout != DATA_LAYOUT_NHWC) {
1737 logerr (TAG, "data manipulation is supported for NHWC only\n");
1741 for (n = 0; n < batch; n++) {
1742 for (h = 0; h < height; h++) {
1743 for (w = 0; w < width; w++) {
1744 for (d = 0; d < depth; d += MPA_L) {
1745 std_offset = d + depth * (w + width * (h + n * height));
1746 npu_offset = MPA_L * (w + width * (h + (n + d / MPA_L) * height));
1747 slice_size = (depth - d >= MPA_L) ? MPA_L : depth - d;
1750 src_offset = std_offset * data_size;
1751 dst_offset = npu_offset;
1753 src_offset = npu_offset;
1754 dst_offset = std_offset * data_size;
1757 /* if depth is not a multiple of MPA_L, add zero paddings (not exact values) */
1758 if (need_quantization) {
1759 memcpy_with_quant (is_input, info->type, scale, zero_point,
1760 static_cast<char*>(dst) + dst_offset,
1761 static_cast<char*>(src) + src_offset,
1765 static_cast<char*>(dst) + dst_offset,
1766 static_cast<char*>(src) + src_offset,
1773 } else if (need_quantization) {
1774 /** depth == 3 || depth == 64; special cases which can directly copy input tensor data */
1775 memcpy_with_quant (is_input, info->type, scale, zero_point,
1776 dst, src, is_input ? size / data_size : size);
1778 memcpy (dst, src, size);
1787 TrinityVision::manipulateData (const Model *model, uint32_t idx, bool is_input,
1788 void *dst, void *src, size_t size)
1790 memcpy (dst, src, size);
1796 /** other device types don't have data manip impl. yet */
1799 TrinityVision2::manipulateData (const Model *model, uint32_t idx, bool is_input,
1800 void *dst, void *src, size_t size)
1802 memcpy (dst, src, size);
1807 TrinityAsr::manipulateData (const Model *model, uint32_t idx, bool is_input,
1808 void *dst, void *src, size_t size)
1810 memcpy (dst, src, size);