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] input The input buffer where input data comes.
199 * @param[in] output The output buffer where output data is filled.
200 * @return @c 0 if no error. otherwise a negative error value
202 int runNPU_internalInput(npudev_h dev, uint32_t modelid, npu_input_opmode opmode,
203 const input_buffers *input, const output_buffers *output)
205 INIT_HOST_HANDLER (host_handler, dev);
207 return host_handler->runInternal (modelid, opmode, input, output);
211 * @brief Stop the request with the given id
212 * @param[in] dev The NPU device handle
213 * @param[in] id The request id
214 * @return @c 0 if no error. otherwise a negative error value
216 int stopNPU_internalInput(npudev_h dev, int id)
218 INIT_HOST_HANDLER (host_handler, dev);
220 return host_handler->stopInternal (id);
224 * @brief Allocate a generic buffer with the requested buffer type.
225 * @param[in] dev The NPU device handle
226 * @param[in/out] Buffer the buffer pointer where memory is allocated.
227 * @return 0 if no error, otherwise a negative errno.
229 int allocNPU_genericBuffer (npudev_h dev, generic_buffer * buffer)
231 INIT_HOST_HANDLER (host_handler, dev);
233 return host_handler->allocGenericBuffer (buffer);
237 * @brief Free the generic buffer and remove the address mapping
238 * @param[in] dev The NPU device handle
239 * @param[in] buffer the model buffer
240 * @return 0 if no error, otherwise a negative errno.
242 int cleanNPU_genericBuffer (npudev_h dev, generic_buffer * buffer)
244 INIT_HOST_HANDLER (host_handler, dev);
246 return host_handler->deallocGenericBuffer (buffer);
250 * @brief Allocate generic buffers, which have multiple instances of generic_buffer
251 * @param[in] dev The NPU device handle
252 * @param[in/out] buffers generic buffers.
253 * @return 0 if no error, otherwise a negative errno.
254 * @note it reuses allocGenericBuffer().
256 int allocNPU_genericBuffers (npudev_h dev, generic_buffers * buffers)
258 INIT_HOST_HANDLER (host_handler, dev);
260 return host_handler->allocGenericBuffer (buffers);
264 * @brief Free generic buffers allocated by allocGenericBuffers().
265 * @param[in] dev The NPU device handle
266 * @param[in/out] buffers generic buffers.
267 * @note it reuses cleanGenericbuffer().
268 * @return 0 if no error, otherwise a negative errno.
270 int cleanNPU_genericBuffers (npudev_h dev, generic_buffers * buffers)
272 INIT_HOST_HANDLER (host_handler, dev);
274 return host_handler->deallocGenericBuffer (buffers);
278 * @brief alias of allocNPU_genericBuffer for model buffer
280 int allocNPU_modelBuffer (npudev_h dev, generic_buffer * model)
282 return allocNPU_genericBuffer (dev, model);
286 * @brief alias of cleanNPU_genericBuffer for model buffer
288 int cleanNPU_modelBuffer (npudev_h dev, generic_buffer * model)
290 return cleanNPU_genericBuffer (dev, model);
294 * @brief alias of allocNPU_genericBuffer for input buffer
296 int allocNPU_inputBuffer (npudev_h dev, generic_buffer * input)
298 return allocNPU_genericBuffer (dev, input);
302 * @brief alias of cleanNPU_genericBuffer for input buffer
304 int cleanNPU_inputBuffer (npudev_h dev, generic_buffer * input)
306 return cleanNPU_genericBuffer (dev, input);
310 * @brief alias of allocNPU_genericBuffers for input buffers
312 int allocNPU_inputBuffers (npudev_h dev, input_buffers * input)
314 return allocNPU_genericBuffers (dev, input);
318 * @brief alias of cleanNPU_genericBuffers for input buffers
320 int cleanNPU_inputBuffers (npudev_h dev, input_buffers * input)
322 return cleanNPU_genericBuffers (dev, input);
326 * @brief get the current memory status for the given device
327 * @param[in] dev The NPU device handle
328 * @param[out] alloc_total The size of allocated memory until now
329 * @param[out] free_total The size of freed memory until now
330 * @return @c 0 if no error. otherwise a negatice error value
332 int getNPU_memoryStatus(npudev_h dev, size_t *alloc_total, size_t *free_total)
334 INIT_HOST_HANDLER (host_handler, dev);
336 return host_handler->getMemoryStatus (alloc_total, free_total);
340 * @brief Get the current device status to be used
341 * @param[in] dev The NPU device handle
342 * @param[out] status the device status
343 * @param[out] num_requests the number of running requests (or pending)
344 * @return 0 if no error, otherwise a negative errno.
346 int getNPU_deviceStatus(npudev_h dev, npu_status *status, uint32_t *num_requests)
348 INIT_HOST_HANDLER (host_handler, dev);
350 return host_handler->getDeviceStatus (status, num_requests);
354 * @brief Get metadata for NPU model
355 * @param[in] model The path of model binary file
356 * @param[in] need_extra whether you want to extract the extra data in metadata
357 * @return the metadata structure to be filled if no error, otherwise nullptr
359 * @note For most npu-engine users, the extra data is not useful because it will be
360 * used for second-party users (e.g., compiler, simulator).
361 * Also, the caller needs to free the metadata.
363 * @note the caller needs to free the metadata
365 npubin_meta * getNPUmodel_metadata (const char *model, bool need_extra)
374 fp = fopen (model, "rb");
376 logerr (TAG, "Failed to open the model binary: %d\n", -errno);
380 meta = (npubin_meta *) malloc (NPUBIN_META_SIZE);
382 logerr (TAG, "Failed to allocate metadata\n");
386 ret = fread (meta, 1, NPUBIN_META_SIZE, fp);
387 if (ret != NPUBIN_META_SIZE) {
388 logerr (TAG, "Failed to read the metadata\n");
392 if (!CHECK_NPUBIN (meta->magiccode)) {
393 logerr (TAG, "Invalid metadata provided\n");
397 if (need_extra && NPUBIN_META_EXTRA (meta->magiccode) > 0) {
398 npubin_meta *new_meta;
400 new_meta = (npubin_meta *) realloc (meta, NPUBIN_META_TOTAL_SIZE(meta->magiccode));
402 logerr (TAG, "Failed to allocate extra metadata\n");
406 ret = fread (new_meta->reserved_extra, 1, NPUBIN_META_EXTRA_SIZE (meta->magiccode), fp);
407 if (ret != NPUBIN_META_EXTRA_SIZE (meta->magiccode)) {
408 logerr (TAG, "Invalid extra metadata provided\n");
428 /** implement methods of HostHandler class */
430 /** @brief host handler constructor */
431 HostHandler::HostHandler (Device *device)
433 /* ignored as we don't use double buffering anymore, but for backward-compatibility */
434 async_mode_ (NPUASYNC_WAIT)
438 /** @brief host handler destructor */
439 HostHandler::~HostHandler ()
444 * @brief register model from generic buffer
445 * @param[in] model_buf model buffer
446 * @param[out] modelid model id
447 * @return 0 if no error. otherwise a negative errno
450 HostHandler::registerModel (generic_buffer *model_buf, uint32_t *modelid)
452 if (model_buf == nullptr || modelid == nullptr) {
453 logerr (TAG, "Invalid arguments given\n");
457 Model *model = nullptr;
458 int status = device_->setModel (model_buf, &model);
460 logerr (TAG, "Failed to set model: %d\n", status);
464 assert (model != nullptr);
466 status = models_.insert (model->getID(), model);
468 logerr (TAG, "Failed to insert model id\n");
473 *modelid = model->getID();
478 * @brief remove the registered model
479 * @param[in] modelid model id
480 * @return 0 if no error. otherwise a negative errno
483 HostHandler::unregisterModel (uint32_t modelid)
485 Model *model = models_.find (modelid);
486 if (model == nullptr)
489 int status = device_->unsetModel (model);
491 logerr (TAG, "Failed to unset model: %d\n", status);
495 return models_.remove (modelid);
499 * @brief remove all registered models
503 HostHandler::unregisterModels ()
510 * @brief Set the data layout for input/output tensors
511 * @param[in] modelid The ID of model whose layouts are set
512 * @param[in] in the layout/type info for input tensors
513 * @param[in] out the layout/type info for output tensors
514 * @return @c 0 if no error. otherwise a negative error value
515 * @note if this function is not called, default layout/type will be used.
518 HostHandler::setDataInfo (uint32_t modelid, tensors_data_info *in,
519 tensors_data_info *out)
521 Model *model = models_.find (modelid);
522 if (model == nullptr)
525 return model->setDataInfo (in, out);
529 * @brief Set the inference constraint for next NPU inferences
530 * @param[in] modelid The target model id
531 * @param[in] constraint inference constraint (e.g., timeout, priority)
532 * @return @c 0 if no error. otherwise a negative error value
533 * @note If this function is not called, default values are used.
536 HostHandler::setConstraint (uint32_t modelid, npuConstraint constraint)
538 Model *model = models_.find (modelid);
539 if (model == nullptr)
542 model->setConstraint (constraint);
548 * @brief find and return model instance
549 * @param[in] modelid model id
550 * @return model instance if found. otherwise nullptr
553 HostHandler::getModel (uint32_t modelid)
555 return models_.find (modelid);
558 /** @brief dummay callback for runSync. */
561 callbackSync (output_buffers *output) : output_(output), done_(false) {}
563 static void callback (output_buffers *output, uint64_t sequence, void *data) {
564 callbackSync *sync = static_cast<callbackSync *>(data);
565 sync->callback (output, sequence);
568 void callback (output_buffers *output, uint64_t sequence) {
569 if (output_ != nullptr) {
570 /** just copy internal variables of output buffers */
571 memcpy (output_, output, sizeof (output_buffers));
578 std::unique_lock<std::mutex> lock (m_);
579 cv_.wait (lock, [this]() { return done_; });
584 std::condition_variable cv_;
585 output_buffers *output_;
590 * @brief Execute inference. Wait (block) until the output is available.
591 * @param[in] modelid The model to be inferred.
592 * @param[in] input The input data to be inferred.
593 * @param[out] output The output result.
594 * @return @c 0 if no error. otherwise a negative error value
597 HostHandler::runSync (uint32_t modelid, const input_buffers *input,
598 output_buffers *output)
600 callbackSync sync (output);
601 int status = runAsync (modelid, input, callbackSync::callback,
602 static_cast <void*> (&sync), NPUASYNC_DROP_OLD, nullptr);
604 /** sync needs to wait callback */
611 * @brief Invoke NPU inference. Unblocking call.
612 * @param[in] modelid The model to be inferred.
613 * @param[in] input The input data to be inferred.
614 * @param[in] cb The output buffer handler.
615 * @param[in] cb_data The data given as a parameter to the runNPU_async call.
616 * @param[in] mode Configures how this operation works.
617 * @param[out] sequence The sequence number returned with runNPU_async.
618 * @return @c 0 if no error. otherwise a negative error value
621 HostHandler::runAsync (uint32_t modelid, const input_buffers *input,
622 npuOutputNotify cb, void *cb_data, npu_async_mode mode, uint64_t *sequence)
624 Model *model = nullptr;
626 if (device_->needModel()) {
627 model = getModel (modelid);
628 if (model == nullptr)
632 /* check the given model before running */
633 if (!model->finalize ()) {
634 logerr (TAG, "Failed to finalize the model. Please see the log messages\n");
638 device_->setAsyncMode (mode);
639 return device_->run (NPUINPUT_HOST, model, input, cb, cb_data, sequence);
643 * @brief Let NPU accept input frames from its internal source continuously
644 * @param[in] modelid The model to be inferred.
645 * @param[in] opmode NPU has different opmode with auto-inputs. Choose one.
646 * @param[in] input The input buffer where input data comes.
647 * @param[in] output The output buffer where output data is filled.
648 * @return @c 0 if no error. otherwise a negative error value
651 HostHandler::runInternal (uint32_t modelid, npu_input_opmode opmode,
652 const input_buffers *input, const output_buffers *output)
654 Model *model = nullptr;
656 if (device_->needModel()) {
657 model = getModel (modelid);
658 if (model == nullptr)
662 /* check the given model before running */
663 if (!model->finalize ()) {
664 logerr (TAG, "Failed to finalize the model. Please see the log messages\n");
668 return device_->runInternal (opmode, model, input, output);
672 * @brief Stop the request with the given id
673 * @param[in] dev The NPU device handle
674 * @param[in] id The request id
675 * @return @c 0 if no error. otherwise a negative error value
678 HostHandler::stopInternal (int id)
681 logerr (TAG, "Unable to stop this request with id (%d)\n", id);
685 const DriverAPI * api = device_->getDriverAPI ();
686 assert (api != nullptr);
688 return api->stop_target (id);
692 * @brief get number of available devices
693 * @param[in] type device type
694 * @return number of devices
697 HostHandler::getNumDevices (dev_type type)
699 return DriverAPI::getNumDevices (type);
703 * @brief get device instance
704 * @param[out] dev device instance
705 * @param[in] type device type
706 * @param[in] id device id
707 * @return 0 if no error. otherwise a negative errno
710 HostHandler::getDevice (npudev_h *dev, dev_type type, uint32_t id)
712 int num_devices = getNumDevices (type);
714 /** check the validity of device id */
715 if (!(num_devices > 0 && id < static_cast<uint32_t>(num_devices))) {
716 logerr (TAG, "Invalid arguments provided\n");
720 Device *device = Device::createInstance (type, id);
721 if (device == nullptr) {
722 logerr (TAG, "Failed to create a device with the given type\n");
727 /** This is just for backward-compatility; we don't guarantee its corresness */
734 * @brief allocate generic buffer (just for users)
735 * @param[out] buffer buffer instance
736 * @return 0 if no error. otherwise a negative errno
739 HostHandler::allocGenericBuffer (generic_buffer *buffer)
744 if (buffer->size == 0) {
745 logerr (TAG, "Invalid size\n");
749 if (buffer->size > UINT32_MAX) {
750 logerr (TAG, "Don't support such a large size");
754 switch (buffer->type) {
757 if (buffer->filepath == nullptr)
762 /* now, npu-engine always provides dmabuf-based allocation */
763 void *addr = nullptr;
764 int dmabuf = device_->allocMemory (buffer->size, &addr);
768 buffer->dmabuf = dmabuf;
780 * @brief deallocate generic buffer (just for users)
781 * @param[in] buffer buffer instance
782 * @return 0 if no error. otherwise a negative errno
785 HostHandler::deallocGenericBuffer (generic_buffer *buffer)
790 switch (buffer->type) {
792 /** always true cuz nothing to do */
795 return device_->deallocMemory (buffer->dmabuf, buffer->size, buffer->addr);
804 * @brief allocate multiple generic buffers (just for users)
805 * @param[out] buffers multi-buffer instance
806 * @return 0 if no error. otherwise a negative errno
809 HostHandler::allocGenericBuffer (generic_buffers *buffers)
814 if (buffers == NULL || buffers->num_buffers < 1)
817 for (idx = 0; idx < buffers->num_buffers; idx++) {
818 status = allocGenericBuffer (&buffers->bufs[idx]);
826 for (idx = idx - 1; idx >= 0; idx--) {
827 deallocGenericBuffer (&buffers->bufs[idx]);
834 * @brief deallocate multiple generic buffers (just for users)
835 * @param[in] buffers multi-buffer instance
836 * @return 0 if no error. otherwise a negative errno
839 HostHandler::deallocGenericBuffer (generic_buffers *buffers)
841 if (buffers == NULL || buffers->num_buffers < 1)
844 for (uint32_t idx = 0; idx < buffers->num_buffers; idx++)
845 deallocGenericBuffer (&buffers->bufs[idx]);
846 buffers->num_buffers = 0;
852 * @brief get the current memory status
853 * @param[out] alloc_total The size of allocated memory until now
854 * @param[out] free_total The size of freed memory until now
855 * @return 0 if no error. otherwise a negatice error value
858 HostHandler::getMemoryStatus (size_t *alloc_total, size_t *free_total)
860 /** API is always set in initialize () */
861 const DriverAPI * api = device_->getDriverAPI ();
862 assert (api != nullptr);
864 return api->getMemoryStatus (alloc_total, free_total);
868 * @brief Get the current device status to be used
869 * @param[out] status the device status
870 * @param[out] num_requests the number of running requests (or pending)
871 * @return 0 if no error, otherwise a negative errno.
874 HostHandler::getDeviceStatus (npu_status *status, uint32_t *num_requests)
876 /** API is always set in initialize () */
877 const DriverAPI * api = device_->getDriverAPI ();
878 assert (api != nullptr);
880 device_state_t state = api->isReady ();
881 if (state == device_state_t::STATE_READY) {
882 *num_requests = api->numRequests ();
883 if (*num_requests > 0)
895 /** implement methods of Device class */
897 /** @brief constructor of device */
898 Device::Device (dev_type type, int id, bool need_model)
899 : comm_ (CommPlugin::getCommPlugin()), type_ (type), id_ (id), need_model_ (true),
900 mode_ (NPUASYNC_WAIT), initialized_ (false), atomic_flag_ (ATOMIC_FLAG_INIT)
905 * @brief create device instance depending on device type and id
906 * @param[in] type device type
907 * @param[in] id device id
908 * @return device instance
911 Device::createInstance (dev_type type, int id)
913 Device *device = nullptr;
915 switch (type & DEVICETYPE_MASK) {
916 case DEVICETYPE_TRIV:
917 device = new TrinityVision (id);
919 case DEVICETYPE_TRIV2:
920 device = new TrinityVision2 (id);
922 case DEVICETYPE_TRIA:
923 device = new TrinityAsr (id);
929 if (device != nullptr && device->init () != 0) {
938 * @brief device initialization
939 * @return 0 if no error, otherwise a negative errno
940 * @note Init failures come from createDriverAPI() only.
945 /** should be initilizaed only once */
946 if (!atomic_flag_.test_and_set()) {
947 /** create the corresponding driver API */
948 api_ = DriverAPI::createDriverAPI (type_, id_);
949 if (api_.get() == nullptr) {
950 atomic_flag_.clear();
951 logerr (TAG, "Failed to create driver API\n");
955 handler_.reset (new HostHandler (this));
956 scheduler_.reset (new Scheduler (api_.get()));
957 mem_ = MemAllocator::createInstance (api_.get());
959 initialized_ = true; /** c++11 does not provide test() of atomic flag */
966 * @brief stop all requests from this device
967 * @param[in] force_stop indicate the schedduler waits until to handle previous requests
968 * @return 0 if no error, otherwise a negative errno
971 Device::stop (bool force_stop)
973 if (!initialized ()) {
974 logerr (TAG, "Uninitialized device; should use libnpuhost APIs\n");
978 Request *req = new Request (NPUINPUT_STOP);
979 req->setForceStop (force_stop);
980 return scheduler_->submitRequest (req);
984 * @brief allocate generic memory buffer
985 * @param[in] size the size to allocate
986 * @param[out] addr the mapped address
987 * @return dmabuf fd if no error, otherwise a negative errno
990 Device::allocMemory (size_t size, void **addr)
992 if (!initialized ()) {
993 logerr (TAG, "Uninitialized device; should use libnpuhost APIs\n");
997 if (size == 0 || addr == nullptr) {
998 logerr (TAG, "Invalid arguments\n");
1002 return mem_->allocMemory (size, addr);
1006 * @brief deallocate generic memory buffer
1007 * @param[in] dmabuf_fd dmabuf file descriptor
1008 * @param[in] size buffer size
1009 * @param[in] addr mapped addr
1010 * @return 0 if no error, otherwise a negative errno
1013 Device::deallocMemory (int dmabuf_fd, size_t size, void * addr)
1015 if (!initialized ()) {
1016 logerr (TAG, "Uninitialized device; should use libnpuhost APIs\n");
1020 if (dmabuf_fd < 0 || size == 0 || addr == nullptr) {
1021 logerr (TAG, "Invalid arguments\n");
1025 return mem_->deallocMemory (dmabuf_fd, size, addr);
1029 * @brief extract the buffer instance from input generic buffers
1030 * @param[in] meta the model metadata
1031 * @param[in] input the input generic buffers
1032 * @return the buffer instance
1035 TrinityVision::prepareInputBuffers (const Metadata *meta, const input_buffers *input)
1037 if (meta == nullptr || input == nullptr ||
1038 meta->getInputNum() != input->num_buffers) {
1039 logerr (TAG, "Invalid metadata info provided\n");
1044 const generic_buffer *first = &input->bufs[0];
1045 if (first->type == BUFFER_DMABUF) {
1046 buffer = mem_->allocBuffer (new HWmemExternal);
1047 if (buffer == nullptr)
1050 buffer->setDmabuf (first->dmabuf);
1051 buffer->setOffset (first->offset);
1052 buffer->setSize (meta->getBufferSize());
1054 buffer = mem_->allocBuffer (new HWmemDevice);
1055 if (buffer == nullptr)
1058 int status = buffer->alloc (meta->getBufferSize ());
1060 logerr (TAG, "Failed to allocate buffer: %d\n", status);
1066 int status = buffer->createTensors (meta);
1068 logerr (TAG, "Failed to create tensors: %d\n", status);
1077 * @brief implementation of TRIV's setModel ()
1078 * @param[in] model_buf the model generic buffer
1079 * @param[out] model the model instance
1080 * @return 0 if no error, otherwise a negative errno
1083 TrinityVision::setModel (const generic_buffer *model_buf, Model ** model_ptr)
1085 if (!initialized ()) {
1086 logerr (TAG, "Uninitialized device; should use libnpuhost APIs\n");
1090 if (model_buf == nullptr || model_ptr == nullptr)
1093 Model *model = nullptr;
1094 HWmem * hwmem_prog = nullptr;
1095 HWmem * hwmem_weight = nullptr;
1098 /** In TRIV1, model data (including program/weight) should be contiguous */
1100 switch (model_buf->type) {
1103 model = mem_->allocModel (new HWmemDevice);
1104 if (model == nullptr) {
1105 logerr (TAG, "Failed to allocate model\n");
1109 status = model->alloc (model_buf->size);
1111 logerr (TAG, "Failed to allocate model: %d\n", status);
1115 /** extract the whole model data */
1116 status = comm_.extractGenericBuffer (model_buf, model->getData(), nullptr);
1118 logerr (TAG, "Failed to extract generic buffer: %d\n", status);
1126 status = model->setMetadata (model->getData());
1130 /** allocate program (optional; NOP) */
1131 if (model->getMetadata()->getProgramSize() > 0) {
1132 hwmem_prog = new HWmem (new HWmemChunk);
1133 model->setProgramData (hwmem_prog);
1135 hwmem_prog->setParent (model);
1136 hwmem_prog->setOffset (model->getMetadata()->getMetaSize());
1137 status = hwmem_prog->alloc (model->getMetadata()->getProgramSize());
1139 logerr (TAG, "Failed to allocate program\n");
1144 /** allocate weight (optional) */
1145 if (model->getMetadata()->getWeightSize() > 0) {
1146 hwmem_weight = new HWmem (new HWmemChunk);
1147 model->setWeightData (hwmem_weight);
1149 hwmem_weight->setParent (model);
1150 hwmem_weight->setOffset (model->getMetadata()->getMetaSize() +
1151 model->getMetadata()->getProgramSize());
1152 status = hwmem_weight->alloc (model->getMetadata()->getWeightSize());
1154 logerr (TAG, "Failed to allocate program\n");
1159 if (hwmem_prog != nullptr) {
1160 /** register this model to the driver */
1161 model_config_t config;
1162 config.dbuf_fd = hwmem_prog->getDmabuf ();
1163 config.program_size = hwmem_prog->getSize ();
1164 config.program_offset_addr = hwmem_prog->getOffset ();
1165 if (hwmem_weight != nullptr)
1166 config.weight_offset_addr = hwmem_weight->getOffset ();
1168 status = api_->registerModel (&config);
1172 model->setInternalID(config.id);
1184 * @brief implementation of TRIV's unsetModel ()
1185 * @param[in] model the model instance
1186 * @return 0 if no error, otherwise a negative errno
1189 TrinityVision::unsetModel (Model * model)
1191 if (!initialized ()) {
1192 logerr (TAG, "Uninitialized device; should use libnpuhost APIs\n");
1196 if (model == nullptr) {
1197 logerr (TAG, "Invalid model instance\n");
1201 if (model->getMetadata()->getProgramSize() > 0)
1202 return api_->deregisterModel (model->getInternalID ());
1208 * @brief implementation of TRIV's run()
1209 * @param[in] opmode input opmode
1210 * @param[in] model the model instance
1211 * @param[in] input generic buffers of input data
1212 * @param[in] cb the output callback
1213 * @param[in] cb_data the output callback data
1214 * @param[out] sequence The sequence number returned with runNPU_async.
1217 TrinityVision::run (npu_input_opmode opmode, const Model *model,
1218 const input_buffers *input, npuOutputNotify cb, void *cb_data,
1221 if (!initialized ()) {
1222 logerr (TAG, "Uninitialized device; should use libnpuhost APIs\n");
1226 if (opmode != NPUINPUT_HOST) {
1227 logerr (TAG, "TRIV supports only host inputservice\n");
1231 if (model == nullptr || input == nullptr) {
1232 logerr (TAG, "TRIV requires both model and input buffers\n");
1236 Buffer *buffer = prepareInputBuffers (model->getMetadata(), input);
1237 if (buffer == nullptr) {
1238 logerr (TAG, "Failed to extract buffer instance\n");
1242 if (!buffer->isExternal ()) {
1243 for (uint32_t idx = 0; idx < input->num_buffers; idx++) {
1244 auto func = std::bind (TrinityVision::manipulateData, model, idx, true,
1245 std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
1246 int status = comm_.extractGenericBuffer (&input->bufs[idx],
1247 buffer->getInputTensor(idx)->getData(), func);
1249 logerr (TAG, "Failed to feed input buffer: %d\n", status);
1255 /** this device uses CMA buffer */
1257 Request *req = new Request (opmode);
1258 req->setModel (model);
1259 req->setBuffer (buffer);
1262 req->setCallback (std::bind (&TrinityVision::callback, this, req, cb, cb_data));
1264 if (sequence != nullptr)
1265 *sequence = req->getID();
1267 return scheduler_->submitRequest (req);
1271 * @brief callback of TRIV2 request
1272 * @param[in] req the request instance
1273 * @param[in] cb callback for completion
1274 * @param[in] cb_data callback data
1275 * @note The callback invoke does not gurantee the request was successful
1276 * @todo Check the request failures
1279 TrinityVision::callback (Request *req, npuOutputNotify cb, void *cb_data)
1281 const Model *model = req->getModel ();
1282 Buffer *buffer = req->getBuffer ();
1283 output_buffers output = {
1284 .num_buffers = buffer->getOutputNum ()
1287 for (uint32_t idx = 0; idx < output.num_buffers; idx++) {
1288 uint32_t output_tensor_size = model->getOutputTensorSize (idx);
1290 if (buffer->isExternal ()) {
1291 output.bufs[idx].type = BUFFER_DMABUF;
1292 output.bufs[idx].size = output_tensor_size;
1293 output.bufs[idx].addr = buffer->getOutputTensor(idx)->getData();
1295 output.bufs[idx].type = BUFFER_MAPPED;
1296 output.bufs[idx].size = output_tensor_size;
1297 /** user needs to free this */
1298 output.bufs[idx].addr = malloc (output_tensor_size);
1300 auto func = std::bind (TrinityVision::manipulateData, model, idx, false,
1301 std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
1302 int status = comm_.insertGenericBuffer (buffer->getOutputTensor(idx)->getData(),
1303 &output.bufs[idx], func);
1305 logerr (TAG, "Failed to return output buffer: %d\n", status);
1310 cb (&output, req->getID(), cb_data);
1316 * @brief extract the segment table instance from input generic buffers
1317 * @param[in] model the model instance
1318 * @param[in] input the input generic buffers
1319 * @param[in] output the output generic buffers
1320 * @return the segment table instance
1323 TrinityVision2::prepareSegmentTable (const Model *model, const input_buffers *input,
1324 const output_buffers *output)
1326 if (model == nullptr || input == nullptr) {
1327 logerr (TAG, "Invalid arguments provided\n");
1331 const Metadata *meta = model->getMetadata ();
1332 if (meta == nullptr ||
1333 meta->getInputNum() != input->num_buffers) {
1334 logerr (TAG, "Invalid metadata info provided\n");
1338 SegmentTable * segt = mem_->allocSegmentTable (new HWmemDevice);
1339 int status = segt->alloc ();
1341 logerr (TAG, "Failed to allocate segment table: %d\n", status);
1345 status = segt->createSegments (model, input, output);
1347 logerr (TAG, "Failed to create segments: %d\n", status);
1359 * @brief implementation of TRIV2's setModel ()
1360 * @param[in] model_buf the model generic buffer
1361 * @param[out] model the model instance
1362 * @return 0 if no error, otherwise a negative errno
1365 TrinityVision2::setModel (const generic_buffer *model_buf, Model ** model_ptr)
1367 if (!initialized ()) {
1368 logerr (TAG, "Uninitialized device; should use libnpuhost APIs\n");
1372 if (model_buf == nullptr || model_ptr == nullptr)
1378 switch (model_buf->type) {
1381 model = mem_->allocModel (new HWmemDevice);
1382 if (model == nullptr) {
1383 logerr (TAG, "Failed to allocate model\n");
1387 status = model->alloc (NPUBIN_META_SIZE);
1389 logerr (TAG, "Failed to allocate model: %d\n", status);
1393 status = comm_.extractGenericBuffer (model_buf, model->getData(), nullptr,
1394 0, NPUBIN_META_SIZE);
1396 logerr (TAG, "Failed to extract generic buffer: %d\n", status);
1404 status = model->setMetadata (model->getData());
1408 /** allocate program (optional; NOP) */
1409 if (model->getMetadata()->getProgramSize() > 0) {
1410 HWmem * hwmem_prog = new HWmem (new HWmemDevice);
1411 hwmem_prog->setDriverAPI (api_.get());
1413 model->setProgramData (hwmem_prog);
1415 status = hwmem_prog->alloc (model->getMetadata()->getProgramSize());
1417 logerr (TAG, "Failed to allocate program\n");
1421 status = comm_.extractGenericBuffer (model_buf, hwmem_prog->getData(), nullptr,
1422 model->getMetadata()->getMetaSize(),
1423 model->getMetadata()->getProgramSize());
1425 logerr (TAG, "Failed to extract generic buffer: %d\n", status);
1429 /** register this model to the driver */
1430 model_config_t config;
1431 config.dbuf_fd = hwmem_prog->getDmabuf ();
1432 config.program_size = hwmem_prog->getSize ();
1433 config.program_offset_addr = 0;
1435 status = api_->registerModel (&config);
1439 model->setInternalID(config.id);
1442 /** allocate weight (optional) */
1443 if (model->getMetadata()->getWeightSize() > 0) {
1444 HWmem * hwmem_weight = new HWmem (new HWmemDevice);
1445 hwmem_weight->setDriverAPI (api_.get());
1447 model->setWeightData (hwmem_weight);
1449 status = hwmem_weight->alloc (model->getMetadata()->getWeightSize());
1451 logerr (TAG, "Failed to allocate program\n");
1455 status = comm_.extractGenericBuffer (model_buf, hwmem_weight->getData(), nullptr,
1456 model->getMetadata()->getMetaSize() + model->getMetadata()->getProgramSize(),
1457 model->getMetadata()->getWeightSize());
1459 logerr (TAG, "Failed to extract generic buffer: %d\n", status);
1473 * @brief implementation of TRIV2's unsetModel ()
1474 * @param[in] model the model instance
1475 * @return 0 if no error, otherwise a negative errno
1478 TrinityVision2::unsetModel (Model * model)
1480 if (!initialized ()) {
1481 logerr (TAG, "Uninitialized device; should use libnpuhost APIs\n");
1485 if (model == nullptr) {
1486 logerr (TAG, "Invalid model instance\n");
1490 if (model->getMetadata()->getProgramSize() > 0)
1491 return api_->deregisterModel (model->getInternalID ());
1496 /** @brief implementation of TRIV2's run() */
1498 TrinityVision2::run (npu_input_opmode opmode, const Model *model,
1499 const input_buffers *input, npuOutputNotify cb, void *cb_data,
1502 if (!initialized ()) {
1503 logerr (TAG, "Uninitialized device; should use libnpuhost APIs\n");
1507 if (opmode != NPUINPUT_HOST)
1510 /** this device uses segment table */
1511 SegmentTable * segt = prepareSegmentTable (model, input);
1512 if (segt == nullptr) {
1513 logerr (TAG, "Failed to create segment table instance\n");
1517 /** extract input data */
1518 for (uint32_t idx = 0; idx < input->num_buffers; idx++) {
1519 size_t max_seg_size = segt->getInputSegment(idx)->getSize();
1520 uint32_t seg_offset = segt->getInputSegmentOffset(idx);
1522 if (input->bufs[idx].size + seg_offset > max_seg_size) {
1523 logerr (TAG, "Too large input data provided: max segment size (%zu)\n",
1528 if (!segt->getInputSegment(idx)->isExternal ()) {
1529 auto func = std::bind (TrinityVision2::manipulateData, model, idx, true,
1530 std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
1531 int status = comm_.extractGenericBuffer (
1533 segt->getInputSegment(idx)->getData() + seg_offset,
1536 logerr (TAG, "Failed to feed input segment: %d\n", status);
1542 Request *req = new Request (opmode);
1543 req->setModel (model);
1544 req->setSegmentTable (segt);
1545 req->setCallback (std::bind (&TrinityVision2::callback, this, req, cb, cb_data));
1548 *sequence = req->getID();
1550 return scheduler_->submitRequest (req);
1553 /** @brief implementation of TRIV2's runInternal() */
1555 TrinityVision2::runInternal (npu_input_opmode opmode, const Model *model,
1556 const input_buffers *input, const output_buffers *output)
1558 if (!initialized ()) {
1559 logerr (TAG, "Uninitialized device; should use libnpuhost APIs\n");
1563 if (opmode != NPUINPUT_HW_RECURRING)
1566 /** this device uses segment table */
1567 SegmentTable * segt = prepareSegmentTable (model, input, output);
1568 if (segt == nullptr) {
1569 logerr (TAG, "Failed to create segment table instance\n");
1573 Request *req = new Request (opmode);
1574 req->setModel (model);
1575 req->setSegmentTable (segt);
1577 return scheduler_->submitRequest (req);
1580 /** @brief callback of TRIV2 request */
1582 TrinityVision2::callback (Request *req, npuOutputNotify cb, void *cb_data)
1584 const Model *model = req->getModel ();
1585 SegmentTable *segt = req->getSegmentTable ();
1586 output_buffers output = {
1587 .num_buffers = segt->getNumOutputSegments ()
1590 for (uint32_t idx = 0; idx < output.num_buffers; idx++) {
1591 uint32_t output_tensor_size = model->getOutputTensorSize (idx);
1593 output.bufs[idx].type = BUFFER_MAPPED;
1594 output.bufs[idx].size = output_tensor_size;
1595 /** user needs to free this */
1596 output.bufs[idx].addr = calloc (1, output_tensor_size);
1598 auto func = std::bind (TrinityVision2::manipulateData, model, idx, false,
1599 std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
1600 int status = comm_.insertGenericBuffer (
1601 segt->getOutputSegment(idx)->getData() + segt->getOutputSegmentOffset(idx),
1602 &output.bufs[idx], func);
1605 logerr (TAG, "Failed to return output buffer: %d\n", status);
1609 cb (&output, req->getID(), cb_data);
1614 /** @brief implementation of TRIA's run(): WIP */
1616 TrinityAsr::run (npu_input_opmode opmode, const Model *model,
1617 const input_buffers *input, npuOutputNotify cb, void *cb_data,
1620 if (!initialized ()) {
1621 logerr (TAG, "Uninitialized device; should use libnpuhost APIs\n");
1625 if (opmode != NPUINPUT_HOST)
1630 /** ASR does not require model and support only a single tensor */
1631 const generic_buffer *first_buf = &input->bufs[0];
1632 if (first_buf->type == BUFFER_DMABUF) {
1633 buffer = mem_->allocBuffer (new HWmemExternal);
1634 if (buffer == nullptr)
1637 buffer->setDmabuf (first_buf->dmabuf);
1638 buffer->setOffset (first_buf->offset);
1639 buffer->setSize (first_buf->size);
1641 buffer = mem_->allocBuffer (new HWmemDevice);
1642 if (buffer == nullptr)
1645 status = buffer->alloc (first_buf->size);
1652 status = buffer->createTensors ();
1654 logerr (TAG, "Failed to create tensors: %d\n", status);
1659 if (!buffer->isExternal ()) {
1660 status = comm_.extractGenericBuffer (first_buf,
1661 buffer->getInputTensor(0)->getData(), nullptr);
1666 Request *req = new Request (opmode);
1667 req->setBuffer (buffer);
1668 req->setCallback (std::bind (&TrinityAsr::callback, this, req, cb, cb_data));
1671 *sequence = req->getID();
1673 return scheduler_->submitRequest (req);
1676 /** @brief callback of TRIA request: WIP */
1678 TrinityAsr::callback (Request *req, npuOutputNotify cb, void *cb_data)
1682 /** Implement data manipulation (each device may have different impl.) */
1686 #define do_quantized_memcpy(type) do {\
1689 while (idx < num_elems) {\
1690 val = ((type *) src)[idx];\
1691 val = val / _scale;\
1692 val += _zero_point;\
1693 val = (val > 255.0) ? 255.0 : 0.0;\
1694 ((uint8_t *) dst)[idx++] = (uint8_t) val;\
1697 while (idx < num_elems) {\
1698 val = *(uint8_t *) src;\
1699 val -= _zero_point;\
1701 ((type *) dst)[idx++] = (type) val;\
1702 dst = (void*)(((uint8_t *) dst) + data_size);\
1703 src = (void*)(((uint8_t *) src) + 1);\
1709 * @brief memcpy during quantization
1711 static void memcpy_with_quant (bool quant, data_type type, float scale, uint32_t zero_point,
1712 void *dst, const void *src, uint32_t num_elems)
1714 double _scale = (double) scale;
1715 double _zero_point = (double) zero_point;
1717 uint32_t data_size = get_data_size (type);
1721 case DATA_TYPE_INT8:
1722 do_quantized_memcpy (int8_t);
1724 case DATA_TYPE_UINT8:
1725 do_quantized_memcpy (uint8_t);
1727 case DATA_TYPE_INT16:
1728 do_quantized_memcpy (int16_t);
1730 case DATA_TYPE_UINT16:
1731 do_quantized_memcpy (uint16_t);
1733 case DATA_TYPE_INT32:
1734 do_quantized_memcpy (int32_t);
1736 case DATA_TYPE_UINT32:
1737 do_quantized_memcpy (uint32_t);
1739 case DATA_TYPE_INT64:
1740 do_quantized_memcpy (int64_t);
1742 case DATA_TYPE_UINT64:
1743 do_quantized_memcpy (uint64_t);
1745 case DATA_TYPE_FLOAT32:
1746 do_quantized_memcpy (float);
1748 case DATA_TYPE_FLOAT64:
1749 do_quantized_memcpy (double);
1752 logerr (TAG, "Unsupported datatype %d\n", type);
1757 * @brief perform data manipulation
1758 * @param[in] model model instance
1759 * @param[in] idx tensor index
1760 * @param[in] is_input indicate it's input manipulation
1761 * @param[out] dst destination buffer
1762 * @param[in] src source buffer (feature map)
1763 * @param[in] size size to be copied
1764 * @return size of memory copy if no error, otherwise zero
1766 * @note the input data format should be NHWC
1767 * @detail rules for the memory address of activations in NPU HW.
1768 * (https://code.sec.samsung.net/confluence/pages/viewpage.action?pageId=146491864)
1770 * 1) Special case (depth == 3)
1771 * - addr(x,y,z) = addr(0,0,0) + (z) + 3 * (x + width * y)
1774 * - addr(x,y,z) = addr(0,0,0) + (z % MPA_L) + MPA_L * (x + width * (y + height * (z / MPA_L)))
1776 * Thus, if depth is not a multiple of MPA_L (i.e., 64), zero padding is required
1779 TrinityVision::manipulateData (const Model *model, uint32_t idx, bool is_input,
1780 void *dst, void *src, size_t size)
1782 const Metadata *meta = model->getMetadata();
1783 const tensor_data_info* info;
1784 const uint32_t *dims;
1785 uint32_t zero_point;
1788 /** extract required information from the metadata */
1790 if (idx >= meta->getInputNum()) {
1791 logerr (TAG, "Wrong information for input tensors in metadata\n");
1795 info = model->getInputDataInfo (idx);
1796 dims = meta->getInputDims (idx);
1797 zero_point = meta->getInputQuantZero (idx);
1798 scale = meta->getInputQuantScale (idx);
1800 if (idx >= meta->getOutputNum()) {
1801 logerr (TAG, "Wrong information for output tensors in metadata\n");
1805 info = model->getOutputDataInfo (idx);
1806 dims = meta->getOutputDims (idx);
1807 zero_point = meta->getOutputQuantZero (idx);
1808 scale = meta->getOutputQuantScale (idx);
1811 if (info == nullptr) {
1812 logerr (TAG, "Unmatched tensors info\n");
1816 uint32_t batch = dims[0];
1817 uint32_t height = dims[1];
1818 uint32_t width = dims[2];
1819 uint32_t depth = dims[3];
1821 uint32_t data_size = get_data_size (info->type);
1822 if (data_size == 0) {
1823 logerr (TAG, "Invalid data size\n");
1827 bool need_quantization = false;
1829 * note that we assume DATA_TYPE_SRNPU is the smallest data type that we consider.
1830 * Also, DATA_TYPE_SRNPU and uint8_t may be regarded as the same in the view of apps.
1832 if (info->type != DATA_TYPE_SRNPU) {
1833 assert (data_size >= get_data_size (DATA_TYPE_SRNPU));
1835 if (data_size > get_data_size (DATA_TYPE_SRNPU) ||
1836 !(zero_point == default_quant_zero && scale == default_quant_scale))
1837 need_quantization = true;
1840 /** check data manipulation is required */
1841 if (depth != 3 && depth != 64 && info->layout != DATA_LAYOUT_SRNPU) {
1842 uint32_t MPA_L = DATA_GRANULARITY;
1843 uint32_t n, h, w, d;
1844 uint32_t std_offset; /* standard offset in NHWC data format */
1845 uint32_t npu_offset; /* npu offset in NPU HW data format*/
1846 uint32_t src_offset;
1847 uint32_t dst_offset;
1848 uint32_t slice_size;
1850 /* @todo we currently support only NHWC */
1851 if (info->layout != DATA_LAYOUT_NHWC) {
1852 logerr (TAG, "data manipulation is supported for NHWC only\n");
1856 for (n = 0; n < batch; n++) {
1857 for (h = 0; h < height; h++) {
1858 for (w = 0; w < width; w++) {
1859 for (d = 0; d < depth; d += MPA_L) {
1860 std_offset = d + depth * (w + width * (h + n * height));
1861 npu_offset = MPA_L * (w + width * (h + (n + d / MPA_L) * height));
1862 slice_size = (depth - d >= MPA_L) ? MPA_L : depth - d;
1865 src_offset = std_offset * data_size;
1866 dst_offset = npu_offset;
1868 src_offset = npu_offset;
1869 dst_offset = std_offset * data_size;
1872 /* if depth is not a multiple of MPA_L, add zero paddings (not exact values) */
1873 if (need_quantization) {
1874 memcpy_with_quant (is_input, info->type, scale, zero_point,
1875 static_cast<char*>(dst) + dst_offset,
1876 static_cast<char*>(src) + src_offset,
1880 static_cast<char*>(dst) + dst_offset,
1881 static_cast<char*>(src) + src_offset,
1888 } else if (need_quantization) {
1889 /** depth == 3 || depth == 64; special cases which can directly copy input tensor data */
1890 memcpy_with_quant (is_input, info->type, scale, zero_point,
1891 dst, src, is_input ? size / data_size : size);
1893 memcpy (dst, src, size);
1902 TrinityVision::manipulateData (const Model *model, uint32_t idx, bool is_input,
1903 void *dst, void *src, size_t size)
1905 memcpy (dst, src, size);
1911 /** other device types don't have data manip impl. yet */
1914 TrinityVision2::manipulateData (const Model *model, uint32_t idx, bool is_input,
1915 void *dst, void *src, size_t size)
1917 memcpy (dst, src, size);
1922 TrinityAsr::manipulateData (const Model *model, uint32_t idx, bool is_input,
1923 void *dst, void *src, size_t size)
1925 memcpy (dst, src, size);