3 * Copyright (C) 2020 Samsung Electronics
4 * Copyright (C) 2020 Dongju Chae <dongju.chae@samsung.com>
7 * @file ne-host-handler.cc
9 * @brief Implementation of APIs to access NPU from Host
10 * @see https://code.sec.samsung.net/confluence/display/ODLC/2020+Overall+Software+Stack
11 * @author Dongju Chae <dongju.chae@samsung.com>
12 * @bug No known bugs except for NYI items
15 #include "ne-handler.h"
17 #include <libnpuhost.h>
18 #include <npubinfmt.h>
19 #include <NPUdrvAPI.h>
20 #include <CommPlugin.h>
25 #include <condition_variable>
32 #define INIT_HOST_HANDLER(handler, dev) \
33 Device *tdev = static_cast <Device *> (dev); \
34 if (tdev == nullptr) return -EINVAL; \
35 HostHandler *handler = tdev->getHostHandler (); \
36 if (handler == nullptr) return -EINVAL;
38 /** just for backward-compatability */
39 npudev_h HostHandler::latest_dev_ = nullptr;
41 /** implement libnpuhost APIs */
44 * @brief Returns the number of available NPU devices.
45 * @return @c The number of NPU devices.
46 * @retval 0 if no NPU devices available. if positive (number of NPUs) if NPU devices available. otherwise, a negative error value.
47 * @note the caller should call putNPUdevice() to release the device handle
49 int getnumNPUdeviceByType (dev_type type)
51 return HostHandler::getNumDevices (type);
55 * @brief Returns the handle of the chosen NPU devices.
56 * @param[out] dev The NPU device handle
57 * @param[in] id The NPU id to get the handle. 0 <= id < getnumNPUdeviceByType().
58 * @return @c 0 if no error. otherwise a negative error value
59 * @note the caller should call putNPUdevice() to release the device handle
61 int getNPUdeviceByType (npudev_h *dev, dev_type type, uint32_t id)
63 return HostHandler::getDevice (dev, type, id);
67 * @brief Returns the handle of an NPU device meeting the condition
68 * @param[out] dev The NPU device handle
69 * @param[in] cond The condition for device search.
70 * @return @c 0 if no error. otherwise a negative error value
71 * @note the caller should call putNPUdevice() to release the device handle
72 * @note it's not supported yet
74 int getNPUdeviceByCondition(npudev_h *dev, const npucondition *cond)
76 /** not implmeneted yet */
77 return getNPUdeviceByType (dev, NPUCOND_TRIV_CONN_SOCIP, 0);
81 * @brief release the NPU device instance obtained by getDevice ()
82 * @param[in] dev the NPU device handle
84 void putNPUdevice (npudev_h dev)
87 delete static_cast<Device *> (dev);
91 * @brief Send the NN model to NPU.
92 * @param[in] dev The NPU device handle
93 * @param[in] modelfile The filepath to the compiled NPU NN model in any buffer_type
94 * @param[out] modelid The modelid allocated for this instance of NN model.
95 * @return @c 0 if no error. otherwise a negative error value
97 * @detail For ASR devices, which do not accept models, but have models
98 * embedded in devices, you do not need to call register and
99 * register calls for ASR are ignored.
101 * @todo Add a variation: in-memory model register.
103 int registerNPUmodel (npudev_h dev, generic_buffer *modelfile, uint32_t *modelid)
105 INIT_HOST_HANDLER (host_handler, dev);
107 return host_handler->registerModel (modelfile, modelid);
111 * @brief Remove the NN model from NPU
112 * @param[in] dev The NPU device handle
113 * @param[in] modelid The model to be removed from the NPU.
114 * @return @c 0 if no error. otherwise a negative error value
115 * @detail This may incur some latency with memory compatcion.
117 int unregisterNPUmodel(npudev_h dev, uint32_t modelid)
119 INIT_HOST_HANDLER (host_handler, dev);
121 return host_handler->unregisterModel (modelid);
125 * @brief Remove all NN models from NPU
126 * @param[in] dev The NPU device handle
127 * @return @c 0 if no error. otherwise a negative error value
129 int unregisterNPUmodel_all(npudev_h dev)
131 INIT_HOST_HANDLER (host_handler, dev);
133 return host_handler->unregisterModels ();
137 * @brief [OPTIONAL] Set the data layout for input/output tensors
138 * @param[in] dev The NPU device handle
139 * @param[in] modelid The ID of model whose layouts are set
140 * @param[in] info_in the layout/type info for input tensors
141 * @param[in] info_out the layout/type info for output tensors
142 * @return @c 0 if no error. otherwise a negative error value
143 * @note if this function is not called, default layout/type will be used.
145 int setNPU_dataInfo(npudev_h dev, uint32_t modelid,
146 tensors_data_info *info_in, tensors_data_info *info_out)
148 INIT_HOST_HANDLER (host_handler, dev);
150 return host_handler->setDataInfo (modelid, info_in, info_out);
154 * @brief [OPTIONAL] Set the inference constraint for next NPU inferences
155 * @param[in] dev The NPU device handle
156 * @param[in] modelid The target model id
157 * @param[in] constraint inference constraint (e.g., timeout, priority)
158 * @return @c 0 if no error. otherwise a negative error value
159 * @note If this function is not called, default values are used.
161 int setNPU_constraint(npudev_h dev, uint32_t modelid, npuConstraint constraint)
163 INIT_HOST_HANDLER (host_handler, dev);
165 return host_handler->setConstraint (modelid, constraint);
169 * @brief Execute inference. Wait (block) until the output is available.
170 * @param[in] dev The NPU device handle
171 * @param[in] modelid The model to be inferred.
172 * @param[in] input The input data to be inferred.
173 * @param[out] output The output result. The caller MUST allocate appropriately before calling this.
174 * @return @c 0 if no error. otherwise a negative error value
176 * @detail This is a syntactic sugar of runNPU_async().
177 * CAUTION: There is a memcpy for the output buffer.
179 int runNPU_sync(npudev_h dev, uint32_t modelid, const input_buffers *input,
180 output_buffers *output)
182 INIT_HOST_HANDLER (host_handler, dev);
184 return host_handler->runSync (modelid, input, output);
188 * @brief Invoke NPU inference. Unblocking call.
189 * @param[in] dev The NPU device handle
190 * @param[in] modelid The model to be inferred.
191 * @param[in] input The input data to be inferred.
192 * @param[in] cb The output buffer handler.
193 * @param[out] sequence The sequence number returned with runNPU_async.
194 * @param[in] data The data given as a parameter to the runNPU_async call.
195 * @param[in] mode Configures how this operation works.
196 * @return @c 0 if no error. otherwise a negative error value
198 int runNPU_async(npudev_h dev, uint32_t modelid, const input_buffers *input,
199 npuOutputNotify cb, uint64_t *sequence, void *data,
202 INIT_HOST_HANDLER (host_handler, dev);
204 return host_handler->runAsync (modelid, input, cb, data, mode, sequence);
208 * @brief Allocate a buffer for NPU model with the requested buffer type.
209 * @param[in] dev The NPU device handle
210 * @param[in/out] Buffer the buffer pointer where memory is allocated.
211 * @return 0 if no error, otherwise a negative errno.
213 int allocNPU_modelBuffer (npudev_h dev, generic_buffer *buffer)
215 INIT_HOST_HANDLER (host_handler, dev);
217 return host_handler->allocGenericBuffer (buffer);
221 * @brief Free the buffer and remove the address mapping.
222 * @param[in] dev The NPU device handle
223 * @param[in] buffer the model buffer
224 * @return 0 if no error, otherwise a negative errno.
226 int cleanNPU_modelBuffer (npudev_h dev, generic_buffer *buffer)
228 INIT_HOST_HANDLER (host_handler, dev);
230 return host_handler->deallocGenericBuffer (buffer);
234 * @brief Allocate a buffer for NPU input with the requested buffer type.
235 * @param[in] dev The NPU device handle
236 * @param[in/out] Buffer the buffer pointer where memory is allocated.
237 * @return 0 if no error, otherwise a negative errno.
238 * @note please utilize allocInputBuffers() for multiple input tensors because subsequent
239 * calls of allocInputBuffer() don't gurantee contiguous allocations between them.
241 int allocNPU_inputBuffer (npudev_h dev, generic_buffer *buffer)
243 INIT_HOST_HANDLER (host_handler, dev);
245 return host_handler->allocGenericBuffer (buffer);
249 * @brief Free the buffer and remove the address mapping.
250 * @param[in] dev The NPU device handle
251 * @param[in] buffer the input buffer
252 * @return 0 if no error, otherwise a negative errno.
254 int cleanNPU_inputBuffer (npudev_h dev, generic_buffer *buffer)
256 INIT_HOST_HANDLER (host_handler, dev);
258 return host_handler->deallocGenericBuffer (buffer);
262 * @brief Allocate input buffers, which have multiple instances of generic_buffer
263 * @param[in] dev The NPU device handle
264 * @param[in/out] input input buffers.
265 * @return 0 if no error, otherwise a negative errno.
266 * @note it reuses allocInputBuffer().
267 * @details in case of BUFFER_DMABUF, this function can be used to gurantee physically-contiguous
268 * memory mapping for multiple tensors (in a single inference, not batch size).
270 int allocNPU_inputBuffers (npudev_h dev, input_buffers * input)
272 INIT_HOST_HANDLER (host_handler, dev);
274 return host_handler->allocGenericBuffer (input);
278 * @brief Free input buffers allocated by allocInputBuffers().
279 * @param[in] dev The NPU device handle
280 * @param[in/out] input input buffers.
281 * @note it reuses cleanInputbuffer().
282 * @return 0 if no error, otherwise a negative errno.
284 int cleanNPU_inputBuffers (npudev_h dev, input_buffers * input)
286 INIT_HOST_HANDLER (host_handler, dev);
288 return host_handler->deallocGenericBuffer (input);
292 * @brief get the current memory status for the given device
293 * @param[in] dev The NPU device handle
294 * @param[out] alloc_total The size of allocated memory until now
295 * @param[out] free_total The size of freed memory until now
296 * @return @c 0 if no error. otherwise a negatice error value
298 int getNPU_memoryStatus(npudev_h dev, size_t *alloc_total, size_t *free_total)
300 INIT_HOST_HANDLER (host_handler, dev);
302 return host_handler->getMemoryStatus (alloc_total, free_total);
306 * @brief Get metadata for NPU model
307 * @param[in] model The path of model binary file
308 * @param[in] need_extra whether you want to extract the extra data in metadata
309 * @return the metadata structure to be filled if no error, otherwise nullptr
311 * @note For most npu-engine users, the extra data is not useful because it will be
312 * used for second-party users (e.g., compiler, simulator).
313 * Also, the caller needs to free the metadata.
315 * @note the caller needs to free the metadata
317 npubin_meta * getNPUmodel_metadata (const char *model, bool need_extra)
326 fp = fopen (model, "rb");
328 logerr (TAG, "Failed to open the model binary: %d\n", -errno);
332 meta = (npubin_meta *) malloc (NPUBIN_META_SIZE);
334 logerr (TAG, "Failed to allocate metadata\n");
338 ret = fread (meta, 1, NPUBIN_META_SIZE, fp);
339 if (ret != NPUBIN_META_SIZE) {
340 logerr (TAG, "Failed to read the metadata\n");
344 if (!CHECK_NPUBIN (meta->magiccode)) {
345 logerr (TAG, "Invalid metadata provided\n");
349 if (need_extra && NPUBIN_META_EXTRA (meta->magiccode) > 0) {
350 npubin_meta *new_meta;
352 new_meta = (npubin_meta *) realloc (meta, NPUBIN_META_TOTAL_SIZE(meta->magiccode));
354 logerr (TAG, "Failed to allocate extra metadata\n");
358 ret = fread (new_meta->reserved_extra, 1, NPUBIN_META_EXTRA_SIZE (meta->magiccode), fp);
359 if (ret != NPUBIN_META_EXTRA_SIZE (meta->magiccode)) {
360 logerr (TAG, "Invalid extra metadata provided\n");
380 /** deprecated buffer APIs; please use the above APIs */
383 * @brief Returns the number of NPU devices (TRIV).
385 int getnumNPUdevice (void)
387 logwarn (TAG, "deprecated. Please use getnumNPUdeviceByType ()\n");
388 return getnumNPUdeviceByType (NPUCOND_TRIV_CONN_SOCIP);
392 * @brief Returns the list of ASR devices (TRIA)
394 int getnumASRdevice (void)
396 logwarn (TAG, "deprecated. Please use getnumNPUdeviceByType ()\n");
397 return getnumNPUdeviceByType (NPUCOND_TRIA_CONN_SOCIP);
401 * @brief Returns the handle of the chosen TRIV device.
403 int getNPUdevice (npudev_h *dev, uint32_t id)
405 logwarn (TAG, "deprecated. Please use getNPUdeviceByType ()\n");
406 return getNPUdeviceByType (dev, NPUCOND_TRIV_CONN_SOCIP, id);
410 * @brief Returns the handle of the chosen TRIA device.
412 int getASRdevice (npudev_h *dev, uint32_t id)
414 logwarn (TAG, "deprecated. Please use getNPUdeviceByType ()\n");
415 return getNPUdeviceByType (dev, NPUCOND_TRIA_CONN_SOCIP, id);
418 /** @brief deprecated */
419 int allocModelBuffer (generic_buffer *buffer)
421 logwarn (TAG, "deprecated. Please use allocNPU_modelBuffer\n");
422 return allocNPU_modelBuffer (HostHandler::getLatestDevice(), buffer);
425 /** @brief deprecated */
426 int cleanModelBuffer (generic_buffer *buffer)
428 logwarn (TAG, "deprecated. Please use cleanNPU_modelBuffer\n");
429 return allocNPU_modelBuffer (HostHandler::getLatestDevice(), buffer);
432 /** @brief deprecated */
433 int allocInputBuffer (generic_buffer *buffer)
435 logwarn (TAG, "deprecated. Please use allocNPU_inputBuffer\n");
436 return allocNPU_inputBuffer (HostHandler::getLatestDevice(), buffer);
439 /** @brief deprecated */
440 int cleanInputBuffer (generic_buffer *buffer)
442 logwarn (TAG, "deprecated. Please use cleanNPU_inputBuffer\n");
443 return cleanNPU_inputBuffer (HostHandler::getLatestDevice(), buffer);
446 /** @brief deprecated */
447 int allocInputBuffers (input_buffers * input)
449 logwarn (TAG, "deprecated. Please use allocNPU_inputBuffers\n");
450 return allocNPU_inputBuffers (HostHandler::getLatestDevice(), input);
453 /** @brief deprecated */
454 int cleanInputBuffers (input_buffers * input)
456 logwarn (TAG, "deprecated. Please use cleanNPU_inputBuffers\n");
457 return cleanNPU_inputBuffers (HostHandler::getLatestDevice(), input);
460 /** @brief deprecated */
461 int allocNPUBuffer (uint64_t size, buffer_types type,
462 const char * filepath, generic_buffer *buffer)
467 buffer->filepath = filepath;
470 logwarn (TAG, "deprecated. Please use allocNPU_* APIs\n");
471 return allocModelBuffer (buffer);
474 /** @brief deprecated */
475 int cleanNPUBuffer (generic_buffer * buffer)
477 logwarn (TAG, "deprecated. Please use cleanNPU_* APIs\n");
478 return cleanModelBuffer (buffer);
481 /** implement methods of HostHandler class */
483 /** @brief host handler constructor */
484 HostHandler::HostHandler (Device *device)
486 /* ignored as we don't use double buffering anymore, but for backward-compatibility */
487 async_mode_ (NPUASYNC_WAIT)
491 /** @brief host handler destructor */
492 HostHandler::~HostHandler ()
497 * @brief register model from generic buffer
498 * @param[in] model_buf model buffer
499 * @param[out] modelid model id
500 * @return 0 if no error. otherwise a negative errno
503 HostHandler::registerModel (generic_buffer *model_buf, uint32_t *modelid)
505 if (model_buf == nullptr || modelid == nullptr) {
506 logerr (TAG, "Invalid arguments given\n");
510 Model *model = nullptr;
511 int status = device_->setModel (model_buf, &model);
513 logerr (TAG, "Failed to set model: %d\n", status);
517 assert (model != nullptr);
519 status = models_.insert (model->getID(), model);
521 logerr (TAG, "Failed to insert model id\n");
526 *modelid = model->getID();
531 * @brief remove the registered model
532 * @param[in] modelid model id
533 * @return 0 if no error. otherwise a negative errno
536 HostHandler::unregisterModel (uint32_t modelid)
538 Model *model = models_.find (modelid);
539 if (model == nullptr)
542 int status = device_->unsetModel (model);
544 logerr (TAG, "Failed to unset model: %d\n", status);
548 return models_.remove (modelid);
552 * @brief remove all registered models
556 HostHandler::unregisterModels ()
563 * @brief Set the data layout for input/output tensors
564 * @param[in] modelid The ID of model whose layouts are set
565 * @param[in] in the layout/type info for input tensors
566 * @param[in] out the layout/type info for output tensors
567 * @return @c 0 if no error. otherwise a negative error value
568 * @note if this function is not called, default layout/type will be used.
571 HostHandler::setDataInfo (uint32_t modelid, tensors_data_info *in,
572 tensors_data_info *out)
574 Model *model = models_.find (modelid);
575 if (model == nullptr)
578 return model->setDataInfo (in, out);
582 * @brief Set the inference constraint for next NPU inferences
583 * @param[in] modelid The target model id
584 * @param[in] constraint inference constraint (e.g., timeout, priority)
585 * @return @c 0 if no error. otherwise a negative error value
586 * @note If this function is not called, default values are used.
589 HostHandler::setConstraint (uint32_t modelid, npuConstraint constraint)
591 Model *model = models_.find (modelid);
592 if (model == nullptr)
595 model->setConstraint (constraint);
601 * @brief find and return model instance
602 * @param[in] modelid model id
603 * @return model instance if found. otherwise nullptr
606 HostHandler::getModel (uint32_t modelid)
608 return models_.find (modelid);
611 /** @brief dummay callback for runSync. */
614 callbackSync (output_buffers *output) : output_(output), done_(false) {}
616 static void callback (output_buffers *output, uint64_t sequence, void *data) {
617 callbackSync *sync = static_cast<callbackSync *>(data);
618 sync->callback (output, sequence);
621 void callback (output_buffers *output, uint64_t sequence) {
622 if (output_ != nullptr) {
623 /** just copy internal variables of output buffers */
624 memcpy (output_, output, sizeof (output_buffers));
631 std::unique_lock<std::mutex> lock (m_);
632 cv_.wait (lock, [this]() { return done_; });
637 std::condition_variable cv_;
638 output_buffers *output_;
643 * @brief Execute inference. Wait (block) until the output is available.
644 * @param[in] modelid The model to be inferred.
645 * @param[in] input The input data to be inferred.
646 * @param[out] output The output result.
647 * @return @c 0 if no error. otherwise a negative error value
650 HostHandler::runSync (uint32_t modelid, const input_buffers *input,
651 output_buffers *output)
653 callbackSync sync (output);
654 int status = runAsync (modelid, input, callbackSync::callback,
655 static_cast <void*> (&sync), NPUASYNC_DROP_OLD, nullptr);
657 /** sync needs to wait callback */
664 * @brief Invoke NPU inference. Unblocking call.
665 * @param[in] modelid The model to be inferred.
666 * @param[in] input The input data to be inferred.
667 * @param[in] cb The output buffer handler.
668 * @param[in] cb_data The data given as a parameter to the runNPU_async call.
669 * @param[in] mode Configures how this operation works.
670 * @param[out] sequence The sequence number returned with runNPU_async.
671 * @return @c 0 if no error. otherwise a negative error value
674 HostHandler::runAsync (uint32_t modelid, const input_buffers *input,
675 npuOutputNotify cb, void *cb_data, npu_async_mode mode, uint64_t *sequence)
677 Model *model = nullptr;
679 if (device_->needModel()) {
680 model = getModel (modelid);
681 if (model == nullptr)
685 device_->setAsyncMode (mode);
686 return device_->run (NPUINPUT_HOST, model, input, cb, cb_data, sequence);
690 * @brief get number of available devices
691 * @param[in] type device type
692 * @return number of devices
695 HostHandler::getNumDevices (dev_type type)
697 return DriverAPI::getNumDevices (type);
701 * @brief get device instance
702 * @param[out] dev device instance
703 * @param[in] type device type
704 * @param[in] id device id
705 * @return 0 if no error. otherwise a negative errno
708 HostHandler::getDevice (npudev_h *dev, dev_type type, uint32_t id)
710 int num_devices = getNumDevices (type);
712 /** check the validity of device id */
713 if (!(num_devices > 0 && id < static_cast<uint32_t>(num_devices))) {
714 logerr (TAG, "Invalid arguments provided\n");
718 Device *device = Device::createInstance (type, id);
719 if (device == nullptr) {
720 logerr (TAG, "Failed to create a device with the given type\n");
725 /** This is just for backward-compatility; we don't guarantee its corresness */
732 * @brief allocate generic buffer (just for users)
733 * @param[out] buffer buffer instance
734 * @return 0 if no error. otherwise a negative errno
737 HostHandler::allocGenericBuffer (generic_buffer *buffer)
742 if (buffer->size == 0) {
743 logerr (TAG, "Invalid size\n");
747 if (buffer->size > UINT32_MAX) {
748 logerr (TAG, "Don't support such a large size");
752 switch (buffer->type) {
755 if (buffer->filepath == nullptr)
761 /* now, npu-engine always provides dmabuf-based allocation */
762 void *addr = nullptr;
763 int dmabuf = device_->allocMemory (buffer->size, &addr);
767 buffer->dmabuf = dmabuf;
779 * @brief deallocate generic buffer (just for users)
780 * @param[in] buffer buffer instance
781 * @return 0 if no error. otherwise a negative errno
784 HostHandler::deallocGenericBuffer (generic_buffer *buffer)
790 switch (buffer->type) {
792 status = 0; /** always true cuz nothing to do */
796 status = device_->deallocMemory (buffer->dmabuf, buffer->size, buffer->addr);
807 * @brief allocate multiple generic buffers (just for users)
808 * @param[out] buffers multi-buffer instance
809 * @return 0 if no error. otherwise a negative errno
812 HostHandler::allocGenericBuffer (generic_buffers *buffers)
814 if (buffers == NULL || buffers->num_buffers < 1)
817 buffer_types type = buffers->bufs[0].type;
818 if (type == BUFFER_FILE)
821 uint64_t total_size = 0;
822 for (uint32_t idx = 0; idx < buffers->num_buffers; idx++)
823 total_size += buffers->bufs[idx].size;
825 uint64_t first_size = buffers->bufs[0].size;
826 buffers->bufs[0].size = total_size;
827 int status = allocGenericBuffer (&buffers->bufs[0]);
831 uint64_t offset = first_size;
832 for (uint32_t idx = 1; idx < buffers->num_buffers; idx++) {
833 buffers->bufs[idx].dmabuf = buffers->bufs[0].dmabuf;
834 buffers->bufs[idx].offset = buffers->bufs[0].offset + offset;
835 buffers->bufs[idx].addr = static_cast<char*>(buffers->bufs[0].addr) + offset;
836 buffers->bufs[idx].type = type;
838 offset += buffers->bufs[idx].size;
841 buffers->bufs[0].size = first_size;
847 * @brief deallocate multiple generic buffers (just for users)
848 * @param[in] buffers multi-buffer instance
849 * @return 0 if no error. otherwise a negative errno
852 HostHandler::deallocGenericBuffer (generic_buffers *buffers)
854 if (buffers == NULL || buffers->num_buffers < 1)
857 return deallocGenericBuffer (&buffers->bufs[0]);
861 * @brief get the current memory status
862 * @param[out] alloc_total The size of allocated memory until now
863 * @param[out] free_total The size of freed memory until now
864 * @return 0 if no error. otherwise a negatice error value
867 HostHandler::getMemoryStatus (size_t *alloc_total, size_t *free_total)
869 /** API is always set in initialize () */
870 const DriverAPI * api = device_->getDriverAPI ();
871 assert (api != nullptr);
873 return api->getMemoryStatus (alloc_total, free_total);
876 /** implement methods of Device class */
878 /** @brief constructor of device */
879 Device::Device (dev_type type, int id, bool need_model)
880 : comm_ (CommPlugin::getCommPlugin()), type_ (type), id_ (id), need_model_ (true),
881 mode_ (NPUASYNC_WAIT), initialized_ (false), atomic_flag_ (ATOMIC_FLAG_INIT)
886 * @brief create device instance depending on device type and id
887 * @param[in] type device type
888 * @param[in] id device id
889 * @return device instance
892 Device::createInstance (dev_type type, int id)
894 Device *device = nullptr;
896 switch (type & DEVICETYPE_MASK) {
897 case DEVICETYPE_TRIV:
898 device = new TrinityVision (id);
900 case DEVICETYPE_TRIV2:
901 device = new TrinityVision2 (id);
903 case DEVICETYPE_TRIA:
904 device = new TrinityAsr (id);
910 if (device != nullptr && device->init () != 0) {
919 * @brief device initialization
920 * @return 0 if no error, otherwise a negative errno
921 * @note Init failures come from createDriverAPI() only.
926 /** should be initilizaed only once */
927 if (!atomic_flag_.test_and_set()) {
928 /** create the corresponding driver API */
929 api_ = DriverAPI::createDriverAPI (type_, id_);
930 if (api_.get() == nullptr) {
931 atomic_flag_.clear();
932 logerr (TAG, "Failed to create driver API\n");
936 handler_.reset (new HostHandler (this));
937 scheduler_.reset (new Scheduler (api_.get()));
938 mem_ = MemAllocator::createInstance (api_.get());
940 initialized_ = true; /** c++11 does not provide test() of atomic flag */
947 * @brief stop all requests from this device
948 * @param[in] force_stop indicate the schedduler waits until to handle previous requests
949 * @return 0 if no error, otherwise a negative errno
952 Device::stop (bool force_stop)
954 if (!initialized ()) {
955 logerr (TAG, "Uninitialized device; should use libnpuhost APIs\n");
959 Request *req = new Request (NPUINPUT_STOP);
960 req->setForceStop (force_stop);
961 return scheduler_->submitRequest (req);
965 * @brief allocate generic memory buffer
966 * @param[in] size the size to allocate
967 * @param[out] addr the mapped address
968 * @return dmabuf fd if no error, otherwise a negative errno
971 Device::allocMemory (size_t size, void **addr)
973 if (!initialized ()) {
974 logerr (TAG, "Uninitialized device; should use libnpuhost APIs\n");
978 if (size == 0 || addr == nullptr) {
979 logerr (TAG, "Invalid arguments\n");
983 return mem_->allocMemory (size, addr);
987 * @brief deallocate generic memory buffer
988 * @param[in] dmabuf_fd dmabuf file descriptor
989 * @param[in] size buffer size
990 * @param[in] addr mapped addr
991 * @return 0 if no error, otherwise a negative errno
994 Device::deallocMemory (int dmabuf_fd, size_t size, void * addr)
996 if (!initialized ()) {
997 logerr (TAG, "Uninitialized device; should use libnpuhost APIs\n");
1001 if (dmabuf_fd < 0 || size == 0 || addr == nullptr) {
1002 logerr (TAG, "Invalid arguments\n");
1006 return mem_->deallocMemory (dmabuf_fd, size, addr);
1010 * @brief extract the buffer instance from input generic buffers
1011 * @param[in] meta the model metadata
1012 * @param[in] input the input generic buffers
1013 * @return the buffer instance
1016 TrinityVision::prepareInputBuffers (const Metadata *meta, const input_buffers *input)
1018 if (meta == nullptr || input == nullptr ||
1019 meta->getInputNum() != input->num_buffers) {
1020 logerr (TAG, "Invalid metadata info provided\n");
1025 const generic_buffer *first = &input->bufs[0];
1026 if (first->type == BUFFER_DMABUF) {
1027 buffer = mem_->allocBuffer (new HWmemExternal);
1028 if (buffer == nullptr)
1031 buffer->setDmabuf (first->dmabuf);
1032 buffer->setOffset (first->offset);
1033 buffer->setSize (meta->getBufferSize());
1035 buffer = mem_->allocBuffer (new HWmemDevice);
1036 if (buffer == nullptr)
1039 int status = buffer->alloc (meta->getBufferSize ());
1041 logerr (TAG, "Failed to allocate buffer: %d\n", status);
1047 int status = buffer->createTensors (meta);
1049 logerr (TAG, "Failed to create tensors: %d\n", status);
1058 * @brief implementation of TRIV's setModel ()
1059 * @param[in] model_buf the model generic buffer
1060 * @param[out] model the model instance
1061 * @return 0 if no error, otherwise a negative errno
1064 TrinityVision::setModel (const generic_buffer *model_buf, Model ** model_ptr)
1066 if (!initialized ()) {
1067 logerr (TAG, "Uninitialized device; should use libnpuhost APIs\n");
1071 if (model_buf == nullptr || model_ptr == nullptr)
1077 /** In TRIV1, model data (including program/weight) should be contiguous */
1079 switch (model_buf->type) {
1082 model = mem_->allocModel (new HWmemDevice);
1083 if (model == nullptr) {
1084 logerr (TAG, "Failed to allocate model\n");
1088 status = model->alloc (model_buf->size);
1090 logerr (TAG, "Failed to allocate model: %d\n", status);
1094 /** extract the whole model data */
1095 status = comm_.extractGenericBuffer (model_buf, model->getData(), nullptr);
1097 logerr (TAG, "Failed to extract generic buffer: %d\n", status);
1105 status = model->setMetadata (model->getData());
1109 /** allocate program (optional; NOP) */
1110 if (model->getMetadata()->getProgramSize() > 0) {
1111 HWmem * hwmem_prog = new HWmem (new HWmemChunk);
1112 model->setProgramData (hwmem_prog);
1114 hwmem_prog->setParent (model);
1115 hwmem_prog->setOffset (model->getMetadata()->getMetaSize());
1116 status = hwmem_prog->alloc (model->getMetadata()->getProgramSize());
1118 logerr (TAG, "Failed to allocate program\n");
1122 /** register this model to the driver */
1123 model_config_t config;
1124 config.dbuf_fd = hwmem_prog->getDmabuf ();
1125 config.program_size = hwmem_prog->getSize ();
1126 config.program_offset_addr = hwmem_prog->getOffset ();
1128 status = api_->registerModel (&config);
1132 model->setInternalID(config.id);
1135 /** allocate weight (optional) */
1136 if (model->getMetadata()->getWeightSize() > 0) {
1137 HWmem * hwmem_weight = new HWmem (new HWmemChunk);
1138 model->setWeightData (hwmem_weight);
1140 hwmem_weight->setParent (model);
1141 hwmem_weight->setOffset (model->getMetadata()->getMetaSize() +
1142 model->getMetadata()->getProgramSize());
1143 status = hwmem_weight->alloc (model->getMetadata()->getWeightSize());
1145 logerr (TAG, "Failed to allocate program\n");
1159 * @brief implementation of TRIV's unsetModel ()
1160 * @param[in] model the model instance
1161 * @return 0 if no error, otherwise a negative errno
1164 TrinityVision::unsetModel (Model * model)
1166 if (!initialized ()) {
1167 logerr (TAG, "Uninitialized device; should use libnpuhost APIs\n");
1171 if (model == nullptr) {
1172 logerr (TAG, "Invalid model instance\n");
1176 if (model->getMetadata()->getProgramSize() > 0)
1177 return api_->deregisterModel (model->getInternalID ());
1183 * @brief implementation of TRIV's run()
1184 * @param[in] opmode input opmode
1185 * @param[in] model the model instance
1186 * @param[in] input generic buffers of input data
1187 * @param[in] cb the output callback
1188 * @param[in] cb_data the output callback data
1189 * @param[out] sequence The sequence number returned with runNPU_async.
1192 TrinityVision::run (npu_input_opmode opmode, const Model *model,
1193 const input_buffers *input, npuOutputNotify cb, void *cb_data,
1196 if (!initialized ()) {
1197 logerr (TAG, "Uninitialized device; should use libnpuhost APIs\n");
1201 if (opmode != NPUINPUT_HOST) {
1202 logerr (TAG, "TRIV supports only host inputservice\n");
1206 if (model == nullptr || input == nullptr) {
1207 logerr (TAG, "TRIV requires both model and input buffers\n");
1211 Buffer *buffer = prepareInputBuffers (model->getMetadata(), input);
1212 if (buffer == nullptr) {
1213 logerr (TAG, "Failed to extract buffer instance\n");
1217 if (!buffer->isExternal ()) {
1218 for (uint32_t idx = 0; idx < input->num_buffers; idx++) {
1219 auto func = std::bind (TrinityVision::manipulateData, model, idx, true,
1220 std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
1221 int status = comm_.extractGenericBuffer (&input->bufs[idx],
1222 buffer->getInputTensor(idx)->getData(), func);
1224 logerr (TAG, "Failed to feed input buffer: %d\n", status);
1230 /** this device uses CMA buffer */
1232 Request *req = new Request (opmode);
1233 req->setModel (model);
1234 req->setBuffer (buffer);
1237 req->setCallback (std::bind (&TrinityVision::callback, this, req, cb, cb_data));
1239 if (sequence != nullptr)
1240 *sequence = req->getID();
1242 return scheduler_->submitRequest (req);
1246 * @brief callback of TRIV2 request
1247 * @param[in] req the request instance
1248 * @param[in] cb callback for completion
1249 * @param[in] cb_data callback data
1250 * @note The callback invoke does not gurantee the request was successful
1251 * @todo Check the request failures
1254 TrinityVision::callback (Request *req, npuOutputNotify cb, void *cb_data)
1256 const Model *model = req->getModel ();
1257 Buffer *buffer = req->getBuffer ();
1258 output_buffers output = {
1259 .num_buffers = buffer->getOutputNum ()
1262 for (uint32_t idx = 0; idx < output.num_buffers; idx++) {
1263 uint32_t output_tensor_size = model->getOutputTensorSize (idx);
1265 if (buffer->isExternal ()) {
1266 output.bufs[idx].type = BUFFER_DMABUF;
1267 output.bufs[idx].size = output_tensor_size;
1268 output.bufs[idx].addr = buffer->getOutputTensor(idx)->getData();
1270 output.bufs[idx].type = BUFFER_MAPPED;
1271 output.bufs[idx].size = output_tensor_size;
1272 /** user needs to free this */
1273 output.bufs[idx].addr = malloc (output_tensor_size);
1275 auto func = std::bind (TrinityVision::manipulateData, model, idx, false,
1276 std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
1277 int status = comm_.insertGenericBuffer (buffer->getOutputTensor(idx)->getData(),
1278 &output.bufs[idx], func);
1280 logerr (TAG, "Failed to return output buffer: %d\n", status);
1285 cb (&output, req->getID(), cb_data);
1291 * @brief extract the segment table instance from input generic buffers
1292 * @param[in] model the model instance
1293 * @param[in] input the input generic buffers
1294 * @return the segment table instance
1297 TrinityVision2::prepareSegmentTable (const Model *model, const input_buffers *input)
1299 if (model == nullptr || input == nullptr) {
1300 logerr (TAG, "Invalid arguments provided\n");
1304 const Metadata *meta = model->getMetadata ();
1305 if (meta == nullptr ||
1306 meta->getInputNum() != input->num_buffers) {
1307 logerr (TAG, "Invalid metadata info provided\n");
1311 SegmentTable * segt = mem_->allocSegmentTable (new HWmemDevice);
1312 int status = segt->alloc ();
1314 logerr (TAG, "Failed to allocate segment table: %d\n", status);
1318 status = segt->createSegments (model, input);
1320 logerr (TAG, "Failed to create segments: %d\n", status);
1332 * @brief implementation of TRIV2's setModel ()
1333 * @param[in] model_buf the model generic buffer
1334 * @param[out] model the model instance
1335 * @return 0 if no error, otherwise a negative errno
1338 TrinityVision2::setModel (const generic_buffer *model_buf, Model ** model_ptr)
1340 if (!initialized ()) {
1341 logerr (TAG, "Uninitialized device; should use libnpuhost APIs\n");
1345 if (model_buf == nullptr || model_ptr == nullptr)
1351 switch (model_buf->type) {
1354 model = mem_->allocModel (new HWmemDevice);
1355 if (model == nullptr) {
1356 logerr (TAG, "Failed to allocate model\n");
1360 status = model->alloc (NPUBIN_META_SIZE);
1362 logerr (TAG, "Failed to allocate model: %d\n", status);
1366 status = comm_.extractGenericBuffer (model_buf, model->getData(), nullptr,
1367 0, NPUBIN_META_SIZE);
1369 logerr (TAG, "Failed to extract generic buffer: %d\n", status);
1377 status = model->setMetadata (model->getData());
1381 /** allocate program (optional; NOP) */
1382 if (model->getMetadata()->getProgramSize() > 0) {
1383 HWmem * hwmem_prog = new HWmem (new HWmemDevice);
1384 hwmem_prog->setDriverAPI (api_.get());
1386 model->setProgramData (hwmem_prog);
1388 status = hwmem_prog->alloc (model->getMetadata()->getProgramSize());
1390 logerr (TAG, "Failed to allocate program\n");
1394 status = comm_.extractGenericBuffer (model_buf, hwmem_prog->getData(), nullptr,
1395 model->getMetadata()->getMetaSize(),
1396 model->getMetadata()->getProgramSize());
1398 logerr (TAG, "Failed to extract generic buffer: %d\n", status);
1402 /** register this model to the driver */
1403 model_config_t config;
1404 config.dbuf_fd = hwmem_prog->getDmabuf ();
1405 config.program_size = hwmem_prog->getSize ();
1406 config.program_offset_addr = 0;
1408 status = api_->registerModel (&config);
1412 model->setInternalID(config.id);
1415 /** allocate weight (optional) */
1416 if (model->getMetadata()->getWeightSize() > 0) {
1417 HWmem * hwmem_weight = new HWmem (new HWmemDevice);
1418 hwmem_weight->setDriverAPI (api_.get());
1420 model->setWeightData (hwmem_weight);
1422 status = hwmem_weight->alloc (model->getMetadata()->getWeightSize());
1424 logerr (TAG, "Failed to allocate program\n");
1428 status = comm_.extractGenericBuffer (model_buf, hwmem_weight->getData(), nullptr,
1429 model->getMetadata()->getMetaSize() + model->getMetadata()->getProgramSize(),
1430 model->getMetadata()->getWeightSize());
1432 logerr (TAG, "Failed to extract generic buffer: %d\n", status);
1446 * @brief implementation of TRIV2's unsetModel ()
1447 * @param[in] model the model instance
1448 * @return 0 if no error, otherwise a negative errno
1451 TrinityVision2::unsetModel (Model * model)
1453 if (!initialized ()) {
1454 logerr (TAG, "Uninitialized device; should use libnpuhost APIs\n");
1458 if (model == nullptr) {
1459 logerr (TAG, "Invalid model instance\n");
1463 if (model->getMetadata()->getProgramSize() > 0)
1464 return api_->deregisterModel (model->getInternalID ());
1469 /** @brief implementation of TRIV2's run() */
1471 TrinityVision2::run (npu_input_opmode opmode, const Model *model,
1472 const input_buffers *input, npuOutputNotify cb, void *cb_data,
1475 if (!initialized ()) {
1476 logerr (TAG, "Uninitialized device; should use libnpuhost APIs\n");
1480 if (opmode != NPUINPUT_HOST && opmode != NPUINPUT_HW_RECURRING)
1483 /** this device uses segment table */
1484 SegmentTable * segt = prepareSegmentTable (model, input);
1485 if (segt == nullptr) {
1486 logerr (TAG, "Failed to create segment table instance\n");
1490 /** extract input data */
1491 for (uint32_t idx = 0; idx < input->num_buffers; idx++) {
1492 if (!segt->getInputSegment(idx)->isExternal ()) {
1493 auto func = std::bind (TrinityVision2::manipulateData, model, idx, true,
1494 std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
1495 int status = comm_.extractGenericBuffer (
1497 segt->getInputSegment(idx)->getData() + segt->getInputSegmentOffset(idx),
1500 logerr (TAG, "Failed to feed input segment: %d\n", status);
1506 Request *req = new Request (opmode);
1507 req->setModel (model);
1508 req->setSegmentTable (segt);
1509 req->setCallback (std::bind (&TrinityVision2::callback, this, req, cb, cb_data));
1512 *sequence = req->getID();
1514 return scheduler_->submitRequest (req);
1517 /** @brief callback of TRIV2 request */
1519 TrinityVision2::callback (Request *req, npuOutputNotify cb, void *cb_data)
1521 const Model *model = req->getModel ();
1522 SegmentTable *segt = req->getSegmentTable ();
1523 output_buffers output = {
1524 .num_buffers = segt->getNumOutputSegments ()
1527 for (uint32_t idx = 0; idx < output.num_buffers; idx++) {
1528 uint32_t output_tensor_size = model->getOutputTensorSize (idx);
1530 output.bufs[idx].type = BUFFER_MAPPED;
1531 output.bufs[idx].size = output_tensor_size;
1532 /** user needs to free this */
1533 output.bufs[idx].addr = malloc (output_tensor_size);
1535 auto func = std::bind (TrinityVision2::manipulateData, model, idx, false,
1536 std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
1537 int status = comm_.insertGenericBuffer (
1538 segt->getOutputSegment(idx)->getData() + segt->getOutputSegmentOffset(idx),
1539 &output.bufs[idx], func);
1541 logerr (TAG, "Failed to return output buffer: %d\n", status);
1545 cb (&output, req->getID(), cb_data);
1550 /** @brief implementation of TRIA's run(): WIP */
1552 TrinityAsr::run (npu_input_opmode opmode, const Model *model,
1553 const input_buffers *input, npuOutputNotify cb, void *cb_data,
1556 if (!initialized ()) {
1557 logerr (TAG, "Uninitialized device; should use libnpuhost APIs\n");
1561 if (opmode != NPUINPUT_HOST)
1566 /** ASR does not require model and support only a single tensor */
1567 const generic_buffer *first_buf = &input->bufs[0];
1568 if (first_buf->type == BUFFER_DMABUF) {
1569 buffer = mem_->allocBuffer (new HWmemExternal);
1570 if (buffer == nullptr)
1573 buffer->setDmabuf (first_buf->dmabuf);
1574 buffer->setOffset (first_buf->offset);
1575 buffer->setSize (first_buf->size);
1577 buffer = mem_->allocBuffer (new HWmemDevice);
1578 if (buffer == nullptr)
1581 status = buffer->alloc (first_buf->size);
1588 status = buffer->createTensors ();
1590 logerr (TAG, "Failed to create tensors: %d\n", status);
1595 if (!buffer->isExternal ()) {
1596 status = comm_.extractGenericBuffer (first_buf,
1597 buffer->getInputTensor(0)->getData(), nullptr);
1602 Request *req = new Request (opmode);
1603 req->setBuffer (buffer);
1604 req->setCallback (std::bind (&TrinityAsr::callback, this, req, cb, cb_data));
1607 *sequence = req->getID();
1609 return scheduler_->submitRequest (req);
1612 /** @brief callback of TRIA request: WIP */
1614 TrinityAsr::callback (Request *req, npuOutputNotify cb, void *cb_data)
1618 /** Implement data manipulation (each device may have different impl.) */
1622 #define do_quantized_memcpy(type) do {\
1625 while (idx < num_elems) {\
1626 val = ((type *) src)[idx];\
1627 val = val / _scale;\
1628 val += _zero_point;\
1629 val = (val > 255.0) ? 255.0 : 0.0;\
1630 ((uint8_t *) dst)[idx++] = (uint8_t) val;\
1633 while (idx < num_elems) {\
1634 val = *(uint8_t *) src;\
1635 val -= _zero_point;\
1637 ((type *) dst)[idx++] = (type) val;\
1638 dst = (void*)(((uint8_t *) dst) + data_size);\
1639 src = (void*)(((uint8_t *) src) + 1);\
1645 * @brief memcpy during quantization
1647 static void memcpy_with_quant (bool quant, data_type type, float scale, uint32_t zero_point,
1648 void *dst, const void *src, uint32_t num_elems)
1650 double _scale = (double) scale;
1651 double _zero_point = (double) zero_point;
1653 uint32_t data_size = get_data_size (type);
1657 case DATA_TYPE_INT8:
1658 do_quantized_memcpy (int8_t);
1660 case DATA_TYPE_UINT8:
1661 do_quantized_memcpy (uint8_t);
1663 case DATA_TYPE_INT16:
1664 do_quantized_memcpy (int16_t);
1666 case DATA_TYPE_UINT16:
1667 do_quantized_memcpy (uint16_t);
1669 case DATA_TYPE_INT32:
1670 do_quantized_memcpy (int32_t);
1672 case DATA_TYPE_UINT32:
1673 do_quantized_memcpy (uint32_t);
1675 case DATA_TYPE_INT64:
1676 do_quantized_memcpy (int64_t);
1678 case DATA_TYPE_UINT64:
1679 do_quantized_memcpy (uint64_t);
1681 case DATA_TYPE_FLOAT32:
1682 do_quantized_memcpy (float);
1684 case DATA_TYPE_FLOAT64:
1685 do_quantized_memcpy (double);
1688 logerr (TAG, "Unsupported datatype %d\n", type);
1693 * @brief perform data manipulation
1694 * @param[in] model model instance
1695 * @param[in] idx tensor index
1696 * @param[in] is_input indicate it's input manipulation
1697 * @param[out] dst destination buffer
1698 * @param[in] src source buffer (feature map)
1699 * @param[in] size size to be copied
1700 * @return size of memory copy if no error, otherwise zero
1702 * @note the input data format should be NHWC
1703 * @detail rules for the memory address of activations in NPU HW.
1704 * (https://code.sec.samsung.net/confluence/pages/viewpage.action?pageId=146491864)
1706 * 1) Special case (depth == 3)
1707 * - addr(x,y,z) = addr(0,0,0) + (z) + 3 * (x + width * y)
1710 * - addr(x,y,z) = addr(0,0,0) + (z % MPA_L) + MPA_L * (x + width * (y + height * (z / MPA_L)))
1712 * Thus, if depth is not a multiple of MPA_L (i.e., 64), zero padding is required
1715 TrinityVision::manipulateData (const Model *model, uint32_t idx, bool is_input,
1716 void *dst, void *src, size_t size)
1718 const Metadata *meta = model->getMetadata();
1719 const tensor_data_info* info;
1720 const uint32_t *dims;
1721 uint32_t zero_point;
1724 /** extract required information from the metadata */
1726 if (idx >= meta->getInputNum()) {
1727 logerr (TAG, "Wrong information for input tensors in metadata\n");
1731 info = model->getInputDataInfo (idx);
1732 dims = meta->getInputDims (idx);
1733 zero_point = meta->getInputQuantZero (idx);
1734 scale = meta->getInputQuantScale (idx);
1736 if (idx >= meta->getOutputNum()) {
1737 logerr (TAG, "Wrong information for output tensors in metadata\n");
1741 info = model->getOutputDataInfo (idx);
1742 dims = meta->getOutputDims (idx);
1743 zero_point = meta->getOutputQuantZero (idx);
1744 scale = meta->getOutputQuantScale (idx);
1747 if (info == nullptr) {
1748 logerr (TAG, "Unmatched tensors info\n");
1752 uint32_t batch = dims[0];
1753 uint32_t height = dims[1];
1754 uint32_t width = dims[2];
1755 uint32_t depth = dims[3];
1757 uint32_t data_size = get_data_size (info->type);
1758 if (data_size == 0) {
1759 logerr (TAG, "Invalid data size\n");
1763 bool need_quantization = false;
1765 * note that we assume DATA_TYPE_SRNPU is the smallest data type that we consider.
1766 * Also, DATA_TYPE_SRNPU and uint8_t may be regarded as the same in the view of apps.
1768 if (info->type != DATA_TYPE_SRNPU) {
1769 assert (data_size >= get_data_size (DATA_TYPE_SRNPU));
1771 if (data_size > get_data_size (DATA_TYPE_SRNPU) ||
1772 !(zero_point == default_quant_zero && scale == default_quant_scale))
1773 need_quantization = true;
1776 /** check data manipulation is required */
1777 if (depth != 3 && depth != 64 && info->layout != DATA_LAYOUT_SRNPU) {
1778 uint32_t MPA_L = DATA_GRANULARITY;
1779 uint32_t n, h, w, d;
1780 uint32_t std_offset; /* standard offset in NHWC data format */
1781 uint32_t npu_offset; /* npu offset in NPU HW data format*/
1782 uint32_t src_offset;
1783 uint32_t dst_offset;
1784 uint32_t slice_size;
1786 /* @todo we currently support only NHWC */
1787 if (info->layout != DATA_LAYOUT_NHWC) {
1788 logerr (TAG, "data manipulation is supported for NHWC only\n");
1792 for (n = 0; n < batch; n++) {
1793 for (h = 0; h < height; h++) {
1794 for (w = 0; w < width; w++) {
1795 for (d = 0; d < depth; d += MPA_L) {
1796 std_offset = d + depth * (w + width * (h + n * height));
1797 npu_offset = MPA_L * (w + width * (h + (n + d / MPA_L) * height));
1798 slice_size = (depth - d >= MPA_L) ? MPA_L : depth - d;
1801 src_offset = std_offset * data_size;
1802 dst_offset = npu_offset;
1804 src_offset = npu_offset;
1805 dst_offset = std_offset * data_size;
1808 /* if depth is not a multiple of MPA_L, add zero paddings (not exact values) */
1809 if (need_quantization) {
1810 memcpy_with_quant (is_input, info->type, scale, zero_point,
1811 static_cast<char*>(dst) + dst_offset,
1812 static_cast<char*>(src) + src_offset,
1816 static_cast<char*>(dst) + dst_offset,
1817 static_cast<char*>(src) + src_offset,
1824 } else if (need_quantization) {
1825 /** depth == 3 || depth == 64; special cases which can directly copy input tensor data */
1826 memcpy_with_quant (is_input, info->type, scale, zero_point,
1827 dst, src, is_input ? size / data_size : size);
1829 memcpy (dst, src, size);
1838 TrinityVision::manipulateData (const Model *model, uint32_t idx, bool is_input,
1839 void *dst, void *src, size_t size)
1841 memcpy (dst, src, size);
1847 /** other device types don't have data manip impl. yet */
1850 TrinityVision2::manipulateData (const Model *model, uint32_t idx, bool is_input,
1851 void *dst, void *src, size_t size)
1853 memcpy (dst, src, size);
1858 TrinityAsr::manipulateData (const Model *model, uint32_t idx, bool is_input,
1859 void *dst, void *src, size_t size)
1861 memcpy (dst, src, size);