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) {}
117 static size_t manipulateData (const Model *model, uint32_t idx, bool is_input,
118 void *dst, void *src, size_t size);
120 Model * registerModel (const generic_buffer *model_buf) {
121 Model *model = mem_->allocModel ();
122 if (model == nullptr) {
123 logerr (TAG, "Failed to allocate model\n");
128 if (model_buf->type == BUFFER_DMABUF) {
129 model->setDmabuf (model_buf->dmabuf);
130 model->setOffset (model_buf->offset);
131 model->setSize (model_buf->size);
133 status = model->alloc (model_buf->size);
135 logerr (TAG, "Failed to allocate model: %d\n", status);
139 status = comm_.extractGenericBuffer (model_buf, model->getData(), nullptr);
141 logerr (TAG, "Failed to extract generic buffer: %d\n", status);
146 status = model->setMetadata (model->getData());
150 model_config_t config;
151 config.dmabuf_id = model->getDmabuf();
152 config.program_size = model->getMetadata()->getProgramSize();
153 config.program_offset_addr = model->getOffset() + model->getMetadata()->getMetaSize();
154 config.weight_offset_addr = config.program_offset_addr + config.program_size;
156 status = api_->setModel (&config);
167 Buffer * prepareInputBuffers (const Model *model, const input_buffers *input) {
168 const Metadata *meta = model->getMetadata();
169 const generic_buffer *first = &input->bufs[0];
171 if (meta->getInputNum() != input->num_buffers)
174 Buffer * buffer = mem_->allocBuffer ();
175 if (buffer != nullptr) {
176 if (first->type == BUFFER_DMABUF) {
177 buffer->setDmabuf (first->dmabuf);
178 buffer->setOffset (first->offset);
179 buffer->setSize (meta->getBufferSize());
181 int status = buffer->alloc (meta->getBufferSize ());
183 logerr (TAG, "Failed to allocate buffer: %d\n", status);
190 buffer->createTensors (meta);
194 int run (npu_input_opmode opmode, const Model *model,
195 const input_buffers *input, npuOutputNotify cb, void *cb_data,
196 uint64_t *sequence) {
197 if (opmode != NPUINPUT_HOST)
200 Buffer *buffer = prepareInputBuffers (model, input);
201 if (buffer == nullptr)
204 for (uint32_t idx = 0; idx < input->num_buffers; idx++) {
205 auto func = std::bind (TrinityVision::manipulateData, model, idx, true,
206 std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
207 int status = comm_.extractGenericBuffer (&input->bufs[idx],
208 buffer->getInputTensor(idx)->getData(), func);
210 logerr (TAG, "Failed to feed input buffer: %d\n", status);
215 /** this device uses CMA buffer */
217 Request *req = new Request (opmode);
218 req->setModel (model);
219 req->setBuffer (buffer);
220 req->setCallback (std::bind (&TrinityVision::callback, this, req, cb, cb_data));
223 *sequence = req->getID();
225 return scheduler_->submitRequest (req);
228 void callback (Request *req, npuOutputNotify cb, void *cb_data) {
229 const Model *model = req->getModel ();
230 Buffer *buffer = req->getBuffer ();
231 output_buffers output = {
232 .num_buffers = buffer->getOutputNum ()
235 for (uint32_t idx = 0; idx < output.num_buffers; idx++) {
236 uint32_t output_tensor_size = model->getOutputTensorSize (idx);
238 output.bufs[idx].type = BUFFER_MAPPED;
239 output.bufs[idx].size = output_tensor_size;
240 /** user needs to free this */
241 output.bufs[idx].addr = malloc (output_tensor_size);
243 auto func = std::bind (TrinityVision::manipulateData, model, idx, false,
244 std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
245 int status = comm_.insertGenericBuffer (buffer->getOutputTensor(idx)->getData(),
246 &output.bufs[idx], func);
248 logerr (TAG, "Failed to return output buffer: %d\n", status);
252 cb (&output, req->getID(), cb_data);
256 /** @brief Trinity Vision2 (TRIV2) classs */
257 class TrinityVision2 : public Device {
259 TrinityVision2 (int id) : Device (NPUCOND_TRIV2_CONN_SOCIP, id) {}
261 static size_t manipulateData (const Model *model, uint32_t idx, bool is_input,
262 void *dst, void *src, size_t size) {
263 memcpy (dst, src, size);
267 Model * registerModel (const generic_buffer *model_buf) {
268 /** TODO: model's weight values are stored in segments */
272 int run (npu_input_opmode opmode, const Model *model,
273 const input_buffers *input, npuOutputNotify cb, void *cb_data,
274 uint64_t *sequence) {
275 if (opmode != NPUINPUT_HOST || opmode != NPUINPUT_HW_RECURRING)
278 /** this device uses segment table */
280 Request *req = new Request (opmode);
281 req->setModel (model);
283 req->setSegmentTable (segt);
285 req->setCallback (std::bind (&TrinityVision2::callback, this, req, cb, cb_data));
288 *sequence = req->getID();
290 return scheduler_->submitRequest (req);
293 void callback (Request *req, npuOutputNotify cb, void *cb_data) {
297 /** @brief Trinity Asr (TRIA) classs */
298 class TrinityAsr : public Device {
300 TrinityAsr (int id) : Device (NPUCOND_TRIA_CONN_SOCIP, id, false) {}
302 static size_t manipulateData (const Model *model, uint32_t idx, bool is_input,
303 void *dst, void *src, size_t size) {
304 memcpy (dst, src, size);
308 Model * registerModel (const generic_buffer *model_buf) { return nullptr; }
310 int run (npu_input_opmode opmode, const Model *model,
311 const input_buffers *input, npuOutputNotify cb, void *cb_data,
312 uint64_t *sequence) {
313 if (opmode != NPUINPUT_HOST)
316 /** ASR does not require model and support only a single tensor */
317 const generic_buffer *first_buf = &input->bufs[0];
318 Buffer * buffer = mem_->allocBuffer ();
320 if (first_buf->type == BUFFER_DMABUF) {
321 buffer->setDmabuf (first_buf->dmabuf);
322 buffer->setOffset (first_buf->offset);
323 buffer->setSize (first_buf->size);
325 status = buffer->alloc (first_buf->size);
331 buffer->createTensors ();
333 status = comm_.extractGenericBuffer (first_buf,
334 buffer->getInputTensor(0)->getData(), nullptr);
338 Request *req = new Request (opmode);
339 req->setBuffer (buffer);
340 req->setCallback (std::bind (&TrinityAsr::callback, this, req, cb, cb_data));
343 *sequence = req->getID();
345 return scheduler_->submitRequest (req);
348 void callback (Request *req, npuOutputNotify cb, void *cb_data) {
354 #define do_quantized_memcpy(type) do {\
357 while (idx < num_elems) {\
358 val = ((type *) src)[idx];\
361 val = (val > 255.0) ? 255.0 : 0.0;\
362 ((uint8_t *) dst)[idx++] = (uint8_t) val;\
365 while (idx < num_elems) {\
366 val = *(uint8_t *) src;\
369 ((type *) dst)[idx++] = (type) val;\
370 dst = (void*)(((uint8_t *) dst) + data_size);\
371 src = (void*)(((uint8_t *) src) + 1);\
377 * @brief memcpy during quantization
379 static void memcpy_with_quant (bool quant, data_type type, float scale, uint32_t zero_point,
380 void *dst, const void *src, uint32_t num_elems)
382 double _scale = (double) scale;
383 double _zero_point = (double) zero_point;
385 uint32_t data_size = get_data_size (type);
390 do_quantized_memcpy (int8_t);
392 case DATA_TYPE_UINT8:
393 do_quantized_memcpy (uint8_t);
395 case DATA_TYPE_INT16:
396 do_quantized_memcpy (int16_t);
398 case DATA_TYPE_UINT16:
399 do_quantized_memcpy (uint16_t);
401 case DATA_TYPE_INT32:
402 do_quantized_memcpy (int32_t);
404 case DATA_TYPE_UINT32:
405 do_quantized_memcpy (uint32_t);
407 case DATA_TYPE_INT64:
408 do_quantized_memcpy (int64_t);
410 case DATA_TYPE_UINT64:
411 do_quantized_memcpy (uint64_t);
413 case DATA_TYPE_FLOAT32:
414 do_quantized_memcpy (float);
416 case DATA_TYPE_FLOAT64:
417 do_quantized_memcpy (double);
420 logerr (TAG, "Unsupported datatype %d\n", type);
425 * @brief perform data manipulation
426 * @param[in] model model instance
427 * @param[in] idx tensor index
428 * @param[in] is_input indicate it's input manipulation
429 * @param[out] dst destination buffer
430 * @param[in] src source buffer (feature map)
431 * @param[in] size size to be copied
432 * @return size of memory copy if no error, otherwise zero
434 * @note the input data format should be NHWC
435 * @detail rules for the memory address of activations in NPU HW.
436 * (https://code.sec.samsung.net/confluence/pages/viewpage.action?pageId=146491864)
438 * 1) Special case (depth == 3)
439 * - addr(x,y,z) = addr(0,0,0) + (z) + 3 * (x + width * y)
442 * - addr(x,y,z) = addr(0,0,0) + (z % MPA_L) + MPA_L * (x + width * (y + height * (z / MPA_L)))
444 * Thus, if depth is not a multiple of MPA_L (i.e., 64), zero padding is required
447 TrinityVision::manipulateData (const Model *model, uint32_t idx, bool is_input,
448 void *dst, void *src, size_t size)
450 const Metadata *meta = model->getMetadata();
451 const tensor_data_info* info;
452 const uint32_t *dims;
456 /** extract required information from the metadata */
458 if (idx >= meta->getInputNum()) {
459 logerr (TAG, "Wrong information for input tensors in metadata\n");
463 info = model->getInputDataInfo (idx);
464 dims = meta->getInputDims (idx);
465 zero_point = meta->getInputQuantZero (idx);
466 scale = meta->getInputQuantScale (idx);
468 if (idx >= meta->getOutputNum()) {
469 logerr (TAG, "Wrong information for output tensors in metadata\n");
473 info = model->getOutputDataInfo (idx);
474 dims = meta->getOutputDims (idx);
475 zero_point = meta->getOutputQuantZero (idx);
476 scale = meta->getOutputQuantScale (idx);
479 if (info == nullptr) {
480 logerr (TAG, "Unmatched tensors info\n");
484 uint32_t batch = dims[0];
485 uint32_t height = dims[1];
486 uint32_t width = dims[2];
487 uint32_t depth = dims[3];
489 uint32_t data_size = get_data_size (info->type);
490 if (data_size == 0) {
491 logerr (TAG, "Invalid data size\n");
495 bool need_quantization = false;
497 * note that we assume DATA_TYPE_SRNPU is the smallest data type that we consider.
498 * Also, DATA_TYPE_SRNPU and uint8_t may be regarded as the same in the view of apps.
500 if (info->type != DATA_TYPE_SRNPU) {
501 assert (data_size >= get_data_size (DATA_TYPE_SRNPU));
503 if (data_size > get_data_size (DATA_TYPE_SRNPU) ||
504 !(zero_point == DEFAULT_ZERO_POINT && scale == DEFAULT_SCALE))
505 need_quantization = true;
508 /** check data manipulation is required */
509 if (depth != 3 && depth != 64 && info->layout != DATA_LAYOUT_SRNPU) {
510 uint32_t MPA_L = DATA_GRANULARITY;
512 uint32_t std_offset; /* standard offset in NHWC data format */
513 uint32_t npu_offset; /* npu offset in NPU HW data format*/
518 /* @todo we currently support only NHWC */
519 if (info->layout != DATA_LAYOUT_NHWC) {
520 logerr (TAG, "data manipulation is supported for NHWC only\n");
524 for (n = 0; n < batch; n++) {
525 for (h = 0; h < height; h++) {
526 for (w = 0; w < width; w++) {
527 for (d = 0; d < depth; d += MPA_L) {
528 std_offset = d + depth * (w + width * (h + n * height));
529 npu_offset = MPA_L * (w + width * (h + (n + d / MPA_L) * height));
530 slice_size = (depth - d >= MPA_L) ? MPA_L : depth - d;
533 src_offset = std_offset * data_size;
534 dst_offset = npu_offset;
536 src_offset = npu_offset;
537 dst_offset = std_offset * data_size;
540 /* if depth is not a multiple of MPA_L, add zero paddings (not exact values) */
541 if (need_quantization) {
542 memcpy_with_quant (is_input, info->type, scale, zero_point,
543 static_cast<char*>(dst) + dst_offset,
544 static_cast<char*>(src) + src_offset,
548 static_cast<char*>(dst) + dst_offset,
549 static_cast<char*>(src) + src_offset,
556 } else if (need_quantization) {
557 /** depth == 3 || depth == 64; special cases which can directly copy input tensor data */
559 size = size / data_size;
561 memcpy_with_quant (is_input, info->type, scale, zero_point,
564 memcpy (dst, src, size);
573 TrinityVision::manipulateData (const Model *model, uint32_t idx, bool is_input,
574 void *dst, void *src, size_t size)
576 memcpy (dst, src, size);
583 * @brief create device instance depending on device type and id
584 * @param[in] type device type
585 * @param[in] id device id
586 * @return device instance
589 Device::createInstance (dev_type type, int id)
591 Device *device = nullptr;
593 switch (type & DEVICETYPE_MASK) {
594 case DEVICETYPE_TRIV:
595 device = new TrinityVision (id);
597 case DEVICETYPE_TRIV2:
598 device = new TrinityVision2 (id);
600 case DEVICETYPE_TRIA:
601 device = new TrinityAsr (id);
607 if (device != nullptr && device->init () != 0) {
615 /** @brief host handler constructor */
616 HostHandler::HostHandler (Device *device)
621 /** @brief host handler destructor */
622 HostHandler::~HostHandler ()
627 * @brief register model from generic buffer
628 * @param[in] model_buf model buffer
629 * @param[out] modelid model id
630 * @return 0 if no error. otherwise a negative errno
633 HostHandler::registerModel (generic_buffer *model_buf, uint32_t *modelid)
635 Model *model = device_->registerModel (model_buf);
636 if (model == nullptr) {
637 logerr (TAG, "Failed to register model\n");
641 int status = models_.insert (model->getID(), model);
643 logerr (TAG, "Failed to insert model id\n");
648 *modelid = model->getID();
653 * @brief remove the registered model
654 * @param[in] modelid model id
655 * @return 0 if no error. otherwise a negative errno
658 HostHandler::unregisterModel (uint32_t modelid)
660 return models_.remove (modelid);
664 * @brief remove all registered models
668 HostHandler::unregisterModels ()
675 * @brief Set the data layout for input/output tensors
676 * @param[in] modelid The ID of model whose layouts are set
677 * @param[in] in the layout/type info for input tensors
678 * @param[in] out the layout/type info for output tensors
679 * @return @c 0 if no error. otherwise a negative error value
680 * @note if this function is not called, default layout/type will be used.
683 HostHandler::setDataInfo (uint32_t modelid, tensors_data_info *in,
684 tensors_data_info *out)
686 Model *model = models_.find (modelid);
687 if (model == nullptr)
690 model->setDataInfo (in, out);
696 * @brief Set the inference constraint for next NPU inferences
697 * @param[in] modelid The target model id
698 * @param[in] constraint inference constraint (e.g., timeout, priority)
699 * @return @c 0 if no error. otherwise a negative error value
700 * @note If this function is not called, default values are used.
703 HostHandler::setConstraint (uint32_t modelid, npuConstraint constraint)
705 Model *model = models_.find (modelid);
706 if (model == nullptr)
709 model->setConstraint (constraint);
715 * @brief find and return model instance
716 * @param[in] modelid model id
717 * @return model instance if found. otherwise nullptr
720 HostHandler::getModel (uint32_t modelid)
722 return models_.find (modelid);
725 /** @brief dummay callback for runSync. */
728 callbackSync (output_buffers *output) : output_(output), done_(false) {}
730 static void callback (output_buffers *output, uint64_t sequence, void *data) {
731 callbackSync *sync = static_cast<callbackSync *>(data);
732 sync->callback (output, sequence);
735 void callback (output_buffers *output, uint64_t sequence) {
736 /** just copy internal variables of output buffers */
737 memcpy (output_, output, sizeof (output_buffers));
743 std::unique_lock<std::mutex> lock (m_);
744 cv_.wait (lock, [this]() { return done_; });
749 std::condition_variable cv_;
750 output_buffers *output_;
755 * @brief Execute inference. Wait (block) until the output is available.
756 * @param[in] modelid The model to be inferred.
757 * @param[in] input The input data to be inferred.
758 * @param[out] output The output result.
759 * @return @c 0 if no error. otherwise a negative error value
762 HostHandler::runSync (uint32_t modelid, const input_buffers *input,
763 output_buffers *output)
765 callbackSync sync (output);
766 int status = runAsync (modelid, input, callbackSync::callback,
767 static_cast <void*> (&sync), NPUASYNC_DROP_OLD, nullptr);
769 /** sync needs to wait callback */
776 * @brief Invoke NPU inference. Unblocking call.
777 * @param[in] modelid The model to be inferred.
778 * @param[in] input The input data to be inferred.
779 * @param[in] cb The output buffer handler.
780 * @param[in] cb_data The data given as a parameter to the runNPU_async call.
781 * @param[in] mode Configures how this operation works.
782 * @param[out] sequence The sequence number returned with runNPU_async.
783 * @return @c 0 if no error. otherwise a negative error value
786 HostHandler::runAsync (uint32_t modelid, const input_buffers *input,
787 npuOutputNotify cb, void *cb_data, npu_async_mode mode, uint64_t *sequence)
789 Model *model = nullptr;
791 if (device_->needModel()) {
792 model = getModel (modelid);
793 if (model == nullptr)
797 device_->setAsyncMode (mode);
798 return device_->run (NPUINPUT_HOST, model, input, cb, cb_data, sequence);
802 * @brief get number of available devices
803 * @param[in] type device type
804 * @return number of devices
807 HostHandler::getNumDevices (dev_type type)
809 return DriverAPI::getNumDevices (type);
813 * @brief get device instance
814 * @param[out] dev device instance
815 * @param[in] type device type
816 * @param[in] id device id
817 * @return 0 if no error. otherwise a negative errno
820 HostHandler::getDevice (npudev_h *dev, dev_type type, uint32_t id)
822 int num_devices = getNumDevices (type);
824 /** check the validity of device id */
825 if (!(num_devices > 0 && id < static_cast<uint32_t>(num_devices))) {
826 logerr (TAG, "Invalid arguments provided\n");
830 Device *device = Device::createInstance (type, id);
831 if (device == nullptr) {
832 logerr (TAG, "Failed to create a device with the given type\n");
837 /** This is just for backward-compatility; we don't guarantee its corresness */
844 * @brief allocate generic buffer (just for users)
845 * @param[out] buffer buffer instance
846 * @return 0 if no error. otherwise a negative errno
849 HostHandler::allocGenericBuffer (generic_buffer *buffer)
851 if (buffer == NULL || SIZE_MAX < buffer->size)
854 if (buffer->type == BUFFER_FILE) {
856 if (buffer->filepath == nullptr)
859 /* now, npu-engine always provides dmabuf-based allocation */
860 HWmem *hwmem = device_->allocMemory ();
861 if (hwmem == nullptr || hwmem->alloc (buffer->size) < 0)
864 buffer->dmabuf = hwmem->getDmabuf();
865 buffer->offset = hwmem->getOffset();
866 buffer->addr = hwmem->getData();
872 * @brief deallocate generic buffer (just for users)
873 * @param[in] buffer buffer instance
874 * @return 0 if no error. otherwise a negative errno
877 HostHandler::deallocGenericBuffer (generic_buffer *buffer)
882 if (buffer->type != BUFFER_FILE)
883 device_->deallocMemory (buffer->dmabuf);
889 * @brief allocate multiple generic buffers (just for users)
890 * @param[out] buffers multi-buffer instance
891 * @return 0 if no error. otherwise a negative errno
894 HostHandler::allocGenericBuffer (generic_buffers *buffers)
896 if (buffers == NULL || buffers->num_buffers < 1)
899 buffer_types type = buffers->bufs[0].type;
900 if (type == BUFFER_FILE)
903 uint64_t total_size = 0;
904 for (uint32_t idx = 0; idx < buffers->num_buffers; idx++)
905 total_size += buffers->bufs[idx].size;
907 uint64_t first_size = buffers->bufs[0].size;
908 buffers->bufs[0].size = total_size;
909 int status = allocGenericBuffer (&buffers->bufs[0]);
913 uint64_t offset = first_size;
914 for (uint32_t idx = 1; idx < buffers->num_buffers; idx++) {
915 buffers->bufs[idx].dmabuf = buffers->bufs[0].dmabuf;
916 buffers->bufs[idx].offset = buffers->bufs[0].offset + offset;
917 buffers->bufs[idx].type = type;
919 offset += buffers->bufs[idx].size;
926 * @brief deallocate multiple generic buffers (just for users)
927 * @param[in] buffers multi-buffer instance
928 * @return 0 if no error. otherwise a negative errno
931 HostHandler::deallocGenericBuffer (generic_buffers *buffers)
933 if (buffers == NULL || buffers->num_buffers < 1)
936 return deallocGenericBuffer (&buffers->bufs[0]);
939 /** just for backward-compatability */
940 npudev_h HostHandler::latest_dev_ = nullptr;
942 /** implementation of libnpuhost APIs */
945 * @brief Returns the number of available NPU devices.
946 * @return @c The number of NPU devices.
947 * @retval 0 if no NPU devices available. if positive (number of NPUs) if NPU devices available. otherwise, a negative error value.
949 int getnumNPUdeviceByType (dev_type type)
951 return HostHandler::getNumDevices (type);
955 * @brief Returns the number of NPU devices (TRIV).
957 int getnumNPUdevice (void)
959 return getnumNPUdeviceByType (NPUCOND_TRIV_CONN_SOCIP);
963 * @brief Returns the list of ASR devices (TRIA)
965 int getnumASRdevice (void)
967 return getnumNPUdeviceByType (NPUCOND_TRIA_CONN_SOCIP);
971 * @brief Returns the handle of the chosen NPU devices.
972 * @param[out] dev The NPU device handle
973 * @param[in] id The NPU id to get the handle. 0 <= id < getnumNPUdeviceByType().
974 * @return @c 0 if no error. otherwise a negative error value
976 int getNPUdeviceByType (npudev_h *dev, dev_type type, uint32_t id)
978 return HostHandler::getDevice (dev, type, id);
982 * @brief Returns the handle of the chosen TRIV device.
984 int getNPUdevice (npudev_h *dev, uint32_t id)
986 return getNPUdeviceByType (dev, NPUCOND_TRIV_CONN_SOCIP, id);
990 * @brief Returns the handle of the chosen TRIA device.
992 int getASRdevice (npudev_h *dev, uint32_t id)
994 return getNPUdeviceByType (dev, NPUCOND_TRIA_CONN_SOCIP, id);
998 * @brief Send the NN model to NPU.
999 * @param[in] dev The NPU device handle
1000 * @param[in] modelfile The filepath to the compiled NPU NN model in any buffer_type
1001 * @param[out] modelid The modelid allocated for this instance of NN model.
1002 * @return @c 0 if no error. otherwise a negative error value
1004 * @detail For ASR devices, which do not accept models, but have models
1005 * embedded in devices, you do not need to call register and
1006 * register calls for ASR are ignored.
1008 * @todo Add a variation: in-memory model register.
1010 int registerNPUmodel (npudev_h dev, generic_buffer *modelfile, uint32_t *modelid)
1012 INIT_HOST_HANDLER (host_handler, dev);
1014 return host_handler->registerModel (modelfile, modelid);
1018 * @brief Remove the NN model from NPU
1019 * @param[in] dev The NPU device handle
1020 * @param[in] modelid The model to be removed from the NPU.
1021 * @return @c 0 if no error. otherwise a negative error value
1022 * @detail This may incur some latency with memory compatcion.
1024 int unregisterNPUmodel(npudev_h dev, uint32_t modelid)
1026 INIT_HOST_HANDLER (host_handler, dev);
1028 return host_handler->unregisterModel (modelid);
1032 * @brief Remove all NN models from NPU
1033 * @param[in] dev The NPU device handle
1034 * @return @c 0 if no error. otherwise a negative error value
1036 int unregisterNPUmodel_all(npudev_h dev)
1038 INIT_HOST_HANDLER (host_handler, dev);
1040 return host_handler->unregisterModels ();
1044 * @brief [OPTIONAL] Set the data layout for input/output tensors
1045 * @param[in] dev The NPU device handle
1046 * @param[in] modelid The ID of model whose layouts are set
1047 * @param[in] info_in the layout/type info for input tensors
1048 * @param[in] info_out the layout/type info for output tensors
1049 * @return @c 0 if no error. otherwise a negative error value
1050 * @note if this function is not called, default layout/type will be used.
1052 int setNPU_dataInfo(npudev_h dev, uint32_t modelid,
1053 tensors_data_info *info_in, tensors_data_info *info_out)
1055 INIT_HOST_HANDLER (host_handler, dev);
1057 return host_handler->setDataInfo (modelid, info_in, info_out);
1061 * @brief [OPTIONAL] Set the inference constraint for next NPU inferences
1062 * @param[in] dev The NPU device handle
1063 * @param[in] modelid The target model id
1064 * @param[in] constraint inference constraint (e.g., timeout, priority)
1065 * @return @c 0 if no error. otherwise a negative error value
1066 * @note If this function is not called, default values are used.
1068 int setNPU_constraint(npudev_h dev, uint32_t modelid, npuConstraint constraint)
1070 INIT_HOST_HANDLER (host_handler, dev);
1072 return host_handler->setConstraint (modelid, constraint);
1076 * @brief Execute inference. Wait (block) until the output is available.
1077 * @param[in] dev The NPU device handle
1078 * @param[in] modelid The model to be inferred.
1079 * @param[in] input The input data to be inferred.
1080 * @param[out] output The output result. The caller MUST allocate appropriately before calling this.
1081 * @return @c 0 if no error. otherwise a negative error value
1083 * @detail This is a syntactic sugar of runNPU_async().
1084 * CAUTION: There is a memcpy for the output buffer.
1086 int runNPU_sync(npudev_h dev, uint32_t modelid, const input_buffers *input,
1087 output_buffers *output)
1089 INIT_HOST_HANDLER (host_handler, dev);
1091 return host_handler->runSync (modelid, input, output);
1095 * @brief Invoke NPU inference. Unblocking call.
1096 * @param[in] dev The NPU device handle
1097 * @param[in] modelid The model to be inferred.
1098 * @param[in] input The input data to be inferred.
1099 * @param[in] cb The output buffer handler.
1100 * @param[out] sequence The sequence number returned with runNPU_async.
1101 * @param[in] data The data given as a parameter to the runNPU_async call.
1102 * @param[in] mode Configures how this operation works.
1103 * @return @c 0 if no error. otherwise a negative error value
1105 int runNPU_async(npudev_h dev, uint32_t modelid, const input_buffers *input,
1106 npuOutputNotify cb, uint64_t *sequence, void *data,
1107 npu_async_mode mode)
1109 INIT_HOST_HANDLER (host_handler, dev);
1111 return host_handler->runAsync (modelid, input, cb, data, mode, sequence);
1115 * @brief Allocate a buffer for NPU model with the requested buffer type.
1116 * @param[in] dev The NPU device handle
1117 * @param[in/out] Buffer the buffer pointer where memory is allocated.
1118 * @return 0 if no error, otherwise a negative errno.
1120 int allocNPU_modelBuffer (npudev_h dev, generic_buffer *buffer)
1122 INIT_HOST_HANDLER (host_handler, dev);
1124 return host_handler->allocGenericBuffer (buffer);
1128 * @brief Free the buffer and remove the address mapping.
1129 * @param[in] dev The NPU device handle
1130 * @param[in] buffer the model buffer
1131 * @return 0 if no error, otherwise a negative errno.
1133 int cleanNPU_modelBuffer (npudev_h dev, generic_buffer *buffer)
1135 INIT_HOST_HANDLER (host_handler, dev);
1137 return host_handler->deallocGenericBuffer (buffer);
1141 * @brief Allocate a buffer for NPU input with the requested buffer type.
1142 * @param[in] dev The NPU device handle
1143 * @param[in/out] Buffer the buffer pointer where memory is allocated.
1144 * @return 0 if no error, otherwise a negative errno.
1145 * @note please utilize allocInputBuffers() for multiple input tensors because subsequent
1146 * calls of allocInputBuffer() don't gurantee contiguous allocations between them.
1148 int allocNPU_inputBuffer (npudev_h dev, generic_buffer *buffer)
1150 INIT_HOST_HANDLER (host_handler, dev);
1152 return host_handler->allocGenericBuffer (buffer);
1156 * @brief Free the buffer and remove the address mapping.
1157 * @param[in] dev The NPU device handle
1158 * @param[in] buffer the input buffer
1159 * @return 0 if no error, otherwise a negative errno.
1161 int cleanNPU_inputBuffer (npudev_h dev, generic_buffer *buffer)
1163 INIT_HOST_HANDLER (host_handler, dev);
1165 return host_handler->deallocGenericBuffer (buffer);
1169 * @brief Allocate input buffers, which have multiple instances of generic_buffer
1170 * @param[in] dev The NPU device handle
1171 * @param[in/out] input input buffers.
1172 * @return 0 if no error, otherwise a negative errno.
1173 * @note it reuses allocInputBuffer().
1174 * @details in case of BUFFER_DMABUF, this function can be used to gurantee physically-contiguous
1175 * memory mapping for multiple tensors (in a single inference, not batch size).
1177 int allocNPU_inputBuffers (npudev_h dev, input_buffers * input)
1179 INIT_HOST_HANDLER (host_handler, dev);
1181 return host_handler->allocGenericBuffer (input);
1185 * @brief Free input buffers allocated by allocInputBuffers().
1186 * @param[in] dev The NPU device handle
1187 * @param[in/out] input input buffers.
1188 * @note it reuses cleanInputbuffer().
1189 * @return 0 if no error, otherwise a negative errno.
1191 int cleanNPU_inputBuffers (npudev_h dev, input_buffers * input)
1193 INIT_HOST_HANDLER (host_handler, dev);
1195 return host_handler->deallocGenericBuffer (input);
1199 * @brief Get metadata for NPU model
1200 * @param[in] model The path of model binary file
1201 * @param[in] need_extra whether you want to extract the extra data in metadata
1202 * @return the metadata structure to be filled if no error, otherwise nullptr
1204 * @note For most npu-engine users, the extra data is not useful because it will be
1205 * used for second-party users (e.g., compiler, simulator).
1206 * Also, the caller needs to free the metadata.
1208 * @note the caller needs to free the metadata
1210 npubin_meta * getNPUmodel_metadata (const char *model, bool need_extra)
1219 fp = fopen (model, "rb");
1221 logerr (TAG, "Failed to open the model binary: %d\n", -errno);
1225 meta = (npubin_meta *) malloc (NPUBIN_META_SIZE);
1227 logerr (TAG, "Failed to allocate metadata\n");
1231 ret = fread (meta, 1, NPUBIN_META_SIZE, fp);
1232 if (ret != NPUBIN_META_SIZE) {
1233 logerr (TAG, "Failed to read the metadata\n");
1237 if (!CHECK_NPUBIN (meta->magiccode)) {
1238 logerr (TAG, "Invalid metadata provided\n");
1242 if (need_extra && NPUBIN_META_EXTRA (meta->magiccode) > 0) {
1243 npubin_meta *new_meta;
1245 new_meta = (npubin_meta *) realloc (meta, NPUBIN_META_TOTAL_SIZE(meta->magiccode));
1247 logerr (TAG, "Failed to allocate extra metadata\n");
1251 ret = fread (new_meta->reserved_extra, 1, NPUBIN_META_EXTRA_SIZE (meta->magiccode), fp);
1252 if (ret != NPUBIN_META_EXTRA_SIZE (meta->magiccode)) {
1253 logerr (TAG, "Invalid extra metadata provided\n");
1273 /** deprecated buffer APIs; please use the above APIs */
1275 /** @brief deprecated */
1276 int allocModelBuffer (generic_buffer *buffer)
1278 logwarn (TAG, "deprecated. Please use allocNPU_modelBuffer\n");
1279 return allocNPU_modelBuffer (HostHandler::getLatestDevice(), buffer);
1282 /** @brief deprecated */
1283 int cleanModelBuffer (generic_buffer *buffer)
1285 logwarn (TAG, "deprecated. Please use cleanNPU_modelBuffer\n");
1286 return allocNPU_modelBuffer (HostHandler::getLatestDevice(), buffer);
1289 /** @brief deprecated */
1290 int allocInputBuffer (generic_buffer *buffer)
1292 logwarn (TAG, "deprecated. Please use allocNPU_inputBuffer\n");
1293 return allocNPU_inputBuffer (HostHandler::getLatestDevice(), buffer);
1296 /** @brief deprecated */
1297 int cleanInputBuffer (generic_buffer *buffer)
1299 logwarn (TAG, "deprecated. Please use cleanNPU_inputBuffer\n");
1300 return cleanNPU_inputBuffer (HostHandler::getLatestDevice(), buffer);
1303 /** @brief deprecated */
1304 int allocInputBuffers (input_buffers * input)
1306 logwarn (TAG, "deprecated. Please use allocNPU_inputBuffers\n");
1307 return allocNPU_inputBuffers (HostHandler::getLatestDevice(), input);
1310 /** @brief deprecated */
1311 int cleanInputBuffers (input_buffers * input)
1313 logwarn (TAG, "deprecated. Please use cleanNPU_inputBuffers\n");
1314 return cleanNPU_inputBuffers (HostHandler::getLatestDevice(), input);
1317 /** @brief deprecated */
1318 int allocNPUBuffer (uint64_t size, buffer_types type,
1319 const char * filepath, generic_buffer *buffer)
1322 buffer->size = size;
1323 buffer->type = type;
1324 buffer->filepath = filepath;
1327 logwarn (TAG, "deprecated. Please use allocNPU_* APIs\n");
1328 return allocModelBuffer (buffer);
1331 /** @brief deprecated */
1332 int cleanNPUBuffer (generic_buffer * buffer)
1334 logwarn (TAG, "deprecated. Please use cleanNPU_* APIs\n");
1335 return cleanModelBuffer (buffer);