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 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 /** implement methods of HostHandler class */
368 /** @brief host handler constructor */
369 HostHandler::HostHandler (Device *device)
371 /* ignored as we don't use double buffering anymore, but for backward-compatibility */
372 async_mode_ (NPUASYNC_WAIT)
376 /** @brief host handler destructor */
377 HostHandler::~HostHandler ()
382 * @brief register model from generic buffer
383 * @param[in] model_buf model buffer
384 * @param[out] modelid model id
385 * @return 0 if no error. otherwise a negative errno
388 HostHandler::registerModel (generic_buffer *model_buf, uint32_t *modelid)
390 if (model_buf == nullptr || modelid == nullptr) {
391 logerr (TAG, "Invalid arguments given\n");
395 Model *model = nullptr;
396 int status = device_->setModel (model_buf, &model);
398 logerr (TAG, "Failed to set model: %d\n", status);
402 assert (model != nullptr);
404 status = models_.insert (model->getID(), model);
406 logerr (TAG, "Failed to insert model id\n");
411 *modelid = model->getID();
416 * @brief remove the registered model
417 * @param[in] modelid model id
418 * @return 0 if no error. otherwise a negative errno
421 HostHandler::unregisterModel (uint32_t modelid)
423 Model *model = models_.find (modelid);
424 if (model == nullptr)
427 int status = device_->unsetModel (model);
429 logerr (TAG, "Failed to unset model: %d\n", status);
433 return models_.remove (modelid);
437 * @brief remove all registered models
441 HostHandler::unregisterModels ()
448 * @brief Set the data layout for input/output tensors
449 * @param[in] modelid The ID of model whose layouts are set
450 * @param[in] in the layout/type info for input tensors
451 * @param[in] out the layout/type info for output tensors
452 * @return @c 0 if no error. otherwise a negative error value
453 * @note if this function is not called, default layout/type will be used.
456 HostHandler::setDataInfo (uint32_t modelid, tensors_data_info *in,
457 tensors_data_info *out)
459 Model *model = models_.find (modelid);
460 if (model == nullptr)
463 return model->setDataInfo (in, out);
467 * @brief Set the inference constraint for next NPU inferences
468 * @param[in] modelid The target model id
469 * @param[in] constraint inference constraint (e.g., timeout, priority)
470 * @return @c 0 if no error. otherwise a negative error value
471 * @note If this function is not called, default values are used.
474 HostHandler::setConstraint (uint32_t modelid, npuConstraint constraint)
476 Model *model = models_.find (modelid);
477 if (model == nullptr)
480 model->setConstraint (constraint);
486 * @brief find and return model instance
487 * @param[in] modelid model id
488 * @return model instance if found. otherwise nullptr
491 HostHandler::getModel (uint32_t modelid)
493 return models_.find (modelid);
496 /** @brief dummay callback for runSync. */
499 callbackSync (output_buffers *output) : output_(output), done_(false) {}
501 static void callback (output_buffers *output, uint64_t sequence, void *data) {
502 callbackSync *sync = static_cast<callbackSync *>(data);
503 sync->callback (output, sequence);
506 void callback (output_buffers *output, uint64_t sequence) {
507 if (output_ != nullptr) {
508 /** just copy internal variables of output buffers */
509 memcpy (output_, output, sizeof (output_buffers));
516 std::unique_lock<std::mutex> lock (m_);
517 cv_.wait (lock, [this]() { return done_; });
522 std::condition_variable cv_;
523 output_buffers *output_;
528 * @brief Execute inference. Wait (block) until the output is available.
529 * @param[in] modelid The model to be inferred.
530 * @param[in] input The input data to be inferred.
531 * @param[out] output The output result.
532 * @return @c 0 if no error. otherwise a negative error value
535 HostHandler::runSync (uint32_t modelid, const input_buffers *input,
536 output_buffers *output)
538 callbackSync sync (output);
539 int status = runAsync (modelid, input, callbackSync::callback,
540 static_cast <void*> (&sync), NPUASYNC_DROP_OLD, nullptr);
542 /** sync needs to wait callback */
549 * @brief Invoke NPU inference. Unblocking call.
550 * @param[in] modelid The model to be inferred.
551 * @param[in] input The input data to be inferred.
552 * @param[in] cb The output buffer handler.
553 * @param[in] cb_data The data given as a parameter to the runNPU_async call.
554 * @param[in] mode Configures how this operation works.
555 * @param[out] sequence The sequence number returned with runNPU_async.
556 * @return @c 0 if no error. otherwise a negative error value
559 HostHandler::runAsync (uint32_t modelid, const input_buffers *input,
560 npuOutputNotify cb, void *cb_data, npu_async_mode mode, uint64_t *sequence)
562 Model *model = nullptr;
564 if (device_->needModel()) {
565 model = getModel (modelid);
566 if (model == nullptr)
570 device_->setAsyncMode (mode);
571 return device_->run (NPUINPUT_HOST, model, input, cb, cb_data, sequence);
575 * @brief get number of available devices
576 * @param[in] type device type
577 * @return number of devices
580 HostHandler::getNumDevices (dev_type type)
582 return DriverAPI::getNumDevices (type);
586 * @brief get device instance
587 * @param[out] dev device instance
588 * @param[in] type device type
589 * @param[in] id device id
590 * @return 0 if no error. otherwise a negative errno
593 HostHandler::getDevice (npudev_h *dev, dev_type type, uint32_t id)
595 int num_devices = getNumDevices (type);
597 /** check the validity of device id */
598 if (!(num_devices > 0 && id < static_cast<uint32_t>(num_devices))) {
599 logerr (TAG, "Invalid arguments provided\n");
603 Device *device = Device::createInstance (type, id);
604 if (device == nullptr) {
605 logerr (TAG, "Failed to create a device with the given type\n");
610 /** This is just for backward-compatility; we don't guarantee its corresness */
617 * @brief allocate generic buffer (just for users)
618 * @param[out] buffer buffer instance
619 * @return 0 if no error. otherwise a negative errno
622 HostHandler::allocGenericBuffer (generic_buffer *buffer)
627 if (buffer->size == 0) {
628 logerr (TAG, "Invalid size\n");
632 if (buffer->size > UINT32_MAX) {
633 logerr (TAG, "Don't support such a large size");
637 switch (buffer->type) {
640 if (buffer->filepath == nullptr)
646 /* now, npu-engine always provides dmabuf-based allocation */
647 void *addr = nullptr;
648 int dmabuf = device_->allocMemory (buffer->size, &addr);
652 buffer->dmabuf = dmabuf;
664 * @brief deallocate generic buffer (just for users)
665 * @param[in] buffer buffer instance
666 * @return 0 if no error. otherwise a negative errno
669 HostHandler::deallocGenericBuffer (generic_buffer *buffer)
675 switch (buffer->type) {
677 status = 0; /** always true cuz nothing to do */
681 status = device_->deallocMemory (buffer->dmabuf, buffer->size, buffer->addr);
692 * @brief allocate multiple generic buffers (just for users)
693 * @param[out] buffers multi-buffer instance
694 * @return 0 if no error. otherwise a negative errno
697 HostHandler::allocGenericBuffer (generic_buffers *buffers)
699 if (buffers == NULL || buffers->num_buffers < 1)
702 buffer_types type = buffers->bufs[0].type;
703 if (type == BUFFER_FILE)
706 uint64_t total_size = 0;
707 for (uint32_t idx = 0; idx < buffers->num_buffers; idx++)
708 total_size += buffers->bufs[idx].size;
710 uint64_t first_size = buffers->bufs[0].size;
711 buffers->bufs[0].size = total_size;
712 int status = allocGenericBuffer (&buffers->bufs[0]);
716 uint64_t offset = first_size;
717 for (uint32_t idx = 1; idx < buffers->num_buffers; idx++) {
718 buffers->bufs[idx].dmabuf = buffers->bufs[0].dmabuf;
719 buffers->bufs[idx].offset = buffers->bufs[0].offset + offset;
720 buffers->bufs[idx].addr = static_cast<char*>(buffers->bufs[0].addr) + offset;
721 buffers->bufs[idx].type = type;
723 offset += buffers->bufs[idx].size;
726 buffers->bufs[0].size = first_size;
732 * @brief deallocate multiple generic buffers (just for users)
733 * @param[in] buffers multi-buffer instance
734 * @return 0 if no error. otherwise a negative errno
737 HostHandler::deallocGenericBuffer (generic_buffers *buffers)
739 if (buffers == NULL || buffers->num_buffers < 1)
742 return deallocGenericBuffer (&buffers->bufs[0]);
746 * @brief get the current memory status
747 * @param[out] alloc_total The size of allocated memory until now
748 * @param[out] free_total The size of freed memory until now
749 * @return 0 if no error. otherwise a negatice error value
752 HostHandler::getMemoryStatus (size_t *alloc_total, size_t *free_total)
754 /** API is always set in initialize () */
755 const DriverAPI * api = device_->getDriverAPI ();
756 assert (api != nullptr);
758 return api->getMemoryStatus (alloc_total, free_total);
761 /** implement methods of Device class */
763 /** @brief constructor of device */
764 Device::Device (dev_type type, int id, bool need_model)
765 : comm_ (CommPlugin::getCommPlugin()), type_ (type), id_ (id), need_model_ (true),
766 mode_ (NPUASYNC_WAIT), initialized_ (false), atomic_flag_ (ATOMIC_FLAG_INIT)
771 * @brief create device instance depending on device type and id
772 * @param[in] type device type
773 * @param[in] id device id
774 * @return device instance
777 Device::createInstance (dev_type type, int id)
779 Device *device = nullptr;
781 switch (type & DEVICETYPE_MASK) {
782 case DEVICETYPE_TRIV:
783 device = new TrinityVision (id);
785 case DEVICETYPE_TRIV2:
786 device = new TrinityVision2 (id);
788 case DEVICETYPE_TRIA:
789 device = new TrinityAsr (id);
795 if (device != nullptr && device->init () != 0) {
804 * @brief device initialization
805 * @return 0 if no error, otherwise a negative errno
806 * @note Init failures come from createDriverAPI() only.
811 /** should be initilizaed only once */
812 if (!atomic_flag_.test_and_set()) {
813 /** create the corresponding driver API */
814 api_ = DriverAPI::createDriverAPI (type_, id_);
815 if (api_.get() == nullptr) {
816 atomic_flag_.clear();
817 logerr (TAG, "Failed to create driver API\n");
821 handler_.reset (new HostHandler (this));
822 scheduler_.reset (new Scheduler (api_.get()));
823 mem_ = MemAllocator::createInstance (api_.get());
825 initialized_ = true; /** c++11 does not provide test() of atomic flag */
832 * @brief stop all requests from this device
833 * @param[in] force_stop indicate the schedduler waits until to handle previous requests
834 * @return 0 if no error, otherwise a negative errno
837 Device::stop (bool force_stop)
839 if (!initialized ()) {
840 logerr (TAG, "Uninitialized device; should use libnpuhost APIs\n");
844 Request *req = new Request (NPUINPUT_STOP);
845 req->setForceStop (force_stop);
846 return scheduler_->submitRequest (req);
850 * @brief allocate generic memory buffer
851 * @param[in] size the size to allocate
852 * @param[out] addr the mapped address
853 * @return dmabuf fd if no error, otherwise a negative errno
856 Device::allocMemory (size_t size, void **addr)
858 if (!initialized ()) {
859 logerr (TAG, "Uninitialized device; should use libnpuhost APIs\n");
863 if (size == 0 || addr == nullptr) {
864 logerr (TAG, "Invalid arguments\n");
868 return mem_->allocMemory (size, addr);
872 * @brief deallocate generic memory buffer
873 * @param[in] dmabuf_fd dmabuf file descriptor
874 * @param[in] size buffer size
875 * @param[in] addr mapped addr
876 * @return 0 if no error, otherwise a negative errno
879 Device::deallocMemory (int dmabuf_fd, size_t size, void * addr)
881 if (!initialized ()) {
882 logerr (TAG, "Uninitialized device; should use libnpuhost APIs\n");
886 if (dmabuf_fd < 0 || size == 0 || addr == nullptr) {
887 logerr (TAG, "Invalid arguments\n");
891 return mem_->deallocMemory (dmabuf_fd, size, addr);
895 * @brief extract the buffer instance from input generic buffers
896 * @param[in] meta the model metadata
897 * @param[in] input the input generic buffers
898 * @return the buffer instance
901 TrinityVision::prepareInputBuffers (const Metadata *meta, const input_buffers *input)
903 if (meta == nullptr || input == nullptr ||
904 meta->getInputNum() != input->num_buffers) {
905 logerr (TAG, "Invalid metadata info provided\n");
910 const generic_buffer *first = &input->bufs[0];
911 if (first->type == BUFFER_DMABUF) {
912 buffer = mem_->allocBuffer (new HWmemExternal);
913 if (buffer == nullptr)
916 buffer->setDmabuf (first->dmabuf);
917 buffer->setOffset (first->offset);
918 buffer->setSize (meta->getBufferSize());
920 buffer = mem_->allocBuffer (new HWmemDevice);
921 if (buffer == nullptr)
924 int status = buffer->alloc (meta->getBufferSize ());
926 logerr (TAG, "Failed to allocate buffer: %d\n", status);
932 int status = buffer->createTensors (meta);
934 logerr (TAG, "Failed to create tensors: %d\n", status);
943 * @brief implementation of TRIV's setModel ()
944 * @param[in] model_buf the model generic buffer
945 * @param[out] model the model instance
946 * @return 0 if no error, otherwise a negative errno
949 TrinityVision::setModel (const generic_buffer *model_buf, Model ** model_ptr)
951 if (!initialized ()) {
952 logerr (TAG, "Uninitialized device; should use libnpuhost APIs\n");
956 if (model_buf == nullptr || model_ptr == nullptr)
962 /** In TRIV1, model data (including program/weight) should be contiguous */
964 switch (model_buf->type) {
967 model = mem_->allocModel (new HWmemDevice);
968 if (model == nullptr) {
969 logerr (TAG, "Failed to allocate model\n");
973 status = model->alloc (model_buf->size);
975 logerr (TAG, "Failed to allocate model: %d\n", status);
979 /** extract the whole model data */
980 status = comm_.extractGenericBuffer (model_buf, model->getData(), nullptr);
982 logerr (TAG, "Failed to extract generic buffer: %d\n", status);
990 status = model->setMetadata (model->getData());
994 /** allocate program (optional; NOP) */
995 if (model->getMetadata()->getProgramSize() > 0) {
996 HWmem * hwmem_prog = new HWmem (new HWmemChunk);
997 model->setProgramData (hwmem_prog);
999 hwmem_prog->setParent (model);
1000 hwmem_prog->setOffset (model->getMetadata()->getMetaSize());
1001 status = hwmem_prog->alloc (model->getMetadata()->getProgramSize());
1003 logerr (TAG, "Failed to allocate program\n");
1007 /** register this model to the driver */
1008 model_config_t config;
1009 config.dbuf_fd = hwmem_prog->getDmabuf ();
1010 config.program_size = hwmem_prog->getSize ();
1011 config.program_offset_addr = hwmem_prog->getOffset ();
1013 status = api_->registerModel (&config);
1017 model->setInternalID(config.id);
1020 /** allocate weight (optional) */
1021 if (model->getMetadata()->getWeightSize() > 0) {
1022 HWmem * hwmem_weight = new HWmem (new HWmemChunk);
1023 model->setWeightData (hwmem_weight);
1025 hwmem_weight->setParent (model);
1026 hwmem_weight->setOffset (model->getMetadata()->getMetaSize() +
1027 model->getMetadata()->getProgramSize());
1028 status = hwmem_weight->alloc (model->getMetadata()->getWeightSize());
1030 logerr (TAG, "Failed to allocate program\n");
1044 * @brief implementation of TRIV's unsetModel ()
1045 * @param[in] model the model instance
1046 * @return 0 if no error, otherwise a negative errno
1049 TrinityVision::unsetModel (Model * model)
1051 if (!initialized ()) {
1052 logerr (TAG, "Uninitialized device; should use libnpuhost APIs\n");
1056 if (model == nullptr) {
1057 logerr (TAG, "Invalid model instance\n");
1061 if (model->getMetadata()->getProgramSize() > 0)
1062 return api_->deregisterModel (model->getInternalID ());
1068 * @brief implementation of TRIV's run()
1069 * @param[in] opmode input opmode
1070 * @param[in] model the model instance
1071 * @param[in] input generic buffers of input data
1072 * @param[in] cb the output callback
1073 * @param[in] cb_data the output callback data
1074 * @param[out] sequence The sequence number returned with runNPU_async.
1077 TrinityVision::run (npu_input_opmode opmode, const Model *model,
1078 const input_buffers *input, npuOutputNotify cb, void *cb_data,
1081 if (!initialized ()) {
1082 logerr (TAG, "Uninitialized device; should use libnpuhost APIs\n");
1086 if (opmode != NPUINPUT_HOST) {
1087 logerr (TAG, "TRIV supports only host inputservice\n");
1091 if (model == nullptr || input == nullptr) {
1092 logerr (TAG, "TRIV requires both model and input buffers\n");
1096 Buffer *buffer = prepareInputBuffers (model->getMetadata(), input);
1097 if (buffer == nullptr) {
1098 logerr (TAG, "Failed to extract buffer instance\n");
1102 if (!buffer->isExternal ()) {
1103 for (uint32_t idx = 0; idx < input->num_buffers; idx++) {
1104 auto func = std::bind (TrinityVision::manipulateData, model, idx, true,
1105 std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
1106 int status = comm_.extractGenericBuffer (&input->bufs[idx],
1107 buffer->getInputTensor(idx)->getData(), func);
1109 logerr (TAG, "Failed to feed input buffer: %d\n", status);
1115 /** this device uses CMA buffer */
1117 Request *req = new Request (opmode);
1118 req->setModel (model);
1119 req->setBuffer (buffer);
1122 req->setCallback (std::bind (&TrinityVision::callback, this, req, cb, cb_data));
1124 if (sequence != nullptr)
1125 *sequence = req->getID();
1127 return scheduler_->submitRequest (req);
1131 * @brief callback of TRIV2 request
1132 * @param[in] req the request instance
1133 * @param[in] cb callback for completion
1134 * @param[in] cb_data callback data
1135 * @note The callback invoke does not gurantee the request was successful
1136 * @todo Check the request failures
1139 TrinityVision::callback (Request *req, npuOutputNotify cb, void *cb_data)
1141 const Model *model = req->getModel ();
1142 Buffer *buffer = req->getBuffer ();
1143 output_buffers output = {
1144 .num_buffers = buffer->getOutputNum ()
1147 for (uint32_t idx = 0; idx < output.num_buffers; idx++) {
1148 uint32_t output_tensor_size = model->getOutputTensorSize (idx);
1150 if (buffer->isExternal ()) {
1151 output.bufs[idx].type = BUFFER_DMABUF;
1152 output.bufs[idx].size = output_tensor_size;
1153 output.bufs[idx].addr = buffer->getOutputTensor(idx)->getData();
1155 output.bufs[idx].type = BUFFER_MAPPED;
1156 output.bufs[idx].size = output_tensor_size;
1157 /** user needs to free this */
1158 output.bufs[idx].addr = malloc (output_tensor_size);
1160 auto func = std::bind (TrinityVision::manipulateData, model, idx, false,
1161 std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
1162 int status = comm_.insertGenericBuffer (buffer->getOutputTensor(idx)->getData(),
1163 &output.bufs[idx], func);
1165 logerr (TAG, "Failed to return output buffer: %d\n", status);
1170 cb (&output, req->getID(), cb_data);
1176 * @brief extract the segment table instance from input generic buffers
1177 * @param[in] model the model instance
1178 * @param[in] input the input generic buffers
1179 * @return the segment table instance
1182 TrinityVision2::prepareSegmentTable (const Model *model, const input_buffers *input)
1184 if (model == nullptr || input == nullptr) {
1185 logerr (TAG, "Invalid arguments provided\n");
1189 const Metadata *meta = model->getMetadata ();
1190 if (meta == nullptr ||
1191 meta->getInputNum() != input->num_buffers) {
1192 logerr (TAG, "Invalid metadata info provided\n");
1196 SegmentTable * segt = mem_->allocSegmentTable (new HWmemDevice);
1197 int status = segt->alloc ();
1199 logerr (TAG, "Failed to allocate segment table: %d\n", status);
1203 status = segt->createSegments (model, input);
1205 logerr (TAG, "Failed to create segments: %d\n", status);
1217 * @brief implementation of TRIV2's setModel ()
1218 * @param[in] model_buf the model generic buffer
1219 * @param[out] model the model instance
1220 * @return 0 if no error, otherwise a negative errno
1223 TrinityVision2::setModel (const generic_buffer *model_buf, Model ** model_ptr)
1225 if (!initialized ()) {
1226 logerr (TAG, "Uninitialized device; should use libnpuhost APIs\n");
1230 if (model_buf == nullptr || model_ptr == nullptr)
1236 switch (model_buf->type) {
1239 model = mem_->allocModel (new HWmemDevice);
1240 if (model == nullptr) {
1241 logerr (TAG, "Failed to allocate model\n");
1245 status = model->alloc (NPUBIN_META_SIZE);
1247 logerr (TAG, "Failed to allocate model: %d\n", status);
1251 status = comm_.extractGenericBuffer (model_buf, model->getData(), nullptr,
1252 0, NPUBIN_META_SIZE);
1254 logerr (TAG, "Failed to extract generic buffer: %d\n", status);
1262 status = model->setMetadata (model->getData());
1266 /** allocate program (optional; NOP) */
1267 if (model->getMetadata()->getProgramSize() > 0) {
1268 HWmem * hwmem_prog = new HWmem (new HWmemDevice);
1269 hwmem_prog->setDriverAPI (api_.get());
1271 model->setProgramData (hwmem_prog);
1273 status = hwmem_prog->alloc (model->getMetadata()->getProgramSize());
1275 logerr (TAG, "Failed to allocate program\n");
1279 status = comm_.extractGenericBuffer (model_buf, hwmem_prog->getData(), nullptr,
1280 model->getMetadata()->getMetaSize(),
1281 model->getMetadata()->getProgramSize());
1283 logerr (TAG, "Failed to extract generic buffer: %d\n", status);
1287 /** register this model to the driver */
1288 model_config_t config;
1289 config.dbuf_fd = hwmem_prog->getDmabuf ();
1290 config.program_size = hwmem_prog->getSize ();
1291 config.program_offset_addr = 0;
1293 status = api_->registerModel (&config);
1297 model->setInternalID(config.id);
1300 /** allocate weight (optional) */
1301 if (model->getMetadata()->getWeightSize() > 0) {
1302 HWmem * hwmem_weight = new HWmem (new HWmemDevice);
1303 hwmem_weight->setDriverAPI (api_.get());
1305 model->setWeightData (hwmem_weight);
1307 status = hwmem_weight->alloc (model->getMetadata()->getWeightSize());
1309 logerr (TAG, "Failed to allocate program\n");
1313 status = comm_.extractGenericBuffer (model_buf, hwmem_weight->getData(), nullptr,
1314 model->getMetadata()->getMetaSize() + model->getMetadata()->getProgramSize(),
1315 model->getMetadata()->getWeightSize());
1317 logerr (TAG, "Failed to extract generic buffer: %d\n", status);
1331 * @brief implementation of TRIV2's unsetModel ()
1332 * @param[in] model the model instance
1333 * @return 0 if no error, otherwise a negative errno
1336 TrinityVision2::unsetModel (Model * model)
1338 if (!initialized ()) {
1339 logerr (TAG, "Uninitialized device; should use libnpuhost APIs\n");
1343 if (model == nullptr) {
1344 logerr (TAG, "Invalid model instance\n");
1348 if (model->getMetadata()->getProgramSize() > 0)
1349 return api_->deregisterModel (model->getInternalID ());
1354 /** @brief implementation of TRIV2's run() */
1356 TrinityVision2::run (npu_input_opmode opmode, const Model *model,
1357 const input_buffers *input, npuOutputNotify cb, void *cb_data,
1360 if (!initialized ()) {
1361 logerr (TAG, "Uninitialized device; should use libnpuhost APIs\n");
1365 if (opmode != NPUINPUT_HOST && opmode != NPUINPUT_HW_RECURRING)
1368 /** this device uses segment table */
1369 SegmentTable * segt = prepareSegmentTable (model, input);
1370 if (segt == nullptr) {
1371 logerr (TAG, "Failed to create segment table instance\n");
1375 /** extract input data */
1376 for (uint32_t idx = 0; idx < input->num_buffers; idx++) {
1377 if (!segt->getInputSegment(idx)->isExternal ()) {
1378 auto func = std::bind (TrinityVision2::manipulateData, model, idx, true,
1379 std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
1380 int status = comm_.extractGenericBuffer (
1382 segt->getInputSegment(idx)->getData() + segt->getInputSegmentOffset(idx),
1385 logerr (TAG, "Failed to feed input segment: %d\n", status);
1391 Request *req = new Request (opmode);
1392 req->setModel (model);
1393 req->setSegmentTable (segt);
1394 req->setCallback (std::bind (&TrinityVision2::callback, this, req, cb, cb_data));
1397 *sequence = req->getID();
1399 return scheduler_->submitRequest (req);
1402 /** @brief callback of TRIV2 request */
1404 TrinityVision2::callback (Request *req, npuOutputNotify cb, void *cb_data)
1406 const Model *model = req->getModel ();
1407 SegmentTable *segt = req->getSegmentTable ();
1408 output_buffers output = {
1409 .num_buffers = segt->getNumOutputSegments ()
1412 for (uint32_t idx = 0; idx < output.num_buffers; idx++) {
1413 uint32_t output_tensor_size = model->getOutputTensorSize (idx);
1415 output.bufs[idx].type = BUFFER_MAPPED;
1416 output.bufs[idx].size = output_tensor_size;
1417 /** user needs to free this */
1418 output.bufs[idx].addr = malloc (output_tensor_size);
1420 auto func = std::bind (TrinityVision2::manipulateData, model, idx, false,
1421 std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
1422 int status = comm_.insertGenericBuffer (
1423 segt->getOutputSegment(idx)->getData() + segt->getOutputSegmentOffset(idx),
1424 &output.bufs[idx], func);
1426 logerr (TAG, "Failed to return output buffer: %d\n", status);
1430 cb (&output, req->getID(), cb_data);
1435 /** @brief implementation of TRIA's run(): WIP */
1437 TrinityAsr::run (npu_input_opmode opmode, const Model *model,
1438 const input_buffers *input, npuOutputNotify cb, void *cb_data,
1441 if (!initialized ()) {
1442 logerr (TAG, "Uninitialized device; should use libnpuhost APIs\n");
1446 if (opmode != NPUINPUT_HOST)
1451 /** ASR does not require model and support only a single tensor */
1452 const generic_buffer *first_buf = &input->bufs[0];
1453 if (first_buf->type == BUFFER_DMABUF) {
1454 buffer = mem_->allocBuffer (new HWmemExternal);
1455 if (buffer == nullptr)
1458 buffer->setDmabuf (first_buf->dmabuf);
1459 buffer->setOffset (first_buf->offset);
1460 buffer->setSize (first_buf->size);
1462 buffer = mem_->allocBuffer (new HWmemDevice);
1463 if (buffer == nullptr)
1466 status = buffer->alloc (first_buf->size);
1473 status = buffer->createTensors ();
1475 logerr (TAG, "Failed to create tensors: %d\n", status);
1480 if (!buffer->isExternal ()) {
1481 status = comm_.extractGenericBuffer (first_buf,
1482 buffer->getInputTensor(0)->getData(), nullptr);
1487 Request *req = new Request (opmode);
1488 req->setBuffer (buffer);
1489 req->setCallback (std::bind (&TrinityAsr::callback, this, req, cb, cb_data));
1492 *sequence = req->getID();
1494 return scheduler_->submitRequest (req);
1497 /** @brief callback of TRIA request: WIP */
1499 TrinityAsr::callback (Request *req, npuOutputNotify cb, void *cb_data)
1503 /** Implement data manipulation (each device may have different impl.) */
1507 #define do_quantized_memcpy(type) do {\
1510 while (idx < num_elems) {\
1511 val = ((type *) src)[idx];\
1512 val = val / _scale;\
1513 val += _zero_point;\
1514 val = (val > 255.0) ? 255.0 : 0.0;\
1515 ((uint8_t *) dst)[idx++] = (uint8_t) val;\
1518 while (idx < num_elems) {\
1519 val = *(uint8_t *) src;\
1520 val -= _zero_point;\
1522 ((type *) dst)[idx++] = (type) val;\
1523 dst = (void*)(((uint8_t *) dst) + data_size);\
1524 src = (void*)(((uint8_t *) src) + 1);\
1530 * @brief memcpy during quantization
1532 static void memcpy_with_quant (bool quant, data_type type, float scale, uint32_t zero_point,
1533 void *dst, const void *src, uint32_t num_elems)
1535 double _scale = (double) scale;
1536 double _zero_point = (double) zero_point;
1538 uint32_t data_size = get_data_size (type);
1542 case DATA_TYPE_INT8:
1543 do_quantized_memcpy (int8_t);
1545 case DATA_TYPE_UINT8:
1546 do_quantized_memcpy (uint8_t);
1548 case DATA_TYPE_INT16:
1549 do_quantized_memcpy (int16_t);
1551 case DATA_TYPE_UINT16:
1552 do_quantized_memcpy (uint16_t);
1554 case DATA_TYPE_INT32:
1555 do_quantized_memcpy (int32_t);
1557 case DATA_TYPE_UINT32:
1558 do_quantized_memcpy (uint32_t);
1560 case DATA_TYPE_INT64:
1561 do_quantized_memcpy (int64_t);
1563 case DATA_TYPE_UINT64:
1564 do_quantized_memcpy (uint64_t);
1566 case DATA_TYPE_FLOAT32:
1567 do_quantized_memcpy (float);
1569 case DATA_TYPE_FLOAT64:
1570 do_quantized_memcpy (double);
1573 logerr (TAG, "Unsupported datatype %d\n", type);
1578 * @brief perform data manipulation
1579 * @param[in] model model instance
1580 * @param[in] idx tensor index
1581 * @param[in] is_input indicate it's input manipulation
1582 * @param[out] dst destination buffer
1583 * @param[in] src source buffer (feature map)
1584 * @param[in] size size to be copied
1585 * @return size of memory copy if no error, otherwise zero
1587 * @note the input data format should be NHWC
1588 * @detail rules for the memory address of activations in NPU HW.
1589 * (https://code.sec.samsung.net/confluence/pages/viewpage.action?pageId=146491864)
1591 * 1) Special case (depth == 3)
1592 * - addr(x,y,z) = addr(0,0,0) + (z) + 3 * (x + width * y)
1595 * - addr(x,y,z) = addr(0,0,0) + (z % MPA_L) + MPA_L * (x + width * (y + height * (z / MPA_L)))
1597 * Thus, if depth is not a multiple of MPA_L (i.e., 64), zero padding is required
1600 TrinityVision::manipulateData (const Model *model, uint32_t idx, bool is_input,
1601 void *dst, void *src, size_t size)
1603 const Metadata *meta = model->getMetadata();
1604 const tensor_data_info* info;
1605 const uint32_t *dims;
1606 uint32_t zero_point;
1609 /** extract required information from the metadata */
1611 if (idx >= meta->getInputNum()) {
1612 logerr (TAG, "Wrong information for input tensors in metadata\n");
1616 info = model->getInputDataInfo (idx);
1617 dims = meta->getInputDims (idx);
1618 zero_point = meta->getInputQuantZero (idx);
1619 scale = meta->getInputQuantScale (idx);
1621 if (idx >= meta->getOutputNum()) {
1622 logerr (TAG, "Wrong information for output tensors in metadata\n");
1626 info = model->getOutputDataInfo (idx);
1627 dims = meta->getOutputDims (idx);
1628 zero_point = meta->getOutputQuantZero (idx);
1629 scale = meta->getOutputQuantScale (idx);
1632 if (info == nullptr) {
1633 logerr (TAG, "Unmatched tensors info\n");
1637 uint32_t batch = dims[0];
1638 uint32_t height = dims[1];
1639 uint32_t width = dims[2];
1640 uint32_t depth = dims[3];
1642 uint32_t data_size = get_data_size (info->type);
1643 if (data_size == 0) {
1644 logerr (TAG, "Invalid data size\n");
1648 bool need_quantization = false;
1650 * note that we assume DATA_TYPE_SRNPU is the smallest data type that we consider.
1651 * Also, DATA_TYPE_SRNPU and uint8_t may be regarded as the same in the view of apps.
1653 if (info->type != DATA_TYPE_SRNPU) {
1654 assert (data_size >= get_data_size (DATA_TYPE_SRNPU));
1656 if (data_size > get_data_size (DATA_TYPE_SRNPU) ||
1657 !(zero_point == default_quant_zero && scale == default_quant_scale))
1658 need_quantization = true;
1661 /** check data manipulation is required */
1662 if (depth != 3 && depth != 64 && info->layout != DATA_LAYOUT_SRNPU) {
1663 uint32_t MPA_L = DATA_GRANULARITY;
1664 uint32_t n, h, w, d;
1665 uint32_t std_offset; /* standard offset in NHWC data format */
1666 uint32_t npu_offset; /* npu offset in NPU HW data format*/
1667 uint32_t src_offset;
1668 uint32_t dst_offset;
1669 uint32_t slice_size;
1671 /* @todo we currently support only NHWC */
1672 if (info->layout != DATA_LAYOUT_NHWC) {
1673 logerr (TAG, "data manipulation is supported for NHWC only\n");
1677 for (n = 0; n < batch; n++) {
1678 for (h = 0; h < height; h++) {
1679 for (w = 0; w < width; w++) {
1680 for (d = 0; d < depth; d += MPA_L) {
1681 std_offset = d + depth * (w + width * (h + n * height));
1682 npu_offset = MPA_L * (w + width * (h + (n + d / MPA_L) * height));
1683 slice_size = (depth - d >= MPA_L) ? MPA_L : depth - d;
1686 src_offset = std_offset * data_size;
1687 dst_offset = npu_offset;
1689 src_offset = npu_offset;
1690 dst_offset = std_offset * data_size;
1693 /* if depth is not a multiple of MPA_L, add zero paddings (not exact values) */
1694 if (need_quantization) {
1695 memcpy_with_quant (is_input, info->type, scale, zero_point,
1696 static_cast<char*>(dst) + dst_offset,
1697 static_cast<char*>(src) + src_offset,
1701 static_cast<char*>(dst) + dst_offset,
1702 static_cast<char*>(src) + src_offset,
1709 } else if (need_quantization) {
1710 /** depth == 3 || depth == 64; special cases which can directly copy input tensor data */
1711 memcpy_with_quant (is_input, info->type, scale, zero_point,
1712 dst, src, is_input ? size / data_size : size);
1714 memcpy (dst, src, size);
1723 TrinityVision::manipulateData (const Model *model, uint32_t idx, bool is_input,
1724 void *dst, void *src, size_t size)
1726 memcpy (dst, src, size);
1732 /** other device types don't have data manip impl. yet */
1735 TrinityVision2::manipulateData (const Model *model, uint32_t idx, bool is_input,
1736 void *dst, void *src, size_t size)
1738 memcpy (dst, src, size);
1743 TrinityAsr::manipulateData (const Model *model, uint32_t idx, bool is_input,
1744 void *dst, void *src, size_t size)
1746 memcpy (dst, src, size);