3 * Copyright (C) 2020 Samsung Electronics
4 * Copyright (C) 2020 Dongju Chae <dongju.chae@samsung.com>
7 * @file ne-host-handler.cc
9 * @brief Implementation of APIs to access NPU from Host
10 * @see https://code.sec.samsung.net/confluence/display/ODLC/2020+Overall+Software+Stack
11 * @author Dongju Chae <dongju.chae@samsung.com>
12 * @bug No known bugs except for NYI items
15 #include "ne-handler.h"
17 #include <libnpuhost.h>
18 #include <npubinfmt.h>
19 #include <NPUdrvAPI.h>
20 #include <CommPlugin.h>
25 #include <condition_variable>
32 #define INIT_HOST_HANDLER(handler, dev) \
33 Device *tdev = static_cast <Device *> (dev); \
34 if (tdev == nullptr) return -EINVAL; \
35 HostHandler *handler = tdev->getHostHandler (); \
36 if (handler == nullptr) return -EINVAL;
38 /** just for backward-compatability */
39 npudev_h HostHandler::latest_dev_ = nullptr;
41 /** implement libnpuhost APIs */
44 * @brief Returns the number of available NPU devices.
45 * @return @c The number of NPU devices.
46 * @retval 0 if no NPU devices available. if positive (number of NPUs) if NPU devices available. otherwise, a negative error value.
47 * @note the caller should call putNPUdevice() to release the device handle
49 int getnumNPUdeviceByType (dev_type type)
51 return HostHandler::getNumDevices (type);
55 * @brief Returns the handle of the chosen NPU devices.
56 * @param[out] dev The NPU device handle
57 * @param[in] id The NPU id to get the handle. 0 <= id < getnumNPUdeviceByType().
58 * @return @c 0 if no error. otherwise a negative error value
59 * @note the caller should call putNPUdevice() to release the device handle
61 int getNPUdeviceByType (npudev_h *dev, dev_type type, uint32_t id)
63 return HostHandler::getDevice (dev, type, id);
67 * @brief release the NPU device instance obtained by getDevice ()
68 * @param[in] dev the NPU device handle
70 void putNPUdevice (npudev_h dev)
73 delete static_cast<Device *> (dev);
77 * @brief Send the NN model to NPU.
78 * @param[in] dev The NPU device handle
79 * @param[in] modelfile The filepath to the compiled NPU NN model in any buffer_type
80 * @param[out] modelid The modelid allocated for this instance of NN model.
81 * @return @c 0 if no error. otherwise a negative error value
83 * @detail For ASR devices, which do not accept models, but have models
84 * embedded in devices, you do not need to call register and
85 * register calls for ASR are ignored.
87 * @todo Add a variation: in-memory model register.
89 int registerNPUmodel (npudev_h dev, generic_buffer *modelfile, uint32_t *modelid)
91 INIT_HOST_HANDLER (host_handler, dev);
93 return host_handler->registerModel (modelfile, modelid);
97 * @brief Remove the NN model from NPU
98 * @param[in] dev The NPU device handle
99 * @param[in] modelid The model to be removed from the NPU.
100 * @return @c 0 if no error. otherwise a negative error value
101 * @detail This may incur some latency with memory compatcion.
103 int unregisterNPUmodel(npudev_h dev, uint32_t modelid)
105 INIT_HOST_HANDLER (host_handler, dev);
107 return host_handler->unregisterModel (modelid);
111 * @brief Remove all NN models from NPU
112 * @param[in] dev The NPU device handle
113 * @return @c 0 if no error. otherwise a negative error value
115 int unregisterNPUmodel_all(npudev_h dev)
117 INIT_HOST_HANDLER (host_handler, dev);
119 return host_handler->unregisterModels ();
123 * @brief [OPTIONAL] Set the data layout for input/output tensors
124 * @param[in] dev The NPU device handle
125 * @param[in] modelid The ID of model whose layouts are set
126 * @param[in] info_in the layout/type info for input tensors
127 * @param[in] info_out the layout/type info for output tensors
128 * @return @c 0 if no error. otherwise a negative error value
129 * @note if this function is not called, default layout/type will be used.
131 int setNPU_dataInfo(npudev_h dev, uint32_t modelid,
132 tensors_data_info *info_in, tensors_data_info *info_out)
134 INIT_HOST_HANDLER (host_handler, dev);
136 return host_handler->setDataInfo (modelid, info_in, info_out);
140 * @brief [OPTIONAL] Set the inference constraint for next NPU inferences
141 * @param[in] dev The NPU device handle
142 * @param[in] modelid The target model id
143 * @param[in] constraint inference constraint (e.g., timeout, priority)
144 * @return @c 0 if no error. otherwise a negative error value
145 * @note If this function is not called, default values are used.
147 int setNPU_constraint(npudev_h dev, uint32_t modelid, npuConstraint constraint)
149 INIT_HOST_HANDLER (host_handler, dev);
151 return host_handler->setConstraint (modelid, constraint);
155 * @brief Execute inference. Wait (block) until the output is available.
156 * @param[in] dev The NPU device handle
157 * @param[in] modelid The model to be inferred.
158 * @param[in] input The input data to be inferred.
159 * @param[out] output The output result. The caller MUST allocate appropriately before calling this.
160 * @return @c 0 if no error. otherwise a negative error value
162 * @detail This is a syntactic sugar of runNPU_async().
163 * CAUTION: There is a memcpy for the output buffer.
165 int runNPU_sync(npudev_h dev, uint32_t modelid, const input_buffers *input,
166 output_buffers *output)
168 INIT_HOST_HANDLER (host_handler, dev);
170 return host_handler->runSync (modelid, input, output);
174 * @brief Invoke NPU inference. Unblocking call.
175 * @param[in] dev The NPU device handle
176 * @param[in] modelid The model to be inferred.
177 * @param[in] input The input data to be inferred.
178 * @param[in] cb The output buffer handler.
179 * @param[out] sequence The sequence number returned with runNPU_async.
180 * @param[in] data The data given as a parameter to the runNPU_async call.
181 * @param[in] mode Configures how this operation works.
182 * @return @c 0 if no error. otherwise a negative error value
184 int runNPU_async(npudev_h dev, uint32_t modelid, const input_buffers *input,
185 npuOutputNotify cb, uint64_t *sequence, void *data,
188 INIT_HOST_HANDLER (host_handler, dev);
190 return host_handler->runAsync (modelid, input, cb, data, mode, sequence);
194 * @brief Let NPU accept input frames from its internal source continuously
195 * @param[in] dev The NPU device handle
196 * @param[in] modelid The model to be inferred.
197 * @param[in] opmode NPU has different opmode with auto-inputs. Choose one.
198 * @param[in] hw_dev The target device feeding input data
199 * @return @c 0 if no error. otherwise a negative error value
201 int runNPU_internalInput(npudev_h dev, uint32_t modelid, npu_input_opmode opmode,
204 INIT_HOST_HANDLER (host_handler, dev);
206 return host_handler->runInternal (modelid, opmode, hw_dev);
210 * @brief Stop the request with the given id
211 * @param[in] dev The NPU device handle
212 * @param[in] id The request id
213 * @return @c 0 if no error. otherwise a negative error value
215 int stopNPU_internalInput(npudev_h dev, int id)
217 INIT_HOST_HANDLER (host_handler, dev);
219 return host_handler->stopInternal (id);
223 * @brief Allocate a generic buffer with the requested buffer type.
224 * @param[in] dev The NPU device handle
225 * @param[in/out] Buffer the buffer pointer where memory is allocated.
226 * @return 0 if no error, otherwise a negative errno.
228 int allocNPU_genericBuffer (npudev_h dev, generic_buffer * buffer)
230 INIT_HOST_HANDLER (host_handler, dev);
232 return host_handler->allocGenericBuffer (buffer);
236 * @brief Free the generic buffer and remove the address mapping
237 * @param[in] dev The NPU device handle
238 * @param[in] buffer the model buffer
239 * @return 0 if no error, otherwise a negative errno.
241 int cleanNPU_genericBuffer (npudev_h dev, generic_buffer * buffer)
243 INIT_HOST_HANDLER (host_handler, dev);
245 return host_handler->deallocGenericBuffer (buffer);
249 * @brief Allocate generic buffers, which have multiple instances of generic_buffer
250 * @param[in] dev The NPU device handle
251 * @param[in/out] buffers generic buffers.
252 * @return 0 if no error, otherwise a negative errno.
253 * @note it reuses allocGenericBuffer().
255 int allocNPU_genericBuffers (npudev_h dev, generic_buffers * buffers)
257 INIT_HOST_HANDLER (host_handler, dev);
259 return host_handler->allocGenericBuffer (buffers);
263 * @brief Free generic buffers allocated by allocGenericBuffers().
264 * @param[in] dev The NPU device handle
265 * @param[in/out] buffers generic buffers.
266 * @note it reuses cleanGenericbuffer().
267 * @return 0 if no error, otherwise a negative errno.
269 int cleanNPU_genericBuffers (npudev_h dev, generic_buffers * buffers)
271 INIT_HOST_HANDLER (host_handler, dev);
273 return host_handler->deallocGenericBuffer (buffers);
277 * @brief alias of allocNPU_genericBuffer for model buffer
279 int allocNPU_modelBuffer (npudev_h dev, generic_buffer * model)
281 return allocNPU_genericBuffer (dev, model);
285 * @brief alias of cleanNPU_genericBuffer for model buffer
287 int cleanNPU_modelBuffer (npudev_h dev, generic_buffer * model)
289 return cleanNPU_genericBuffer (dev, model);
293 * @brief alias of allocNPU_genericBuffer for input buffer
295 int allocNPU_inputBuffer (npudev_h dev, generic_buffer * input)
297 return allocNPU_genericBuffer (dev, input);
301 * @brief alias of cleanNPU_genericBuffer for input buffer
303 int cleanNPU_inputBuffer (npudev_h dev, generic_buffer * input)
305 return cleanNPU_genericBuffer (dev, input);
309 * @brief alias of allocNPU_genericBuffers for input buffers
311 int allocNPU_inputBuffers (npudev_h dev, input_buffers * input)
313 return allocNPU_genericBuffers (dev, input);
317 * @brief alias of cleanNPU_genericBuffers for input buffers
319 int cleanNPU_inputBuffers (npudev_h dev, input_buffers * input)
321 return cleanNPU_genericBuffers (dev, input);
325 * @brief get the current memory status for the given device
326 * @param[in] dev The NPU device handle
327 * @param[out] alloc_total The size of allocated memory until now
328 * @param[out] free_total The size of freed memory until now
329 * @return @c 0 if no error. otherwise a negatice error value
331 int getNPU_memoryStatus(npudev_h dev, size_t *alloc_total, size_t *free_total)
333 INIT_HOST_HANDLER (host_handler, dev);
335 return host_handler->getMemoryStatus (alloc_total, free_total);
339 * @brief Get the current device status to be used
340 * @param[in] dev The NPU device handle
341 * @param[out] status the device status
342 * @param[out] num_requests the number of running requests (or pending)
343 * @return 0 if no error, otherwise a negative errno.
345 int getNPU_deviceStatus(npudev_h dev, npu_status *status, uint32_t *num_requests)
347 INIT_HOST_HANDLER (host_handler, dev);
349 return host_handler->getDeviceStatus (status, num_requests);
353 * @brief Get metadata for NPU model
354 * @param[in] model The path of model binary file
355 * @param[in] need_extra whether you want to extract the extra data in metadata
356 * @return the metadata structure to be filled if no error, otherwise nullptr
358 * @note For most npu-engine users, the extra data is not useful because it will be
359 * used for second-party users (e.g., compiler, simulator).
360 * Also, the caller needs to free the metadata.
362 * @note the caller needs to free the metadata
364 npubin_meta * getNPUmodel_metadata (const char *model, bool need_extra)
373 fp = fopen (model, "rb");
375 logerr (TAG, "Failed to open the model binary: %d\n", -errno);
379 meta = (npubin_meta *) malloc (NPUBIN_META_SIZE);
381 logerr (TAG, "Failed to allocate metadata\n");
385 ret = fread (meta, 1, NPUBIN_META_SIZE, fp);
386 if (ret != NPUBIN_META_SIZE) {
387 logerr (TAG, "Failed to read the metadata\n");
391 if (!CHECK_NPUBIN (meta->magiccode)) {
392 logerr (TAG, "Invalid metadata provided\n");
396 if (need_extra && NPUBIN_META_EXTRA (meta->magiccode) > 0) {
397 npubin_meta *new_meta;
399 new_meta = (npubin_meta *) realloc (meta, NPUBIN_META_TOTAL_SIZE(meta->magiccode));
401 logerr (TAG, "Failed to allocate extra metadata\n");
405 ret = fread (new_meta->reserved_extra, 1, NPUBIN_META_EXTRA_SIZE (meta->magiccode), fp);
406 if (ret != NPUBIN_META_EXTRA_SIZE (meta->magiccode)) {
407 logerr (TAG, "Invalid extra metadata provided\n");
427 /** implement methods of HostHandler class */
429 /** @brief host handler constructor */
430 HostHandler::HostHandler (Device *device)
432 /* ignored as we don't use double buffering anymore, but for backward-compatibility */
433 async_mode_ (NPUASYNC_WAIT)
437 /** @brief host handler destructor */
438 HostHandler::~HostHandler ()
443 * @brief register model from generic buffer
444 * @param[in] model_buf model buffer
445 * @param[out] modelid model id
446 * @return 0 if no error. otherwise a negative errno
449 HostHandler::registerModel (generic_buffer *model_buf, uint32_t *modelid)
451 if (model_buf == nullptr || modelid == nullptr) {
452 logerr (TAG, "Invalid arguments given\n");
456 Model *model = nullptr;
457 int status = device_->setModel (model_buf, &model);
459 logerr (TAG, "Failed to set model: %d\n", status);
463 assert (model != nullptr);
465 status = models_.insert (model->getID(), model);
467 logerr (TAG, "Failed to insert model id\n");
472 *modelid = model->getID();
477 * @brief remove the registered model
478 * @param[in] modelid model id
479 * @return 0 if no error. otherwise a negative errno
482 HostHandler::unregisterModel (uint32_t modelid)
484 Model *model = models_.find (modelid);
485 if (model == nullptr)
488 int status = device_->unsetModel (model);
490 logerr (TAG, "Failed to unset model: %d\n", status);
494 return models_.remove (modelid);
498 * @brief remove all registered models
502 HostHandler::unregisterModels ()
509 * @brief Set the data layout for input/output tensors
510 * @param[in] modelid The ID of model whose layouts are set
511 * @param[in] in the layout/type info for input tensors
512 * @param[in] out the layout/type info for output tensors
513 * @return @c 0 if no error. otherwise a negative error value
514 * @note if this function is not called, default layout/type will be used.
517 HostHandler::setDataInfo (uint32_t modelid, tensors_data_info *in,
518 tensors_data_info *out)
520 Model *model = models_.find (modelid);
521 if (model == nullptr)
524 return model->setDataInfo (in, out);
528 * @brief Set the inference constraint for next NPU inferences
529 * @param[in] modelid The target model id
530 * @param[in] constraint inference constraint (e.g., timeout, priority)
531 * @return @c 0 if no error. otherwise a negative error value
532 * @note If this function is not called, default values are used.
535 HostHandler::setConstraint (uint32_t modelid, npuConstraint constraint)
537 Model *model = models_.find (modelid);
538 if (model == nullptr)
541 model->setConstraint (constraint);
547 * @brief find and return model instance
548 * @param[in] modelid model id
549 * @return model instance if found. otherwise nullptr
552 HostHandler::getModel (uint32_t modelid)
554 return models_.find (modelid);
557 /** @brief dummay callback for runSync. */
560 callbackSync (output_buffers *output) : output_(output), done_(false) {}
562 static void callback (output_buffers *output, uint64_t sequence, void *data) {
563 callbackSync *sync = static_cast<callbackSync *>(data);
564 sync->callback (output, sequence);
567 void callback (output_buffers *output, uint64_t sequence) {
568 if (output_ != nullptr) {
569 /** just copy internal variables of output buffers */
570 memcpy (output_, output, sizeof (output_buffers));
577 std::unique_lock<std::mutex> lock (m_);
578 cv_.wait (lock, [this]() { return done_; });
583 std::condition_variable cv_;
584 output_buffers *output_;
589 * @brief Execute inference. Wait (block) until the output is available.
590 * @param[in] modelid The model to be inferred.
591 * @param[in] input The input data to be inferred.
592 * @param[out] output The output result.
593 * @return @c 0 if no error. otherwise a negative error value
596 HostHandler::runSync (uint32_t modelid, const input_buffers *input,
597 output_buffers *output)
599 callbackSync sync (output);
600 int status = runAsync (modelid, input, callbackSync::callback,
601 static_cast <void*> (&sync), NPUASYNC_DROP_OLD, nullptr);
603 /** sync needs to wait callback */
610 * @brief Invoke NPU inference. Unblocking call.
611 * @param[in] modelid The model to be inferred.
612 * @param[in] input The input data to be inferred.
613 * @param[in] cb The output buffer handler.
614 * @param[in] cb_data The data given as a parameter to the runNPU_async call.
615 * @param[in] mode Configures how this operation works.
616 * @param[out] sequence The sequence number returned with runNPU_async.
617 * @return @c 0 if no error. otherwise a negative error value
620 HostHandler::runAsync (uint32_t modelid, const input_buffers *input,
621 npuOutputNotify cb, void *cb_data, npu_async_mode mode, uint64_t *sequence)
623 Model *model = nullptr;
625 if (device_->needModel()) {
626 model = getModel (modelid);
627 if (model == nullptr)
631 /* check the given model before running */
632 if (model != nullptr && !model->finalize ()) {
633 logerr (TAG, "Failed to finalize the model. Please see the log messages\n");
637 device_->setAsyncMode (mode);
638 return device_->run (NPUINPUT_HOST, model, input, cb, cb_data, sequence);
642 * @brief Let NPU accept input frames from its internal source continuously
643 * @param[in] modelid The model to be inferred.
644 * @param[in] opmode NPU has different opmode with auto-inputs. Choose one.
645 * @param[in] hw_dev The target device feeding input data
646 * @return @c 0 if no error. otherwise a negative error value
649 HostHandler::runInternal (uint32_t modelid, npu_input_opmode opmode,
652 Model *model = nullptr;
654 if (device_->needModel()) {
655 model = getModel (modelid);
656 if (model == nullptr)
660 /* check the given model before running */
661 if (model != nullptr && !model->finalize ()) {
662 logerr (TAG, "Failed to finalize the model. Please see the log messages\n");
666 return device_->runInternal (opmode, model, hw_dev);
670 * @brief Stop the request with the given id
671 * @param[in] dev The NPU device handle
672 * @param[in] id The request id
673 * @return @c 0 if no error. otherwise a negative error value
676 HostHandler::stopInternal (int id)
679 logerr (TAG, "Unable to stop this request with id (%d)\n", id);
683 const DriverAPI * api = device_->getDriverAPI ();
684 assert (api != nullptr);
686 return api->stop_target (id);
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)
760 /* now, npu-engine always provides dmabuf-based allocation */
761 void *addr = nullptr;
762 int dmabuf = device_->allocMemory (buffer->size, &addr);
766 buffer->dmabuf = dmabuf;
778 * @brief deallocate generic buffer (just for users)
779 * @param[in] buffer buffer instance
780 * @return 0 if no error. otherwise a negative errno
783 HostHandler::deallocGenericBuffer (generic_buffer *buffer)
788 switch (buffer->type) {
790 /** always true cuz nothing to do */
793 return device_->deallocMemory (buffer->dmabuf, buffer->size, buffer->addr);
802 * @brief allocate multiple generic buffers (just for users)
803 * @param[out] buffers multi-buffer instance
804 * @return 0 if no error. otherwise a negative errno
807 HostHandler::allocGenericBuffer (generic_buffers *buffers)
812 if (buffers == NULL || buffers->num_buffers < 1)
815 for (idx = 0; idx < buffers->num_buffers; idx++) {
816 status = allocGenericBuffer (&buffers->bufs[idx]);
825 deallocGenericBuffer (&buffers->bufs[--idx]);
832 * @brief deallocate multiple generic buffers (just for users)
833 * @param[in] buffers multi-buffer instance
834 * @return 0 if no error. otherwise a negative errno
837 HostHandler::deallocGenericBuffer (generic_buffers *buffers)
839 if (buffers == NULL || buffers->num_buffers < 1)
842 for (uint32_t idx = 0; idx < buffers->num_buffers; idx++)
843 deallocGenericBuffer (&buffers->bufs[idx]);
844 buffers->num_buffers = 0;
850 * @brief get the current memory status
851 * @param[out] alloc_total The size of allocated memory until now
852 * @param[out] free_total The size of freed memory until now
853 * @return 0 if no error. otherwise a negatice error value
856 HostHandler::getMemoryStatus (size_t *alloc_total, size_t *free_total)
858 /** API is always set in initialize () */
859 const DriverAPI * api = device_->getDriverAPI ();
860 assert (api != nullptr);
862 return api->getMemoryStatus (alloc_total, free_total);
866 * @brief Get the current device status to be used
867 * @param[out] status the device status
868 * @param[out] num_requests the number of running requests (or pending)
869 * @return 0 if no error, otherwise a negative errno.
872 HostHandler::getDeviceStatus (npu_status *status, uint32_t *num_requests)
874 /** API is always set in initialize () */
875 const DriverAPI * api = device_->getDriverAPI ();
876 assert (api != nullptr);
878 device_state_t state = api->isReady ();
879 if (state == device_state_t::STATE_READY) {
880 *num_requests = api->numRequests ();
881 if (*num_requests > 0)
893 /** implement methods of Device class */
895 /** @brief constructor of device */
896 Device::Device (dev_type type, int id, bool need_model)
897 : comm_ (CommPlugin::getCommPlugin()), type_ (type), id_ (id), need_model_ (true),
898 mode_ (NPUASYNC_WAIT), initialized_ (false), atomic_flag_ (ATOMIC_FLAG_INIT)
903 * @brief create device instance depending on device type and id
904 * @param[in] type device type
905 * @param[in] id device id
906 * @return device instance
909 Device::createInstance (dev_type type, int id)
911 Device *device = nullptr;
913 switch (type & DEVICETYPE_MASK) {
914 case DEVICETYPE_TRIV:
915 device = new TrinityVision (id);
917 case DEVICETYPE_TRIV2:
918 device = new TrinityVision2 (id);
920 case DEVICETYPE_TRIA:
921 device = new TrinityAsr (id);
927 if (device != nullptr && device->init () != 0) {
936 * @brief device initialization
937 * @return 0 if no error, otherwise a negative errno
938 * @note Init failures come from createDriverAPI() only.
943 /** should be initilizaed only once */
944 if (!atomic_flag_.test_and_set()) {
945 /** create the corresponding driver API */
946 api_ = DriverAPI::createDriverAPI (type_, id_);
947 if (api_.get() == nullptr) {
948 atomic_flag_.clear();
949 logerr (TAG, "Failed to create driver API\n");
953 handler_.reset (new HostHandler (this));
954 scheduler_.reset (new Scheduler (api_.get()));
955 mem_ = MemAllocator::createInstance (api_.get());
957 initialized_ = true; /** c++11 does not provide test() of atomic flag */
964 * @brief stop all requests from this device
965 * @param[in] force_stop indicate the schedduler waits until to handle previous requests
966 * @return 0 if no error, otherwise a negative errno
969 Device::stop (bool force_stop)
971 if (!initialized ()) {
972 logerr (TAG, "Uninitialized device; should use libnpuhost APIs\n");
976 Request *req = new Request (NPUINPUT_STOP);
977 req->setForceStop (force_stop);
978 return scheduler_->submitRequest (req);
982 * @brief allocate generic memory buffer
983 * @param[in] size the size to allocate
984 * @param[out] addr the mapped address
985 * @return dmabuf fd if no error, otherwise a negative errno
988 Device::allocMemory (size_t size, void **addr)
990 if (!initialized ()) {
991 logerr (TAG, "Uninitialized device; should use libnpuhost APIs\n");
995 if (size == 0 || addr == nullptr) {
996 logerr (TAG, "Invalid arguments\n");
1000 return mem_->allocMemory (size, addr);
1004 * @brief deallocate generic memory buffer
1005 * @param[in] dmabuf_fd dmabuf file descriptor
1006 * @param[in] size buffer size
1007 * @param[in] addr mapped addr
1008 * @return 0 if no error, otherwise a negative errno
1011 Device::deallocMemory (int dmabuf_fd, size_t size, void * addr)
1013 if (!initialized ()) {
1014 logerr (TAG, "Uninitialized device; should use libnpuhost APIs\n");
1018 if (dmabuf_fd < 0 || size == 0 || addr == nullptr) {
1019 logerr (TAG, "Invalid arguments\n");
1023 return mem_->deallocMemory (dmabuf_fd, size, addr);
1027 * @brief extract the buffer instance from input generic buffers
1028 * @param[in] meta the model metadata
1029 * @param[in] input the input generic buffers
1030 * @return the buffer instance
1033 TrinityVision::prepareInputBuffers (const Metadata *meta, const input_buffers *input)
1035 if (meta == nullptr || input == nullptr ||
1036 meta->getInputNum() != input->num_buffers) {
1037 logerr (TAG, "Invalid metadata info provided\n");
1042 const generic_buffer *first = &input->bufs[0];
1043 if (first->type == BUFFER_DMABUF) {
1044 buffer = mem_->allocBuffer (new HWmemExternal);
1045 if (buffer == nullptr)
1048 buffer->setDmabuf (first->dmabuf);
1049 buffer->setOffset (first->offset);
1050 buffer->setSize (meta->getBufferSize());
1052 buffer = mem_->allocBuffer (new HWmemDevice);
1053 if (buffer == nullptr)
1056 int status = buffer->alloc (meta->getBufferSize ());
1058 logerr (TAG, "Failed to allocate buffer: %d\n", status);
1064 int status = buffer->createTensors (meta);
1066 logerr (TAG, "Failed to create tensors: %d\n", status);
1075 * @brief implementation of TRIV's setModel ()
1076 * @param[in] model_buf the model generic buffer
1077 * @param[out] model the model instance
1078 * @return 0 if no error, otherwise a negative errno
1081 TrinityVision::setModel (const generic_buffer *model_buf, Model ** model_ptr)
1083 if (!initialized ()) {
1084 logerr (TAG, "Uninitialized device; should use libnpuhost APIs\n");
1088 if (model_buf == nullptr || model_ptr == nullptr)
1091 Model *model = nullptr;
1092 HWmem * hwmem_prog = nullptr;
1093 HWmem * hwmem_weight = nullptr;
1096 /** In TRIV1, model data (including program/weight) should be contiguous */
1098 switch (model_buf->type) {
1101 model = mem_->allocModel (new HWmemDevice);
1102 if (model == nullptr) {
1103 logerr (TAG, "Failed to allocate model\n");
1107 status = model->alloc (model_buf->size);
1109 logerr (TAG, "Failed to allocate model: %d\n", status);
1113 /** extract the whole model data */
1114 status = comm_.extractGenericBuffer (model_buf, model->getData(), nullptr);
1116 logerr (TAG, "Failed to extract generic buffer: %d\n", status);
1124 status = model->setMetadata (model->getData());
1128 /** allocate program (optional; NOP) */
1129 if (model->getMetadata()->getProgramSize() > 0) {
1130 hwmem_prog = new HWmem (new HWmemChunk);
1131 model->setProgramData (hwmem_prog);
1133 hwmem_prog->setParent (model);
1134 hwmem_prog->setOffset (model->getMetadata()->getMetaSize());
1135 status = hwmem_prog->alloc (model->getMetadata()->getProgramSize());
1137 logerr (TAG, "Failed to allocate program\n");
1142 /** allocate weight (optional) */
1143 if (model->getMetadata()->getWeightSize() > 0) {
1144 hwmem_weight = new HWmem (new HWmemChunk);
1145 model->setWeightData (hwmem_weight);
1147 hwmem_weight->setParent (model);
1148 hwmem_weight->setOffset (model->getMetadata()->getMetaSize() +
1149 model->getMetadata()->getProgramSize());
1150 status = hwmem_weight->alloc (model->getMetadata()->getWeightSize());
1152 logerr (TAG, "Failed to allocate program\n");
1157 if (hwmem_prog != nullptr) {
1158 /** register this model to the driver */
1159 model_config_t config;
1160 config.dbuf_fd = hwmem_prog->getDmabuf ();
1161 config.program_size = hwmem_prog->getSize ();
1162 config.program_offset_addr = hwmem_prog->getOffset ();
1163 if (hwmem_weight != nullptr)
1164 config.weight_offset_addr = hwmem_weight->getOffset ();
1166 status = api_->registerModel (&config);
1170 model->setInternalID(config.id);
1182 * @brief implementation of TRIV's unsetModel ()
1183 * @param[in] model the model instance
1184 * @return 0 if no error, otherwise a negative errno
1187 TrinityVision::unsetModel (Model * model)
1189 if (!initialized ()) {
1190 logerr (TAG, "Uninitialized device; should use libnpuhost APIs\n");
1194 if (model == nullptr) {
1195 logerr (TAG, "Invalid model instance\n");
1199 if (model->getMetadata()->getProgramSize() > 0)
1200 return api_->deregisterModel (model->getInternalID ());
1206 * @brief implementation of TRIV's run()
1207 * @param[in] opmode input opmode
1208 * @param[in] model the model instance
1209 * @param[in] input generic buffers of input data
1210 * @param[in] cb the output callback
1211 * @param[in] cb_data the output callback data
1212 * @param[out] sequence The sequence number returned with runNPU_async.
1215 TrinityVision::run (npu_input_opmode opmode, const Model *model,
1216 const input_buffers *input, npuOutputNotify cb, void *cb_data,
1219 if (!initialized ()) {
1220 logerr (TAG, "Uninitialized device; should use libnpuhost APIs\n");
1224 if (opmode != NPUINPUT_HOST) {
1225 logerr (TAG, "TRIV supports only host inputservice\n");
1229 if (model == nullptr || input == nullptr) {
1230 logerr (TAG, "TRIV requires both model and input buffers\n");
1234 Buffer *buffer = prepareInputBuffers (model->getMetadata(), input);
1235 if (buffer == nullptr) {
1236 logerr (TAG, "Failed to extract buffer instance\n");
1240 if (!buffer->isExternal ()) {
1241 for (uint32_t idx = 0; idx < input->num_buffers; idx++) {
1242 auto func = std::bind (TrinityVision::manipulateData, model, idx, true,
1243 std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
1244 int status = comm_.extractGenericBuffer (&input->bufs[idx],
1245 buffer->getInputTensor(idx)->getData(), func);
1247 logerr (TAG, "Failed to feed input buffer: %d\n", status);
1253 /** this device uses CMA buffer */
1255 Request *req = new Request (opmode);
1256 req->setModel (model);
1257 req->setBuffer (buffer);
1260 req->setCallback (std::bind (&TrinityVision::callback, this, req, cb, cb_data));
1262 if (sequence != nullptr)
1263 *sequence = req->getID();
1265 return scheduler_->submitRequest (req);
1269 * @brief callback of TRIV2 request
1270 * @param[in] req the request instance
1271 * @param[in] cb callback for completion
1272 * @param[in] cb_data callback data
1273 * @note The callback invoke does not gurantee the request was successful
1274 * @todo Check the request failures
1277 TrinityVision::callback (Request *req, npuOutputNotify cb, void *cb_data)
1279 const Model *model = req->getModel ();
1280 Buffer *buffer = req->getBuffer ();
1281 output_buffers output = {
1282 .num_buffers = buffer->getOutputNum ()
1285 for (uint32_t idx = 0; idx < output.num_buffers; idx++) {
1286 uint32_t output_tensor_size = model->getOutputTensorSize (idx);
1288 if (buffer->isExternal ()) {
1289 output.bufs[idx].type = BUFFER_DMABUF;
1290 output.bufs[idx].size = output_tensor_size;
1291 output.bufs[idx].addr = buffer->getOutputTensor(idx)->getData();
1293 output.bufs[idx].type = BUFFER_MAPPED;
1294 output.bufs[idx].size = output_tensor_size;
1295 /** user needs to free this */
1296 output.bufs[idx].addr = malloc (output_tensor_size);
1298 auto func = std::bind (TrinityVision::manipulateData, model, idx, false,
1299 std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
1300 int status = comm_.insertGenericBuffer (buffer->getOutputTensor(idx)->getData(),
1301 &output.bufs[idx], func);
1303 logerr (TAG, "Failed to return output buffer: %d\n", status);
1308 cb (&output, req->getID(), cb_data);
1314 * @brief extract the segment table instance from input generic buffers
1315 * @param[in] model the model instance
1316 * @param[in] input the input generic buffers
1317 * @param[in] output the output generic buffers
1318 * @return the segment table instance
1321 TrinityVision2::prepareSegmentTable (const Model *model, const input_buffers *input,
1322 const output_buffers *output)
1324 if (model == nullptr) {
1325 logerr (TAG, "Invalid arguments provided\n");
1329 const Metadata *meta = model->getMetadata ();
1330 if (meta == nullptr || (input != nullptr &&
1331 meta->getInputNum() != input->num_buffers)) {
1332 logerr (TAG, "Invalid metadata info provided\n");
1336 SegmentTable * segt = mem_->allocSegmentTable (new HWmemDevice);
1337 int status = segt->alloc ();
1339 logerr (TAG, "Failed to allocate segment table: %d\n", status);
1343 status = segt->createSegments (model, input, output);
1345 logerr (TAG, "Failed to create segments: %d\n", status);
1357 * @brief implementation of TRIV2's setModel ()
1358 * @param[in] model_buf the model generic buffer
1359 * @param[out] model the model instance
1360 * @return 0 if no error, otherwise a negative errno
1363 TrinityVision2::setModel (const generic_buffer *model_buf, Model ** model_ptr)
1365 if (!initialized ()) {
1366 logerr (TAG, "Uninitialized device; should use libnpuhost APIs\n");
1370 if (model_buf == nullptr || model_ptr == nullptr)
1376 switch (model_buf->type) {
1379 model = mem_->allocModel (new HWmemDevice);
1380 if (model == nullptr) {
1381 logerr (TAG, "Failed to allocate model\n");
1385 status = model->alloc (NPUBIN_META_SIZE);
1387 logerr (TAG, "Failed to allocate model: %d\n", status);
1391 status = comm_.extractGenericBuffer (model_buf, model->getData(), nullptr,
1392 0, NPUBIN_META_SIZE);
1394 logerr (TAG, "Failed to extract generic buffer: %d\n", status);
1402 status = model->setMetadata (model->getData());
1406 /** allocate program (optional; NOP) */
1407 if (model->getMetadata()->getProgramSize() > 0) {
1408 HWmem * hwmem_prog = new HWmem (new HWmemDevice);
1409 hwmem_prog->setDriverAPI (api_.get());
1411 model->setProgramData (hwmem_prog);
1413 status = hwmem_prog->alloc (model->getMetadata()->getProgramSize());
1415 logerr (TAG, "Failed to allocate program\n");
1419 status = comm_.extractGenericBuffer (model_buf, hwmem_prog->getData(), nullptr,
1420 model->getMetadata()->getMetaSize(),
1421 model->getMetadata()->getProgramSize());
1423 logerr (TAG, "Failed to extract generic buffer: %d\n", status);
1427 /** register this model to the driver */
1428 model_config_t config;
1429 config.dbuf_fd = hwmem_prog->getDmabuf ();
1430 config.program_size = hwmem_prog->getSize ();
1431 config.program_offset_addr = 0;
1433 status = api_->registerModel (&config);
1437 model->setInternalID(config.id);
1440 /** allocate weight (optional) */
1441 if (model->getMetadata()->getWeightSize() > 0) {
1442 HWmem * hwmem_weight = new HWmem (new HWmemDevice);
1443 hwmem_weight->setDriverAPI (api_.get());
1445 model->setWeightData (hwmem_weight);
1447 status = hwmem_weight->alloc (model->getMetadata()->getWeightSize());
1449 logerr (TAG, "Failed to allocate program\n");
1453 status = comm_.extractGenericBuffer (model_buf, hwmem_weight->getData(), nullptr,
1454 model->getMetadata()->getMetaSize() + model->getMetadata()->getProgramSize(),
1455 model->getMetadata()->getWeightSize());
1457 logerr (TAG, "Failed to extract generic buffer: %d\n", status);
1471 * @brief implementation of TRIV2's unsetModel ()
1472 * @param[in] model the model instance
1473 * @return 0 if no error, otherwise a negative errno
1476 TrinityVision2::unsetModel (Model * model)
1478 if (!initialized ()) {
1479 logerr (TAG, "Uninitialized device; should use libnpuhost APIs\n");
1483 if (model == nullptr) {
1484 logerr (TAG, "Invalid model instance\n");
1488 if (model->getMetadata()->getProgramSize() > 0)
1489 return api_->deregisterModel (model->getInternalID ());
1494 /** @brief implementation of TRIV2's run() */
1496 TrinityVision2::run (npu_input_opmode opmode, const Model *model,
1497 const input_buffers *input, npuOutputNotify cb, void *cb_data,
1500 if (!initialized ()) {
1501 logerr (TAG, "Uninitialized device; should use libnpuhost APIs\n");
1505 if (opmode != NPUINPUT_HOST)
1508 /** this device uses segment table */
1509 SegmentTable * segt = prepareSegmentTable (model, input);
1510 if (segt == nullptr) {
1511 logerr (TAG, "Failed to create segment table instance\n");
1515 /** extract input data */
1516 for (uint32_t idx = 0; idx < input->num_buffers; idx++) {
1517 size_t max_seg_size = segt->getInputSegment(idx)->getSize();
1518 uint32_t seg_offset = segt->getInputSegmentOffset(idx);
1520 if (input->bufs[idx].size + seg_offset > max_seg_size) {
1521 logerr (TAG, "Too large input data provided: max segment size (%zu)\n",
1526 if (!segt->getInputSegment(idx)->isExternal ()) {
1527 auto func = std::bind (TrinityVision2::manipulateData, model, idx, true,
1528 std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
1529 int status = comm_.extractGenericBuffer (
1531 segt->getInputSegment(idx)->getData() + seg_offset,
1534 logerr (TAG, "Failed to feed input segment: %d\n", status);
1540 Request *req = new Request (opmode);
1541 req->setModel (model);
1542 req->setSegmentTable (segt);
1543 req->setCallback (std::bind (&TrinityVision2::callback, this, req, cb, cb_data));
1546 *sequence = req->getID();
1548 return scheduler_->submitRequest (req);
1551 /** @brief implementation of TRIV2's runInternal() */
1553 TrinityVision2::runInternal (npu_input_opmode opmode, const Model *model,
1556 if (!initialized ()) {
1557 logerr (TAG, "Uninitialized device; should use libnpuhost APIs\n");
1561 if (opmode != NPUINPUT_HW_RECURRING)
1564 /** this device uses segment table */
1565 SegmentTable * segt = prepareSegmentTable (model, nullptr, nullptr);
1566 if (segt == nullptr) {
1567 logerr (TAG, "Failed to create segment table instance\n");
1571 Request *req = new Request (opmode);
1572 req->setModel (model);
1573 req->setSegmentTable (segt);
1574 req->setHwDevice (hw_dev);
1576 return scheduler_->submitRequest (req);
1579 /** @brief callback of TRIV2 request */
1581 TrinityVision2::callback (Request *req, npuOutputNotify cb, void *cb_data)
1583 const Model *model = req->getModel ();
1584 SegmentTable *segt = req->getSegmentTable ();
1585 output_buffers output = {
1586 .num_buffers = segt->getNumOutputSegments ()
1589 for (uint32_t idx = 0; idx < output.num_buffers; idx++) {
1590 uint32_t output_tensor_size = model->getOutputTensorSize (idx);
1592 output.bufs[idx].type = BUFFER_MAPPED;
1593 output.bufs[idx].size = output_tensor_size;
1594 /** user needs to free this */
1595 output.bufs[idx].addr = calloc (1, output_tensor_size);
1597 auto func = std::bind (TrinityVision2::manipulateData, model, idx, false,
1598 std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
1599 int status = comm_.insertGenericBuffer (
1600 segt->getOutputSegment(idx)->getData() + segt->getOutputSegmentOffset(idx),
1601 &output.bufs[idx], func);
1604 logerr (TAG, "Failed to return output buffer: %d\n", status);
1608 cb (&output, req->getID(), cb_data);
1613 /** @brief implementation of TRIA's run(): WIP */
1615 TrinityAsr::run (npu_input_opmode opmode, const Model *model,
1616 const input_buffers *input, npuOutputNotify cb, void *cb_data,
1619 if (!initialized ()) {
1620 logerr (TAG, "Uninitialized device; should use libnpuhost APIs\n");
1624 if (opmode != NPUINPUT_HOST)
1629 /** ASR does not require model and support only a single tensor */
1630 const generic_buffer *first_buf = &input->bufs[0];
1631 if (first_buf->type == BUFFER_DMABUF) {
1632 buffer = mem_->allocBuffer (new HWmemExternal);
1633 if (buffer == nullptr)
1636 buffer->setDmabuf (first_buf->dmabuf);
1637 buffer->setOffset (first_buf->offset);
1638 buffer->setSize (first_buf->size);
1640 buffer = mem_->allocBuffer (new HWmemDevice);
1641 if (buffer == nullptr)
1644 status = buffer->alloc (first_buf->size);
1651 status = buffer->createTensors ();
1653 logerr (TAG, "Failed to create tensors: %d\n", status);
1658 if (!buffer->isExternal ()) {
1659 status = comm_.extractGenericBuffer (first_buf,
1660 buffer->getInputTensor(0)->getData(), nullptr);
1665 Request *req = new Request (opmode);
1666 req->setBuffer (buffer);
1667 req->setCallback (std::bind (&TrinityAsr::callback, this, req, cb, cb_data));
1670 *sequence = req->getID();
1672 return scheduler_->submitRequest (req);
1675 /** @brief callback of TRIA request: WIP */
1677 TrinityAsr::callback (Request *req, npuOutputNotify cb, void *cb_data)
1681 /** Implement data manipulation (each device may have different impl.) */
1685 #define do_quantized_memcpy(type) do {\
1688 while (idx < num_elems) {\
1689 val = ((type *) src)[idx];\
1690 val = val / _scale;\
1691 val += _zero_point;\
1692 val = (val > 255.0) ? 255.0 : 0.0;\
1693 ((uint8_t *) dst)[idx++] = (uint8_t) val;\
1696 while (idx < num_elems) {\
1697 val = *(uint8_t *) src;\
1698 val -= _zero_point;\
1700 ((type *) dst)[idx++] = (type) val;\
1701 dst = (void*)(((uint8_t *) dst) + data_size);\
1702 src = (void*)(((uint8_t *) src) + 1);\
1708 * @brief memcpy during quantization
1710 static void memcpy_with_quant (bool quant, data_type type, float scale, uint32_t zero_point,
1711 void *dst, const void *src, uint32_t num_elems)
1713 double _scale = (double) scale;
1714 double _zero_point = (double) zero_point;
1716 uint32_t data_size = get_data_size (type);
1720 case DATA_TYPE_INT8:
1721 do_quantized_memcpy (int8_t);
1723 case DATA_TYPE_UINT8:
1724 do_quantized_memcpy (uint8_t);
1726 case DATA_TYPE_INT16:
1727 do_quantized_memcpy (int16_t);
1729 case DATA_TYPE_UINT16:
1730 do_quantized_memcpy (uint16_t);
1732 case DATA_TYPE_INT32:
1733 do_quantized_memcpy (int32_t);
1735 case DATA_TYPE_UINT32:
1736 do_quantized_memcpy (uint32_t);
1738 case DATA_TYPE_INT64:
1739 do_quantized_memcpy (int64_t);
1741 case DATA_TYPE_UINT64:
1742 do_quantized_memcpy (uint64_t);
1744 case DATA_TYPE_FLOAT32:
1745 do_quantized_memcpy (float);
1747 case DATA_TYPE_FLOAT64:
1748 do_quantized_memcpy (double);
1751 logerr (TAG, "Unsupported datatype %d\n", type);
1756 * @brief perform data manipulation
1757 * @param[in] model model instance
1758 * @param[in] idx tensor index
1759 * @param[in] is_input indicate it's input manipulation
1760 * @param[out] dst destination buffer
1761 * @param[in] src source buffer (feature map)
1762 * @param[in] size size to be copied
1763 * @return size of memory copy if no error, otherwise zero
1765 * @note the input data format should be NHWC
1766 * @detail rules for the memory address of activations in NPU HW.
1767 * (https://code.sec.samsung.net/confluence/pages/viewpage.action?pageId=146491864)
1769 * 1) Special case (depth == 3)
1770 * - addr(x,y,z) = addr(0,0,0) + (z) + 3 * (x + width * y)
1773 * - addr(x,y,z) = addr(0,0,0) + (z % MPA_L) + MPA_L * (x + width * (y + height * (z / MPA_L)))
1775 * Thus, if depth is not a multiple of MPA_L (i.e., 64), zero padding is required
1778 TrinityVision::manipulateData (const Model *model, uint32_t idx, bool is_input,
1779 void *dst, void *src, size_t size)
1781 const Metadata *meta = model->getMetadata();
1782 const tensor_data_info* info;
1783 const uint32_t *dims;
1784 uint32_t zero_point;
1787 /** extract required information from the metadata */
1789 if (idx >= meta->getInputNum()) {
1790 logerr (TAG, "Wrong information for input tensors in metadata\n");
1794 info = model->getInputDataInfo (idx);
1795 dims = meta->getInputDims (idx);
1796 zero_point = meta->getInputQuantZero (idx);
1797 scale = meta->getInputQuantScale (idx);
1799 if (idx >= meta->getOutputNum()) {
1800 logerr (TAG, "Wrong information for output tensors in metadata\n");
1804 info = model->getOutputDataInfo (idx);
1805 dims = meta->getOutputDims (idx);
1806 zero_point = meta->getOutputQuantZero (idx);
1807 scale = meta->getOutputQuantScale (idx);
1810 if (info == nullptr) {
1811 logerr (TAG, "Unmatched tensors info\n");
1815 uint32_t batch = dims[0];
1816 uint32_t height = dims[1];
1817 uint32_t width = dims[2];
1818 uint32_t depth = dims[3];
1820 uint32_t data_size = get_data_size (info->type);
1821 if (data_size == 0) {
1822 logerr (TAG, "Invalid data size\n");
1826 bool need_quantization = false;
1828 * note that we assume DATA_TYPE_SRNPU is the smallest data type that we consider.
1829 * Also, DATA_TYPE_SRNPU and uint8_t may be regarded as the same in the view of apps.
1831 if (info->type != DATA_TYPE_SRNPU) {
1832 assert (data_size >= get_data_size (DATA_TYPE_SRNPU));
1834 if (data_size > get_data_size (DATA_TYPE_SRNPU) ||
1835 !(zero_point == default_quant_zero && scale == default_quant_scale))
1836 need_quantization = true;
1839 /** check data manipulation is required */
1840 if (depth != 3 && depth != 64 && info->layout != DATA_LAYOUT_SRNPU) {
1841 uint32_t MPA_L = DATA_GRANULARITY;
1842 uint32_t n, h, w, d;
1843 uint32_t std_offset; /* standard offset in NHWC data format */
1844 uint32_t npu_offset; /* npu offset in NPU HW data format*/
1845 uint32_t src_offset;
1846 uint32_t dst_offset;
1847 uint32_t slice_size;
1849 /* @todo we currently support only NHWC */
1850 if (info->layout != DATA_LAYOUT_NHWC) {
1851 logerr (TAG, "data manipulation is supported for NHWC only\n");
1855 for (n = 0; n < batch; n++) {
1856 for (h = 0; h < height; h++) {
1857 for (w = 0; w < width; w++) {
1858 for (d = 0; d < depth; d += MPA_L) {
1859 std_offset = d + depth * (w + width * (h + n * height));
1860 npu_offset = MPA_L * (w + width * (h + (n + d / MPA_L) * height));
1861 slice_size = (depth - d >= MPA_L) ? MPA_L : depth - d;
1864 src_offset = std_offset * data_size;
1865 dst_offset = npu_offset;
1867 src_offset = npu_offset;
1868 dst_offset = std_offset * data_size;
1871 /* if depth is not a multiple of MPA_L, add zero paddings (not exact values) */
1872 if (need_quantization) {
1873 memcpy_with_quant (is_input, info->type, scale, zero_point,
1874 static_cast<char*>(dst) + dst_offset,
1875 static_cast<char*>(src) + src_offset,
1879 static_cast<char*>(dst) + dst_offset,
1880 static_cast<char*>(src) + src_offset,
1887 } else if (need_quantization) {
1888 /** depth == 3 || depth == 64; special cases which can directly copy input tensor data */
1889 memcpy_with_quant (is_input, info->type, scale, zero_point,
1890 dst, src, is_input ? size / data_size : size);
1892 memcpy (dst, src, size);
1901 TrinityVision::manipulateData (const Model *model, uint32_t idx, bool is_input,
1902 void *dst, void *src, size_t size)
1904 memcpy (dst, src, size);
1910 /** other device types don't have data manip impl. yet */
1913 TrinityVision2::manipulateData (const Model *model, uint32_t idx, bool is_input,
1914 void *dst, void *src, size_t size)
1916 memcpy (dst, src, size);
1921 TrinityAsr::manipulateData (const Model *model, uint32_t idx, bool is_input,
1922 void *dst, void *src, size_t size)
1924 memcpy (dst, src, size);