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 <npubinfmt.h>
16 #include <NPUdrvAPI.h>
17 #include <CommPlugin.h>
21 #include "ne-scheduler.h"
22 #include "ne-handler.h"
27 #include <condition_variable>
34 #define INIT_HOST_HANDLER(handler, dev) \
35 Device *tdev = static_cast <Device *> (dev); \
36 if (tdev == nullptr) return -EINVAL; \
37 HostHandler *handler = tdev->getHostHandler (); \
38 if (handler == nullptr) return -EINVAL;
40 /** @brief device class. it contains all related instances */
43 /** @brief Factory method to create a trinity device dependong on dev type */
44 static Device *createInstance (dev_type device_type, int device_id);
46 /** @brief constructor of device */
47 Device (dev_type type, int id, bool need_model = true)
48 : comm_(CommPlugin::getCommPlugin()), type_ (type), id_ (id),
49 need_model_ (true), mode_ (NPUASYNC_WAIT), initialized_ (ATOMIC_FLAG_INIT) {}
51 /** @brief destructor of device */
54 /** @brief initialization */
56 if (!initialized_.test_and_set()) {
57 /** create the corresponding driver API */
58 api_ = DriverAPI::createDriverAPI (type_, id_);
59 if (api_.get() == nullptr) {
61 logerr (TAG, "Failed to create driver API\n");
65 handler_.reset (new HostHandler (this));
66 scheduler_.reset (new Scheduler (api_.get()));
67 mem_ = MemAllocator::createInstance (api_.get());
73 HostHandler *getHostHandler () { return handler_.get(); }
74 dev_type getType () { return type_; }
75 int getID () { return id_; }
76 bool needModel () { return need_model_; }
77 void setAsyncMode (npu_async_mode mode) { mode_ = mode; }
79 HWmem * allocMemory () { return mem_->allocMemory (); }
80 void deallocMemory (int dmabuf_fd) { mem_->deallocMemory (dmabuf_fd); }
82 /** it stops all requests in this device (choose wait or force) */
83 int stop (bool force_stop) {
84 Request *req = new Request (NPUINPUT_STOP);
85 req->setForceStop (force_stop);
86 return scheduler_->submitRequest (req);
89 virtual Model * registerModel (const generic_buffer *model) = 0;
90 virtual int run (npu_input_opmode opmode, const Model *model,
91 const input_buffers *input, npuOutputNotify cb, void *cb_data,
92 uint64_t *sequence) = 0;
95 /** the device instance has ownership of all related components */
96 std::unique_ptr<DriverAPI> api_; /**< device api */
97 std::unique_ptr<MemAllocator> mem_; /**< memory allocator */
98 std::unique_ptr<HostHandler> handler_; /**< host handler */
99 std::unique_ptr<Scheduler> scheduler_; /**< scheduler */
101 CommPlugin& comm_; /**< plugin communicator */
103 dev_type type_; /**< device type */
104 int id_; /**< device id */
105 bool need_model_; /**< indicates whether the device needs model */
106 npu_async_mode mode_; /**< async run mode */
109 std::atomic_flag initialized_;
112 /** @brief Trinity Vision (TRIV) classs */
113 class TrinityVision : public Device {
115 TrinityVision (int id) : Device (NPUCOND_TRIV_CONN_SOCIP, id) {}
118 static size_t manipulateData (const Model *model, uint32_t idx, bool is_input,
119 void *dst, void *src, size_t size);
121 Model * registerModel (const generic_buffer *model_buf) {
122 Model *model = mem_->allocModel ();
123 if (model == nullptr) {
124 logerr (TAG, "Failed to allocate model\n");
129 if (model_buf->type == BUFFER_DMABUF) {
130 model->setDmabuf (model_buf->dmabuf);
131 model->setOffset (model_buf->offset);
132 model->setSize (model_buf->size);
134 status = model->alloc (model_buf->size);
136 logerr (TAG, "Failed to allocate model: %d\n", status);
140 status = comm_.extractGenericBuffer (model_buf, model->getData(), nullptr);
142 logerr (TAG, "Failed to extract generic buffer: %d\n", status);
147 status = model->setMetadata (model->getData());
151 model_config_t config;
152 config.dmabuf_id = model->getDmabuf();
153 config.program_size = model->getMetadata()->getProgramSize();
154 config.program_offset_addr = model->getOffset() + model->getMetadata()->getMetaSize();
155 config.weight_offset_addr = config.program_offset_addr + config.program_size;
157 status = api_->setModel (&config);
168 Buffer * prepareInputBuffers (const Model *model, const input_buffers *input) {
169 const Metadata *meta = model->getMetadata();
170 const generic_buffer *first = &input->bufs[0];
172 if (meta->getInputNum() != input->num_buffers)
175 Buffer * buffer = mem_->allocBuffer ();
176 if (buffer != nullptr) {
177 if (first->type == BUFFER_DMABUF) {
178 buffer->setDmabuf (first->dmabuf);
179 buffer->setOffset (first->offset);
180 buffer->setSize (meta->getBufferSize());
182 int status = buffer->alloc (meta->getBufferSize ());
184 logerr (TAG, "Failed to allocate buffer: %d\n", status);
191 buffer->createTensors (meta);
195 int run (npu_input_opmode opmode, const Model *model,
196 const input_buffers *input, npuOutputNotify cb, void *cb_data,
197 uint64_t *sequence) {
198 if (opmode != NPUINPUT_HOST)
201 Buffer *buffer = prepareInputBuffers (model, input);
202 if (buffer == nullptr)
205 for (uint32_t idx = 0; idx < input->num_buffers; idx++) {
206 auto func = std::bind (TrinityVision::manipulateData, model, idx, true,
207 std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
208 int status = comm_.extractGenericBuffer (&input->bufs[idx],
209 buffer->getInputTensor(idx)->getData(), func);
211 logerr (TAG, "Failed to feed input buffer: %d\n", status);
216 /** this device uses CMA buffer */
218 Request *req = new Request (opmode);
219 req->setModel (model);
220 req->setBuffer (buffer);
221 req->setCallback (std::bind (&TrinityVision::callback, this, req, cb, cb_data));
224 *sequence = req->getID();
226 return scheduler_->submitRequest (req);
229 void callback (Request *req, npuOutputNotify cb, void *cb_data) {
230 const Model *model = req->getModel ();
231 Buffer *buffer = req->getBuffer ();
232 output_buffers output = {
233 .num_buffers = buffer->getOutputNum ()
236 for (uint32_t idx = 0; idx < output.num_buffers; idx++) {
237 uint32_t output_tensor_size = model->getOutputTensorSize (idx);
239 output.bufs[idx].type = BUFFER_MAPPED;
240 output.bufs[idx].size = output_tensor_size;
241 /** user needs to free this */
242 output.bufs[idx].addr = malloc (output_tensor_size);
244 auto func = std::bind (TrinityVision::manipulateData, model, idx, false,
245 std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
246 int status = comm_.insertGenericBuffer (buffer->getOutputTensor(idx)->getData(),
247 &output.bufs[idx], func);
249 logerr (TAG, "Failed to return output buffer: %d\n", status);
253 cb (&output, req->getID(), cb_data);
257 /** @brief Trinity Vision2 (TRIV2) classs */
258 class TrinityVision2 : public Device {
260 TrinityVision2 (int id) : Device (NPUCOND_TRIV2_CONN_SOCIP, id) {}
261 ~TrinityVision2 () {}
263 static size_t manipulateData (const Model *model, uint32_t idx, bool is_input,
264 void *dst, void *src, size_t size) {
265 memcpy (dst, src, size);
269 Model * registerModel (const generic_buffer *model_buf) {
270 /** TODO: model's weight values are stored in segments */
274 int run (npu_input_opmode opmode, const Model *model,
275 const input_buffers *input, npuOutputNotify cb, void *cb_data,
276 uint64_t *sequence) {
277 if (opmode != NPUINPUT_HOST && opmode != NPUINPUT_HW_RECURRING)
280 /** this device uses segment table */
282 Request *req = new Request (opmode);
283 req->setModel (model);
285 req->setSegmentTable (segt);
287 req->setCallback (std::bind (&TrinityVision2::callback, this, req, cb, cb_data));
290 *sequence = req->getID();
292 return scheduler_->submitRequest (req);
295 void callback (Request *req, npuOutputNotify cb, void *cb_data) {
299 /** @brief Trinity Asr (TRIA) classs */
300 class TrinityAsr : public Device {
302 TrinityAsr (int id) : Device (NPUCOND_TRIA_CONN_SOCIP, id, false) {}
305 static size_t manipulateData (const Model *model, uint32_t idx, bool is_input,
306 void *dst, void *src, size_t size) {
307 memcpy (dst, src, size);
311 Model * registerModel (const generic_buffer *model_buf) { return nullptr; }
313 int run (npu_input_opmode opmode, const Model *model,
314 const input_buffers *input, npuOutputNotify cb, void *cb_data,
315 uint64_t *sequence) {
316 if (opmode != NPUINPUT_HOST)
319 /** ASR does not require model and support only a single tensor */
320 const generic_buffer *first_buf = &input->bufs[0];
321 Buffer * buffer = mem_->allocBuffer ();
323 if (first_buf->type == BUFFER_DMABUF) {
324 buffer->setDmabuf (first_buf->dmabuf);
325 buffer->setOffset (first_buf->offset);
326 buffer->setSize (first_buf->size);
328 status = buffer->alloc (first_buf->size);
334 buffer->createTensors ();
336 status = comm_.extractGenericBuffer (first_buf,
337 buffer->getInputTensor(0)->getData(), nullptr);
341 Request *req = new Request (opmode);
342 req->setBuffer (buffer);
343 req->setCallback (std::bind (&TrinityAsr::callback, this, req, cb, cb_data));
346 *sequence = req->getID();
348 return scheduler_->submitRequest (req);
351 void callback (Request *req, npuOutputNotify cb, void *cb_data) {
357 #define do_quantized_memcpy(type) do {\
360 while (idx < num_elems) {\
361 val = ((type *) src)[idx];\
364 val = (val > 255.0) ? 255.0 : 0.0;\
365 ((uint8_t *) dst)[idx++] = (uint8_t) val;\
368 while (idx < num_elems) {\
369 val = *(uint8_t *) src;\
372 ((type *) dst)[idx++] = (type) val;\
373 dst = (void*)(((uint8_t *) dst) + data_size);\
374 src = (void*)(((uint8_t *) src) + 1);\
380 * @brief memcpy during quantization
382 static void memcpy_with_quant (bool quant, data_type type, float scale, uint32_t zero_point,
383 void *dst, const void *src, uint32_t num_elems)
385 double _scale = (double) scale;
386 double _zero_point = (double) zero_point;
388 uint32_t data_size = get_data_size (type);
393 do_quantized_memcpy (int8_t);
395 case DATA_TYPE_UINT8:
396 do_quantized_memcpy (uint8_t);
398 case DATA_TYPE_INT16:
399 do_quantized_memcpy (int16_t);
401 case DATA_TYPE_UINT16:
402 do_quantized_memcpy (uint16_t);
404 case DATA_TYPE_INT32:
405 do_quantized_memcpy (int32_t);
407 case DATA_TYPE_UINT32:
408 do_quantized_memcpy (uint32_t);
410 case DATA_TYPE_INT64:
411 do_quantized_memcpy (int64_t);
413 case DATA_TYPE_UINT64:
414 do_quantized_memcpy (uint64_t);
416 case DATA_TYPE_FLOAT32:
417 do_quantized_memcpy (float);
419 case DATA_TYPE_FLOAT64:
420 do_quantized_memcpy (double);
423 logerr (TAG, "Unsupported datatype %d\n", type);
428 * @brief perform data manipulation
429 * @param[in] model model instance
430 * @param[in] idx tensor index
431 * @param[in] is_input indicate it's input manipulation
432 * @param[out] dst destination buffer
433 * @param[in] src source buffer (feature map)
434 * @param[in] size size to be copied
435 * @return size of memory copy if no error, otherwise zero
437 * @note the input data format should be NHWC
438 * @detail rules for the memory address of activations in NPU HW.
439 * (https://code.sec.samsung.net/confluence/pages/viewpage.action?pageId=146491864)
441 * 1) Special case (depth == 3)
442 * - addr(x,y,z) = addr(0,0,0) + (z) + 3 * (x + width * y)
445 * - addr(x,y,z) = addr(0,0,0) + (z % MPA_L) + MPA_L * (x + width * (y + height * (z / MPA_L)))
447 * Thus, if depth is not a multiple of MPA_L (i.e., 64), zero padding is required
450 TrinityVision::manipulateData (const Model *model, uint32_t idx, bool is_input,
451 void *dst, void *src, size_t size)
453 const Metadata *meta = model->getMetadata();
454 const tensor_data_info* info;
455 const uint32_t *dims;
459 /** extract required information from the metadata */
461 if (idx >= meta->getInputNum()) {
462 logerr (TAG, "Wrong information for input tensors in metadata\n");
466 info = model->getInputDataInfo (idx);
467 dims = meta->getInputDims (idx);
468 zero_point = meta->getInputQuantZero (idx);
469 scale = meta->getInputQuantScale (idx);
471 if (idx >= meta->getOutputNum()) {
472 logerr (TAG, "Wrong information for output tensors in metadata\n");
476 info = model->getOutputDataInfo (idx);
477 dims = meta->getOutputDims (idx);
478 zero_point = meta->getOutputQuantZero (idx);
479 scale = meta->getOutputQuantScale (idx);
482 if (info == nullptr) {
483 logerr (TAG, "Unmatched tensors info\n");
487 uint32_t batch = dims[0];
488 uint32_t height = dims[1];
489 uint32_t width = dims[2];
490 uint32_t depth = dims[3];
492 uint32_t data_size = get_data_size (info->type);
493 if (data_size == 0) {
494 logerr (TAG, "Invalid data size\n");
498 bool need_quantization = false;
500 * note that we assume DATA_TYPE_SRNPU is the smallest data type that we consider.
501 * Also, DATA_TYPE_SRNPU and uint8_t may be regarded as the same in the view of apps.
503 if (info->type != DATA_TYPE_SRNPU) {
504 assert (data_size >= get_data_size (DATA_TYPE_SRNPU));
506 if (data_size > get_data_size (DATA_TYPE_SRNPU) ||
507 !(zero_point == DEFAULT_ZERO_POINT && scale == DEFAULT_SCALE))
508 need_quantization = true;
511 /** check data manipulation is required */
512 if (depth != 3 && depth != 64 && info->layout != DATA_LAYOUT_SRNPU) {
513 uint32_t MPA_L = DATA_GRANULARITY;
515 uint32_t std_offset; /* standard offset in NHWC data format */
516 uint32_t npu_offset; /* npu offset in NPU HW data format*/
521 /* @todo we currently support only NHWC */
522 if (info->layout != DATA_LAYOUT_NHWC) {
523 logerr (TAG, "data manipulation is supported for NHWC only\n");
527 for (n = 0; n < batch; n++) {
528 for (h = 0; h < height; h++) {
529 for (w = 0; w < width; w++) {
530 for (d = 0; d < depth; d += MPA_L) {
531 std_offset = d + depth * (w + width * (h + n * height));
532 npu_offset = MPA_L * (w + width * (h + (n + d / MPA_L) * height));
533 slice_size = (depth - d >= MPA_L) ? MPA_L : depth - d;
536 src_offset = std_offset * data_size;
537 dst_offset = npu_offset;
539 src_offset = npu_offset;
540 dst_offset = std_offset * data_size;
543 /* if depth is not a multiple of MPA_L, add zero paddings (not exact values) */
544 if (need_quantization) {
545 memcpy_with_quant (is_input, info->type, scale, zero_point,
546 static_cast<char*>(dst) + dst_offset,
547 static_cast<char*>(src) + src_offset,
551 static_cast<char*>(dst) + dst_offset,
552 static_cast<char*>(src) + src_offset,
559 } else if (need_quantization) {
560 /** depth == 3 || depth == 64; special cases which can directly copy input tensor data */
562 size = size / data_size;
564 memcpy_with_quant (is_input, info->type, scale, zero_point,
567 memcpy (dst, src, size);
576 TrinityVision::manipulateData (const Model *model, uint32_t idx, bool is_input,
577 void *dst, void *src, size_t size)
579 memcpy (dst, src, size);
586 * @brief create device instance depending on device type and id
587 * @param[in] type device type
588 * @param[in] id device id
589 * @return device instance
592 Device::createInstance (dev_type type, int id)
594 Device *device = nullptr;
596 switch (type & DEVICETYPE_MASK) {
597 case DEVICETYPE_TRIV:
598 device = new TrinityVision (id);
600 case DEVICETYPE_TRIV2:
601 device = new TrinityVision2 (id);
603 case DEVICETYPE_TRIA:
604 device = new TrinityAsr (id);
610 if (device != nullptr && device->init () != 0) {
618 /** @brief host handler constructor */
619 HostHandler::HostHandler (Device *device)
624 /** @brief host handler destructor */
625 HostHandler::~HostHandler ()
630 * @brief register model from generic buffer
631 * @param[in] model_buf model buffer
632 * @param[out] modelid model id
633 * @return 0 if no error. otherwise a negative errno
636 HostHandler::registerModel (generic_buffer *model_buf, uint32_t *modelid)
638 Model *model = device_->registerModel (model_buf);
639 if (model == nullptr) {
640 logerr (TAG, "Failed to register model\n");
644 int status = models_.insert (model->getID(), model);
646 logerr (TAG, "Failed to insert model id\n");
651 *modelid = model->getID();
656 * @brief remove the registered model
657 * @param[in] modelid model id
658 * @return 0 if no error. otherwise a negative errno
661 HostHandler::unregisterModel (uint32_t modelid)
663 return models_.remove (modelid);
667 * @brief remove all registered models
671 HostHandler::unregisterModels ()
678 * @brief Set the data layout for input/output tensors
679 * @param[in] modelid The ID of model whose layouts are set
680 * @param[in] in the layout/type info for input tensors
681 * @param[in] out the layout/type info for output tensors
682 * @return @c 0 if no error. otherwise a negative error value
683 * @note if this function is not called, default layout/type will be used.
686 HostHandler::setDataInfo (uint32_t modelid, tensors_data_info *in,
687 tensors_data_info *out)
689 Model *model = models_.find (modelid);
690 if (model == nullptr)
693 model->setDataInfo (in, out);
699 * @brief Set the inference constraint for next NPU inferences
700 * @param[in] modelid The target model id
701 * @param[in] constraint inference constraint (e.g., timeout, priority)
702 * @return @c 0 if no error. otherwise a negative error value
703 * @note If this function is not called, default values are used.
706 HostHandler::setConstraint (uint32_t modelid, npuConstraint constraint)
708 Model *model = models_.find (modelid);
709 if (model == nullptr)
712 model->setConstraint (constraint);
718 * @brief find and return model instance
719 * @param[in] modelid model id
720 * @return model instance if found. otherwise nullptr
723 HostHandler::getModel (uint32_t modelid)
725 return models_.find (modelid);
728 /** @brief dummay callback for runSync. */
731 callbackSync (output_buffers *output) : output_(output), done_(false) {}
733 static void callback (output_buffers *output, uint64_t sequence, void *data) {
734 callbackSync *sync = static_cast<callbackSync *>(data);
735 sync->callback (output, sequence);
738 void callback (output_buffers *output, uint64_t sequence) {
739 /** just copy internal variables of output buffers */
740 memcpy (output_, output, sizeof (output_buffers));
746 std::unique_lock<std::mutex> lock (m_);
747 cv_.wait (lock, [this]() { return done_; });
752 std::condition_variable cv_;
753 output_buffers *output_;
758 * @brief Execute inference. Wait (block) until the output is available.
759 * @param[in] modelid The model to be inferred.
760 * @param[in] input The input data to be inferred.
761 * @param[out] output The output result.
762 * @return @c 0 if no error. otherwise a negative error value
765 HostHandler::runSync (uint32_t modelid, const input_buffers *input,
766 output_buffers *output)
768 callbackSync sync (output);
769 int status = runAsync (modelid, input, callbackSync::callback,
770 static_cast <void*> (&sync), NPUASYNC_DROP_OLD, nullptr);
772 /** sync needs to wait callback */
779 * @brief Invoke NPU inference. Unblocking call.
780 * @param[in] modelid The model to be inferred.
781 * @param[in] input The input data to be inferred.
782 * @param[in] cb The output buffer handler.
783 * @param[in] cb_data The data given as a parameter to the runNPU_async call.
784 * @param[in] mode Configures how this operation works.
785 * @param[out] sequence The sequence number returned with runNPU_async.
786 * @return @c 0 if no error. otherwise a negative error value
789 HostHandler::runAsync (uint32_t modelid, const input_buffers *input,
790 npuOutputNotify cb, void *cb_data, npu_async_mode mode, uint64_t *sequence)
792 Model *model = nullptr;
794 if (device_->needModel()) {
795 model = getModel (modelid);
796 if (model == nullptr)
800 device_->setAsyncMode (mode);
801 return device_->run (NPUINPUT_HOST, model, input, cb, cb_data, sequence);
805 * @brief get number of available devices
806 * @param[in] type device type
807 * @return number of devices
810 HostHandler::getNumDevices (dev_type type)
812 return DriverAPI::getNumDevices (type);
816 * @brief get device instance
817 * @param[out] dev device instance
818 * @param[in] type device type
819 * @param[in] id device id
820 * @return 0 if no error. otherwise a negative errno
823 HostHandler::getDevice (npudev_h *dev, dev_type type, uint32_t id)
825 int num_devices = getNumDevices (type);
827 /** check the validity of device id */
828 if (!(num_devices > 0 && id < static_cast<uint32_t>(num_devices))) {
829 logerr (TAG, "Invalid arguments provided\n");
833 Device *device = Device::createInstance (type, id);
834 if (device == nullptr) {
835 logerr (TAG, "Failed to create a device with the given type\n");
840 /** This is just for backward-compatility; we don't guarantee its corresness */
847 * @brief allocate generic buffer (just for users)
848 * @param[out] buffer buffer instance
849 * @return 0 if no error. otherwise a negative errno
852 HostHandler::allocGenericBuffer (generic_buffer *buffer)
857 if (buffer->size > UINT32_MAX) {
858 logerr (TAG, "Don't support such a large size");
862 if (buffer->type == BUFFER_FILE) {
864 if (buffer->filepath == nullptr)
867 /* now, npu-engine always provides dmabuf-based allocation */
868 HWmem *hwmem = device_->allocMemory ();
869 if (hwmem == nullptr || hwmem->alloc (buffer->size) < 0)
872 buffer->dmabuf = hwmem->getDmabuf();
873 buffer->offset = hwmem->getOffset();
874 buffer->addr = hwmem->getData();
880 * @brief deallocate generic buffer (just for users)
881 * @param[in] buffer buffer instance
882 * @return 0 if no error. otherwise a negative errno
885 HostHandler::deallocGenericBuffer (generic_buffer *buffer)
890 if (buffer->type != BUFFER_FILE)
891 device_->deallocMemory (buffer->dmabuf);
897 * @brief allocate multiple generic buffers (just for users)
898 * @param[out] buffers multi-buffer instance
899 * @return 0 if no error. otherwise a negative errno
902 HostHandler::allocGenericBuffer (generic_buffers *buffers)
904 if (buffers == NULL || buffers->num_buffers < 1)
907 buffer_types type = buffers->bufs[0].type;
908 if (type == BUFFER_FILE)
911 uint64_t total_size = 0;
912 for (uint32_t idx = 0; idx < buffers->num_buffers; idx++)
913 total_size += buffers->bufs[idx].size;
915 uint64_t first_size = buffers->bufs[0].size;
916 buffers->bufs[0].size = total_size;
917 int status = allocGenericBuffer (&buffers->bufs[0]);
921 uint64_t offset = first_size;
922 for (uint32_t idx = 1; idx < buffers->num_buffers; idx++) {
923 buffers->bufs[idx].dmabuf = buffers->bufs[0].dmabuf;
924 buffers->bufs[idx].offset = buffers->bufs[0].offset + offset;
925 buffers->bufs[idx].type = type;
927 offset += buffers->bufs[idx].size;
934 * @brief deallocate multiple generic buffers (just for users)
935 * @param[in] buffers multi-buffer instance
936 * @return 0 if no error. otherwise a negative errno
939 HostHandler::deallocGenericBuffer (generic_buffers *buffers)
941 if (buffers == NULL || buffers->num_buffers < 1)
944 return deallocGenericBuffer (&buffers->bufs[0]);
947 /** just for backward-compatability */
948 npudev_h HostHandler::latest_dev_ = nullptr;
950 /** implementation of libnpuhost APIs */
953 * @brief Returns the number of available NPU devices.
954 * @return @c The number of NPU devices.
955 * @retval 0 if no NPU devices available. if positive (number of NPUs) if NPU devices available. otherwise, a negative error value.
956 * @note the caller should call putNPUdevice() to release the device handle
958 int getnumNPUdeviceByType (dev_type type)
960 return HostHandler::getNumDevices (type);
964 * @brief Returns the handle of the chosen NPU devices.
965 * @param[out] dev The NPU device handle
966 * @param[in] id The NPU id to get the handle. 0 <= id < getnumNPUdeviceByType().
967 * @return @c 0 if no error. otherwise a negative error value
968 * @note the caller should call putNPUdevice() to release the device handle
970 int getNPUdeviceByType (npudev_h *dev, dev_type type, uint32_t id)
972 return HostHandler::getDevice (dev, type, id);
976 * @brief Returns the handle of an NPU device meeting the condition
977 * @param[out] dev The NPU device handle
978 * @param[in] cond The condition for device search.
979 * @return @c 0 if no error. otherwise a negative error value
980 * @note the caller should call putNPUdevice() to release the device handle
981 * @note it's not supported yet
983 int getNPUdeviceByCondition(npudev_h *dev, const npucondition *cond)
985 /** not implmeneted yet */
986 return getNPUdeviceByType (dev, NPUCOND_TRIV_CONN_SOCIP, 0);
990 * @brief release the NPU device instance obtained by getDevice ()
991 * @param[in] dev the NPU device handle
993 void putNPUdevice (npudev_h dev)
996 delete static_cast<Device *> (dev);
1000 * @brief Send the NN model to NPU.
1001 * @param[in] dev The NPU device handle
1002 * @param[in] modelfile The filepath to the compiled NPU NN model in any buffer_type
1003 * @param[out] modelid The modelid allocated for this instance of NN model.
1004 * @return @c 0 if no error. otherwise a negative error value
1006 * @detail For ASR devices, which do not accept models, but have models
1007 * embedded in devices, you do not need to call register and
1008 * register calls for ASR are ignored.
1010 * @todo Add a variation: in-memory model register.
1012 int registerNPUmodel (npudev_h dev, generic_buffer *modelfile, uint32_t *modelid)
1014 INIT_HOST_HANDLER (host_handler, dev);
1016 return host_handler->registerModel (modelfile, modelid);
1020 * @brief Remove the NN model from NPU
1021 * @param[in] dev The NPU device handle
1022 * @param[in] modelid The model to be removed from the NPU.
1023 * @return @c 0 if no error. otherwise a negative error value
1024 * @detail This may incur some latency with memory compatcion.
1026 int unregisterNPUmodel(npudev_h dev, uint32_t modelid)
1028 INIT_HOST_HANDLER (host_handler, dev);
1030 return host_handler->unregisterModel (modelid);
1034 * @brief Remove all NN models from NPU
1035 * @param[in] dev The NPU device handle
1036 * @return @c 0 if no error. otherwise a negative error value
1038 int unregisterNPUmodel_all(npudev_h dev)
1040 INIT_HOST_HANDLER (host_handler, dev);
1042 return host_handler->unregisterModels ();
1046 * @brief [OPTIONAL] Set the data layout for input/output tensors
1047 * @param[in] dev The NPU device handle
1048 * @param[in] modelid The ID of model whose layouts are set
1049 * @param[in] info_in the layout/type info for input tensors
1050 * @param[in] info_out the layout/type info for output tensors
1051 * @return @c 0 if no error. otherwise a negative error value
1052 * @note if this function is not called, default layout/type will be used.
1054 int setNPU_dataInfo(npudev_h dev, uint32_t modelid,
1055 tensors_data_info *info_in, tensors_data_info *info_out)
1057 INIT_HOST_HANDLER (host_handler, dev);
1059 return host_handler->setDataInfo (modelid, info_in, info_out);
1063 * @brief [OPTIONAL] Set the inference constraint for next NPU inferences
1064 * @param[in] dev The NPU device handle
1065 * @param[in] modelid The target model id
1066 * @param[in] constraint inference constraint (e.g., timeout, priority)
1067 * @return @c 0 if no error. otherwise a negative error value
1068 * @note If this function is not called, default values are used.
1070 int setNPU_constraint(npudev_h dev, uint32_t modelid, npuConstraint constraint)
1072 INIT_HOST_HANDLER (host_handler, dev);
1074 return host_handler->setConstraint (modelid, constraint);
1078 * @brief Execute inference. Wait (block) until the output is available.
1079 * @param[in] dev The NPU device handle
1080 * @param[in] modelid The model to be inferred.
1081 * @param[in] input The input data to be inferred.
1082 * @param[out] output The output result. The caller MUST allocate appropriately before calling this.
1083 * @return @c 0 if no error. otherwise a negative error value
1085 * @detail This is a syntactic sugar of runNPU_async().
1086 * CAUTION: There is a memcpy for the output buffer.
1088 int runNPU_sync(npudev_h dev, uint32_t modelid, const input_buffers *input,
1089 output_buffers *output)
1091 INIT_HOST_HANDLER (host_handler, dev);
1093 return host_handler->runSync (modelid, input, output);
1097 * @brief Invoke NPU inference. Unblocking call.
1098 * @param[in] dev The NPU device handle
1099 * @param[in] modelid The model to be inferred.
1100 * @param[in] input The input data to be inferred.
1101 * @param[in] cb The output buffer handler.
1102 * @param[out] sequence The sequence number returned with runNPU_async.
1103 * @param[in] data The data given as a parameter to the runNPU_async call.
1104 * @param[in] mode Configures how this operation works.
1105 * @return @c 0 if no error. otherwise a negative error value
1107 int runNPU_async(npudev_h dev, uint32_t modelid, const input_buffers *input,
1108 npuOutputNotify cb, uint64_t *sequence, void *data,
1109 npu_async_mode mode)
1111 INIT_HOST_HANDLER (host_handler, dev);
1113 return host_handler->runAsync (modelid, input, cb, data, mode, sequence);
1117 * @brief Allocate a buffer for NPU model with the requested buffer type.
1118 * @param[in] dev The NPU device handle
1119 * @param[in/out] Buffer the buffer pointer where memory is allocated.
1120 * @return 0 if no error, otherwise a negative errno.
1122 int allocNPU_modelBuffer (npudev_h dev, generic_buffer *buffer)
1124 INIT_HOST_HANDLER (host_handler, dev);
1126 return host_handler->allocGenericBuffer (buffer);
1130 * @brief Free the buffer and remove the address mapping.
1131 * @param[in] dev The NPU device handle
1132 * @param[in] buffer the model buffer
1133 * @return 0 if no error, otherwise a negative errno.
1135 int cleanNPU_modelBuffer (npudev_h dev, generic_buffer *buffer)
1137 INIT_HOST_HANDLER (host_handler, dev);
1139 return host_handler->deallocGenericBuffer (buffer);
1143 * @brief Allocate a buffer for NPU input with the requested buffer type.
1144 * @param[in] dev The NPU device handle
1145 * @param[in/out] Buffer the buffer pointer where memory is allocated.
1146 * @return 0 if no error, otherwise a negative errno.
1147 * @note please utilize allocInputBuffers() for multiple input tensors because subsequent
1148 * calls of allocInputBuffer() don't gurantee contiguous allocations between them.
1150 int allocNPU_inputBuffer (npudev_h dev, generic_buffer *buffer)
1152 INIT_HOST_HANDLER (host_handler, dev);
1154 return host_handler->allocGenericBuffer (buffer);
1158 * @brief Free the buffer and remove the address mapping.
1159 * @param[in] dev The NPU device handle
1160 * @param[in] buffer the input buffer
1161 * @return 0 if no error, otherwise a negative errno.
1163 int cleanNPU_inputBuffer (npudev_h dev, generic_buffer *buffer)
1165 INIT_HOST_HANDLER (host_handler, dev);
1167 return host_handler->deallocGenericBuffer (buffer);
1171 * @brief Allocate input buffers, which have multiple instances of generic_buffer
1172 * @param[in] dev The NPU device handle
1173 * @param[in/out] input input buffers.
1174 * @return 0 if no error, otherwise a negative errno.
1175 * @note it reuses allocInputBuffer().
1176 * @details in case of BUFFER_DMABUF, this function can be used to gurantee physically-contiguous
1177 * memory mapping for multiple tensors (in a single inference, not batch size).
1179 int allocNPU_inputBuffers (npudev_h dev, input_buffers * input)
1181 INIT_HOST_HANDLER (host_handler, dev);
1183 return host_handler->allocGenericBuffer (input);
1187 * @brief Free input buffers allocated by allocInputBuffers().
1188 * @param[in] dev The NPU device handle
1189 * @param[in/out] input input buffers.
1190 * @note it reuses cleanInputbuffer().
1191 * @return 0 if no error, otherwise a negative errno.
1193 int cleanNPU_inputBuffers (npudev_h dev, input_buffers * input)
1195 INIT_HOST_HANDLER (host_handler, dev);
1197 return host_handler->deallocGenericBuffer (input);
1201 * @brief Get metadata for NPU model
1202 * @param[in] model The path of model binary file
1203 * @param[in] need_extra whether you want to extract the extra data in metadata
1204 * @return the metadata structure to be filled if no error, otherwise nullptr
1206 * @note For most npu-engine users, the extra data is not useful because it will be
1207 * used for second-party users (e.g., compiler, simulator).
1208 * Also, the caller needs to free the metadata.
1210 * @note the caller needs to free the metadata
1212 npubin_meta * getNPUmodel_metadata (const char *model, bool need_extra)
1221 fp = fopen (model, "rb");
1223 logerr (TAG, "Failed to open the model binary: %d\n", -errno);
1227 meta = (npubin_meta *) malloc (NPUBIN_META_SIZE);
1229 logerr (TAG, "Failed to allocate metadata\n");
1233 ret = fread (meta, 1, NPUBIN_META_SIZE, fp);
1234 if (ret != NPUBIN_META_SIZE) {
1235 logerr (TAG, "Failed to read the metadata\n");
1239 if (!CHECK_NPUBIN (meta->magiccode)) {
1240 logerr (TAG, "Invalid metadata provided\n");
1244 if (need_extra && NPUBIN_META_EXTRA (meta->magiccode) > 0) {
1245 npubin_meta *new_meta;
1247 new_meta = (npubin_meta *) realloc (meta, NPUBIN_META_TOTAL_SIZE(meta->magiccode));
1249 logerr (TAG, "Failed to allocate extra metadata\n");
1253 ret = fread (new_meta->reserved_extra, 1, NPUBIN_META_EXTRA_SIZE (meta->magiccode), fp);
1254 if (ret != NPUBIN_META_EXTRA_SIZE (meta->magiccode)) {
1255 logerr (TAG, "Invalid extra metadata provided\n");
1275 /** deprecated buffer APIs; please use the above APIs */
1278 * @brief Returns the number of NPU devices (TRIV).
1280 int getnumNPUdevice (void)
1282 logwarn (TAG, "deprecated. Please use getnumNPUdeviceByType ()\n");
1283 return getnumNPUdeviceByType (NPUCOND_TRIV_CONN_SOCIP);
1287 * @brief Returns the list of ASR devices (TRIA)
1289 int getnumASRdevice (void)
1291 logwarn (TAG, "deprecated. Please use getnumNPUdeviceByType ()\n");
1292 return getnumNPUdeviceByType (NPUCOND_TRIA_CONN_SOCIP);
1296 * @brief Returns the handle of the chosen TRIV device.
1298 int getNPUdevice (npudev_h *dev, uint32_t id)
1300 logwarn (TAG, "deprecated. Please use getNPUdeviceByType ()\n");
1301 return getNPUdeviceByType (dev, NPUCOND_TRIV_CONN_SOCIP, id);
1305 * @brief Returns the handle of the chosen TRIA device.
1307 int getASRdevice (npudev_h *dev, uint32_t id)
1309 logwarn (TAG, "deprecated. Please use getNPUdeviceByType ()\n");
1310 return getNPUdeviceByType (dev, NPUCOND_TRIA_CONN_SOCIP, id);
1313 /** @brief deprecated */
1314 int allocModelBuffer (generic_buffer *buffer)
1316 logwarn (TAG, "deprecated. Please use allocNPU_modelBuffer\n");
1317 return allocNPU_modelBuffer (HostHandler::getLatestDevice(), buffer);
1320 /** @brief deprecated */
1321 int cleanModelBuffer (generic_buffer *buffer)
1323 logwarn (TAG, "deprecated. Please use cleanNPU_modelBuffer\n");
1324 return allocNPU_modelBuffer (HostHandler::getLatestDevice(), buffer);
1327 /** @brief deprecated */
1328 int allocInputBuffer (generic_buffer *buffer)
1330 logwarn (TAG, "deprecated. Please use allocNPU_inputBuffer\n");
1331 return allocNPU_inputBuffer (HostHandler::getLatestDevice(), buffer);
1334 /** @brief deprecated */
1335 int cleanInputBuffer (generic_buffer *buffer)
1337 logwarn (TAG, "deprecated. Please use cleanNPU_inputBuffer\n");
1338 return cleanNPU_inputBuffer (HostHandler::getLatestDevice(), buffer);
1341 /** @brief deprecated */
1342 int allocInputBuffers (input_buffers * input)
1344 logwarn (TAG, "deprecated. Please use allocNPU_inputBuffers\n");
1345 return allocNPU_inputBuffers (HostHandler::getLatestDevice(), input);
1348 /** @brief deprecated */
1349 int cleanInputBuffers (input_buffers * input)
1351 logwarn (TAG, "deprecated. Please use cleanNPU_inputBuffers\n");
1352 return cleanNPU_inputBuffers (HostHandler::getLatestDevice(), input);
1355 /** @brief deprecated */
1356 int allocNPUBuffer (uint64_t size, buffer_types type,
1357 const char * filepath, generic_buffer *buffer)
1360 buffer->size = size;
1361 buffer->type = type;
1362 buffer->filepath = filepath;
1365 logwarn (TAG, "deprecated. Please use allocNPU_* APIs\n");
1366 return allocModelBuffer (buffer);
1369 /** @brief deprecated */
1370 int cleanNPUBuffer (generic_buffer * buffer)
1372 logwarn (TAG, "deprecated. Please use cleanNPU_* APIs\n");
1373 return cleanModelBuffer (buffer);