5from typing
import List, Optional, Tuple, Union
9import qbruntime.qbruntime
as _cQbRuntime
10from .accelerator
import Accelerator
12from .model_variant_handle
import *
13from .npu_data
import NPUData
14from .pinned_memory
import PinnedMemory
17_Shape = Tuple[int, ...]
19__all__ = [
"Model",
"load"]
27def _is_valid_shape(input_shape: _Shape, shape: _Shape) -> bool:
28 if (len(input_shape) < len(shape))
or (len(input_shape) > len(shape) + 1):
31 offset = 1
if len(input_shape) > len(shape)
else 0
32 for s1, s2
in zip(input_shape[offset:], shape):
35 if s1 % s2 != 0
or (s2 > 0
and s1 != s2):
42def _find_memory_format(
43 inputs: List[np.ndarray], shapes: List[_Shape]
44) -> Optional[Tuple[bool, bool]]:
45 if len(inputs) != len(shapes):
50 for arr, shape
in zip(inputs, shapes):
51 shape_hwc = (shape[0], shape[1], shape[2])
52 shape_chw = (shape[2], shape[0], shape[1])
53 is_hwc = is_hwc
and _is_valid_shape(arr.shape, shape_hwc)
54 is_chw = is_chw
and _is_valid_shape(arr.shape, shape_chw)
56 if not is_hwc
and not is_chw:
62def _find_matching_variant_idx_and_memory_format(
63 model, inputs: List[np.ndarray]
64) -> Tuple[int, Tuple[bool, bool]]:
68 for i
in range(model.get_num_model_variants()):
69 res = _find_memory_format(
70 inputs, model.get_model_variant_handle(i).get_model_input_shape()
77 if variant_idx
is None:
78 raise ValueError(
"Input shape is invalid.")
79 return variant_idx, (is_hwc, is_chw)
84 shapes: List[_Shape], is_hwc: bool, dtype: np.dtype
89 shape = (shape[0], shape[1], shape[2])
91 shape = (shape[2], shape[0], shape[1])
92 outputs.append(np.empty(shape, dtype=dtype))
97def _check_output_shapes(
98 outputs: List[np.ndarray], shapes: List[_Shape], is_hwc: bool, dtype: np.dtype
100 if len(outputs) != len(shapes):
101 raise ValueError(
"The number of outputs is different.")
103 for output, shape
in zip(outputs, shapes):
104 if output.dtype != dtype:
105 raise ValueError(
"Output dtype mismatch.")
108 shape = (shape[0], shape[1], shape[2])
110 shape = (shape[2], shape[0], shape[1])
111 if output.shape != shape:
112 raise ValueError(
"Output shape mismatch.")
117 @brief Represents an AI model loaded from an MXQ file.
119 This class loads an AI model from an MXQ file and provides functions to launch it
120 on the NPU and perform inference.
123 def __init__(self, path: str, model_config: Optional[ModelConfig] =
None):
125 @brief Creates a Model object from the specified MXQ model file and configuration.
127 Parses the MXQ file and constructs a Model object using the provided configuration,
128 initializing the model with the given settings.
130 @note The created Model object must be launched before performing inference.
131 See Model.launch for more details.
133 @param[in] path The path to the MXQ model file.
134 @param[in] model_config The configuration settings to initialize the Model.
136 if model_config
is None:
137 self.
_model = _cQbRuntime.Model(path)
139 self.
_model = _cQbRuntime.Model(path, model_config._model_config)
146 def launch(self, acc: Accelerator) ->
None:
148 @brief Launches the model on the specified Accelerator, which represents
151 @param[in] acc The accelerator on which to launch the model.
158 @brief Disposes of the model loaded onto the NPU.
160 Releases any resources associated with the model on the NPU.
167 @brief Checks if the NPU core specified by CoreId is the target of the model.
168 In other words, whether the model is configured to use the given NPU core.
170 @param[in] core_id The CoreId to check.
171 @return True if the model is configured to use the specified CoreId, false
178 @brief Retrieves the core mode of the model.
180 @return The CoreMode of the model.
186 @brief Returns the supported target device name(s) this model can run on.
188 Returns device names from the model's target device in the MXQ file. A single
189 model may map to multiple names (e.g. a REGULUS model returns both SoC and
190 USB devices). Any of the returned names can be passed to `Accelerator(device_name=)`.
192 @return A list of supported target device names.
198 @brief Returns the NPU cores the model is configured to use.
200 @return A list of CoreIds representing the target NPU cores.
202 return [CoreId.from_cpp(target)
for target
in self.
_model.target_cores]
207 return [CoreId.from_cpp(target)
for target
in self.
_model.target_cores]
211 inputs: Union[np.ndarray, List[np.ndarray]],
212 outputs: Optional[List[np.ndarray]] =
None,
214 params: Optional[List[BatchParam]] =
None,
215 ) -> Optional[List[np.ndarray]]:
217 @brief Performs inference.
219 Fowllowing types of inference supported.
220 1. infer(in:List[numpy]) -> List[numpy] (float / int)
221 2. infer(in:numpy) -> List[numpy] (float / int)
222 3. infer(in:List[numpy], out:List[numpy]) (float / int)
223 4. infer(in:List[numpy], out:List[]) (float / int)
224 5. infer(in:numpy, out:List[numpy]) (float / int)
225 6. infer(in:numpy, out:List[]) (float / int)
227 @param[in] inputs Input data as a single numpy.ndarray or a list
229 @param[out] outputs Optional pre-allocated list of numpy.ndarray's
230 to store inference results.
231 @param[in] cache_size The number of tokens accumulated in the KV cache so far.
232 @param[in] params A List of `BatchParam`, specifying each batch's information
233 for BatchLLM inference. If `params` is specified,
234 `cache_size` is ignored.
235 @return Inference results as a list of numpy.ndarray.
237 return self.
_infer(inputs, outputs, cache_size, params=params)
241 inputs: Union[np.ndarray, List[np.ndarray]],
242 outputs: Optional[List[np.ndarray]] =
None,
244 params: Optional[List[BatchParam]] =
None,
245 ) -> Optional[List[np.ndarray]]:
246 return self.
_infer(inputs, outputs, cache_size,
True, params)
250 inputs: Union[np.ndarray, List[np.ndarray]],
251 outputs: Optional[List[np.ndarray]] =
None,
253 params: Optional[List[BatchParam]] =
None,
254 ) -> Optional[List[np.ndarray]]:
255 return self.
_infer(inputs, outputs, cache_size,
False, params)
259 inputs: Union[np.ndarray, List[np.ndarray]],
260 outputs: Optional[List[np.ndarray]],
262 is_target_hwc: Optional[bool] =
None,
263 params: Optional[List[BatchParam]] =
None,
264 ) -> Optional[List[np.ndarray]]:
265 if not isinstance(inputs, list):
268 variant_idx, (is_hwc, is_chw) = _find_matching_variant_idx_and_memory_format(
271 if (is_target_hwc
is not None)
and (
272 (is_target_hwc != is_hwc)
and (is_target_hwc == is_chw)
274 raise ValueError(
"Input shape is invalid.")
275 elif is_target_hwc
is None:
276 is_target_hwc = is_hwc
277 inputs = [np.ascontiguousarray(i)
for i
in inputs]
279 infer_func = self.
_model.infer
if is_target_hwc
else self.
_model.infer_chw
283 return [np.asarray(o)
for o
in infer_func(inputs, cache_size)]
288 inputs, [param._batch_param
for param
in params]
293 _check_output_shapes(
299 for oi
in range(len(outputs)):
300 outputs[oi] = np.ascontiguousarray(outputs[oi])
302 outputs[:] = _build_outputs(
309 infer_func(inputs, outputs, cache_size)
311 infer_func(inputs, outputs, [param._batch_param
for param
in params])
320 ) -> List[np.ndarray]:
322 @brief int8_t-to-float inference
323 Performs inference with input and output elements of type `int8_t`
325 Using these inference APIs requires manual scaling (quantization)
326 of float values to `int8_t` for input.
328 @note These APIs are intended for advanced use rather than typical usage.
332 def infer_hwc_to_float(
339 ) -> List[np.ndarray]:
342 def infer_chw_to_float(
349 ) -> List[np.ndarray]:
359 is_target_hwc: Optional[bool] =
None,
360 ) -> List[np.ndarray]:
362 @brief int8_t-to-float inference
363 Performs inference with input and output elements of type `int8_t`
365 Using these inference APIs requires manual scaling (quantization)
366 of float values to `int8_t` for input.
368 @note These APIs are intended for advanced use rather than typical usage.
370 if not isinstance(inputs, list):
373 _, (is_hwc, is_chw) = _find_matching_variant_idx_and_memory_format(self, inputs)
374 if (is_target_hwc
is not None)
and (
375 (is_target_hwc != is_hwc)
and (is_target_hwc == is_chw)
377 raise ValueError(
"Input shape is invalid.")
378 elif is_target_hwc
is None:
379 is_target_hwc = is_hwc
380 inputs = [np.ascontiguousarray(i)
for i
in inputs]
385 outputs = self.
_model.infer_chw_to_float(inputs, cache_size)
387 return [np.asarray(o)
for o
in outputs]
391 inputs: List[Buffer],
392 outputs: List[Buffer],
393 shape: List[List[int]] = [],
397 @brief Buffer-to-Buffer inference
399 Performs inference using input and output elements in the NPU’s internal data type.
400 The inference operates on buffers allocated via the following APIs:
402 - `Model.acquire_input_buffer()`
403 - `Model.acquire_output_buffer()`
404 - `ModelVariantHandle.acquire_input_buffer()`
405 - `ModelVariantHandle.acquire_output_buffer()`
407 Additionally, `Model.reposition_inputs()`, `Model.reposition_outputs()`,
408 `ModelVariantHandle.reposition_inputs()`, `ModelVariantHandle.reposition_outputs()`
409 must be used properly.
411 @note These APIs are intended for advanced use rather than typical usage.
414 [i._buffer
for i
in inputs], [o._buffer
for o
in outputs], shape, cache_size
419 @brief Development-only API for measuring pure NPU inference speed.
421 Runs NPU inference without uploading inputs and without retrieving outputs.
427 inputs: List[PinnedMemory],
428 outputs: Optional[List[PinnedMemory]] =
None,
430 ) -> Optional[List[PinnedMemory]]:
432 @brief Performs inference directly on pinned memory buffers (zero-copy).
434 The NPU reads the inputs from and writes the outputs into the pinned
435 buffers in place, avoiding host-to-device copies of the I/O tensors. Write
436 the input data into each input buffer via indexing (e.g. `pm[...] = data`)
437 before calling, and read the results from the output buffers afterwards.
439 @note This is an experimental API and is only supported on REGULUS device.
440 It is not supported for models that use CPU offload.
442 @param inputs A list of PinnedMemory buffers holding the input data. All
443 inputs must share the same dtype (`numpy.float32` or
445 @param outputs A list of pre-allocated PinnedMemory buffers (dtype
446 `numpy.float32`) that will receive the output data. If `None`
447 (the default), the output buffers are allocated internally and
448 returned by this method.
449 @param cache_size The size of the cache to use for inference.
450 @return If `outputs` is `None`, a list of newly allocated PinnedMemory
451 buffers (dtype `numpy.float32`) holding the output data; otherwise
452 `None` (the given `outputs` are filled in place).
456 [pm._pinned_memory
for pm
in inputs],
463 [pm._pinned_memory
for pm
in inputs],
464 [pm._pinned_memory
for pm
in outputs],
473 upload: bool =
False,
474 dtype: Optional[DataType] =
None,
477 @brief Acquires an NPUData for the model input at the given index.
479 @note This is an advanced API rather than a typical usage. (Running inference on
480 the acquired NPUData via `infer_npu_data` additionally requires a
481 single-NPU-op, non-CPU-offload, relocatable (MXQv7+) model.)
482 @warning This API is in beta: it may still contain bugs, and its behavior may
483 change in a future release.
485 @param shape The shape of the input tensor, in NHWC/HWC layout.
486 @param idx The index of the model input.
487 @param upload If True, NPU memory is allocated and the data is placed on the
488 NPU; otherwise the data is kept on the host (CPU).
489 @param dtype The element type of the data. `None` (the default) uses the
490 model's user-facing input type. Pass `DataType.Int8` to hand the
491 model data that is already quantized to the NPU-native type, which
492 skips the host-side quantization.
493 @return The acquired NPUData.
495 shape = [int(s)
for s
in shape]
506 upload: bool =
False,
507 dtype: Optional[DataType] =
None,
510 @brief Acquires an NPUData for the model output at the given index.
512 @note This is an advanced API rather than a typical usage. (Running inference on
513 the acquired NPUData via `infer_npu_data` additionally requires a
514 single-NPU-op, non-CPU-offload, relocatable (MXQv7+) model.)
515 @warning This API is in beta: it may still contain bugs, and its behavior may
516 change in a future release.
518 @param shape The shape of the output tensor, in NHWC/HWC layout.
519 @param idx The index of the model output.
520 @param upload If True, NPU memory is allocated and the data is placed on the
521 NPU; otherwise the data is kept on the host (CPU).
522 @param dtype The element type of the data. `None` (the default) uses the
523 model's user-facing output type. Pass `DataType.Int8` to receive
524 the raw NPU-native output, which skips the host-side
526 @return The acquired NPUData.
528 shape = [int(s)
for s
in shape]
537 inputs: List[NPUData],
538 outputs: Optional[List[NPUData]] =
None,
540 ) -> Optional[List[NPUData]]:
542 @brief Performs inference using NPUData for both inputs and outputs.
544 Every input and output NPUData must share the same residency: either all of
545 them are on the host (acquired with `upload=False`) or all of them are already
546 on the NPU (acquired with `upload=True`). A mixed set results in an error.
548 @note This is an advanced API rather than a typical usage. Only single-NPU-op
549 (non-CPU-offload), relocatable (MXQv7+) models are supported.
550 @warning This API is in beta: it may still contain bugs, and its behavior may
551 change in a future release.
553 @param inputs A list of input NPUData.
554 @param outputs An optional list of pre-allocated output NPUData. If None (the
555 default), the output NPUData are acquired internally and returned.
556 @param cache_size The number of tokens accumulated in the KV cache so far.
557 @return If `outputs` is None, a list of output NPUData holding the inference
558 results; otherwise None (the given `outputs` are filled in place).
562 [d._npu_data
for d
in inputs],
566 return [
NPUData(_out)
for _out
in _outs]
569 [d._npu_data
for d
in inputs],
570 [d._npu_data
for d
in outputs],
577 inputs: List[NPUData],
578 outputs: Optional[List[NPUData]] =
None,
580 ) -> Optional[List[NPUData]]:
582 @brief Performs inference using NPUData in NCHW/CHW layout.
584 Same as `infer_npu_data` except that every input and output NPUData must have
585 been acquired with a NCHW/CHW shape.
587 @note This is an advanced API rather than a typical usage. Only single-NPU-op
588 (non-CPU-offload), relocatable (MXQv7+) models are supported.
589 @warning This API is in beta: it may still contain bugs, and its behavior may
590 change in a future release.
592 @param inputs A list of input NPUData.
593 @param outputs An optional list of pre-allocated output NPUData. If None (the
594 default), the output NPUData are acquired internally and returned.
595 @param cache_size The number of tokens accumulated in the KV cache so far.
596 @return If `outputs` is None, a list of output NPUData holding the inference
597 results; otherwise None (the given `outputs` are filled in place).
601 [d._npu_data
for d
in inputs],
605 return [
NPUData(_out)
for _out
in _outs]
608 [d._npu_data
for d
in inputs],
609 [d._npu_data
for d
in outputs],
616 inputs: Union[np.ndarray, List[np.ndarray]],
619 @brief Asynchronous Inference
621 Performs inference asynchronously.
623 To use asynchronous inference, the model must be created using a `ModelConfig`
624 object with the async pipeline configured to be enabled. This is done by calling
625 @ref ModelConfig.set_async_pipeline_enabled
626 "ModelConfig.set_async_pipeline_enabled(True)" before passing the configuration to
633 mc = qbruntime.ModelConfig()
634 mc.set_async_pipeline_enabled(True)
636 model = qbruntime.Model(MXQ_PATH, mc)
637 acc = qbruntime.Accelerator()
641 future = model.infer_async(inputs)
646 @note Currently, only CNN-based models are supported, as asynchronous execution is
647 particularly effective for this type of workload.
650 - RNN/LSTM and LLM models are not supported yet.
651 - Models requiring CPU offloading are not supported yet.
652 - Currently, only single-batch inference is supported (i.e., N = 1).
653 - Currently, Buffer inference is not supported. The following types
654 are supported in the synchronous API for advanced use cases, but are not
655 yet available for asynchronous inference:
659 if not isinstance(inputs, list):
661 _, (is_hwc, _) = _find_matching_variant_idx_and_memory_format(self, inputs)
662 inputs = [np.ascontiguousarray(i)
for i
in inputs]
664 self.
_model.infer_async
if is_hwc
else self.
_model.infer_async_chw
666 return Future.from_cpp(infer_async_func(inputs), inputs)
670 inputs: Union[np.ndarray, List[np.ndarray]],
673 @brief This method supports int8_t-to-float asynchronous inference.
675 @param[in] inputs Input data as a single numpy.ndarray or a list
678 @return A future that can be used to retrieve the inference result.
680 if not isinstance(inputs, list):
682 _, (is_hwc, _) = _find_matching_variant_idx_and_memory_format(self, inputs)
683 inputs = [np.ascontiguousarray(i)
for i
in inputs]
685 self.
_model.infer_async_to_float
687 else self.
_model.infer_async_chw_to_float
689 return Future.from_cpp(infer_async_func(inputs), inputs)
693 inputs: List[np.ndarray],
694 input_bufs: List[Buffer],
695 seqlens: List[List[int]] = [],
697 """Reposition input"""
698 inputs = [np.ascontiguousarray(i)
for i
in inputs]
700 inputs, [buf._buffer
for buf
in input_bufs], seqlens
705 output_bufs: List[Buffer],
706 outputs: List[np.ndarray],
707 seqlens: List[List[int]] = [],
709 """Reposition output"""
713 outputs.append(np.empty(shape=shape, dtype=np.float32))
715 for oi
in range(len(outputs)):
716 outputs[oi] = np.ascontiguousarray(outputs[oi])
718 [buf._buffer
for buf
in output_bufs], outputs, seqlens
723 @brief Returns the total number of model variants available in this model.
725 The `variant_idx` parameter passed to `Model.get_model_variant_handle()` must be
726 in the range [0, return value of this function).
728 @return The total number of model variants.
734 @brief Retrieves a handle to the specified model variant.
736 Use the returned `ModelVariantHandle` to query details such as input and output
737 shapes for the selected variant.
739 @param[in] variant_idx Index of the model variant to retrieve.
740 Must be in the range [0, getNumModelVariants()).
742 @return A `ModelVariantHandle` object if successful;
743 otherwise, raise qbruntime.QbRuntimeError "Model_InvalidVariantIdx".
745 return ModelVariantHandle.from_cpp(
751 @brief Returns the input shape of the model.
753 @return A list of input shape of the model.
759 @brief Returns the output shape of the model.
761 @return A list of output shape of the model.
767 @brief Returns the input quantization scale(s) of the model.
769 @return A list of input scales.
775 @brief Returns the output quantization scale(s) of the model.
777 @return A list of output scales.
783 @brief Returns the input buffer information for the model.
785 @return A list of input buffer information.
791 @brief Returns the output buffer information of the model.
793 @return A list of output buffer information.
799 @brief Returns a data type for model inputs.
801 @return An input data type.
807 @brief Returns a data type for model outputs.
809 @return An output data type.
815 @brief Buffer Management API
817 Acquires list of `Buffer` for input.
818 These API is required when calling `Model.infer_buffer()`.
820 @note These APIs are intended for advanced use rather than typical usage.
826 @brief Buffer Management API
828 Acquires list of `Buffer` for output.
829 These API is required when calling `Model.infer_buffer()`.
831 @note These APIs are intended for advanced use rather than typical usage.
837 @brief Buffer Management API
839 Deallocate acquired Input/Output buffer
841 @note These APIs are intended for advanced use rather than typical usage.
847 @brief Returns the model's unique identifier.
849 This identifier distinguishes multiple models within a single user program.
850 It is assigned incrementally, starting from 0 (e.g., 0, 1, 2, 3, ...).
852 @return The model identifier.
858 @brief Returns the path to the MXQ model file associated with the Model.
860 @return The MXQ file path.
866 @brief Returns informations of KV-cache of the model.
868 @return A list of CacheInfo objects.
874 @brief Dumps the KV cache memory into buffers.
876 Writes the current KV cache data into provided buffers.
878 @param[in] cache_id Index of target cache.
880 @return A list of bytes containing the KV cache data.
883 return [np.asarray(buf, np.int8).tobytes()
for buf
in bufs]
887 @brief Loads the KV cache memory from buffers.
889 Restores the KV cache from the provided buffers.
891 @param[in] bufs A list of bytes containing the KV cache
894 [np.frombuffer(buf, dtype=np.int8)
for buf
in bufs], cache_id
899 @brief Dumps KV cache memory to files in the specified directory.
901 Writes the KV cache data to binary files within the given directory.
902 Each file is named using the format: `cache_<layer_hash>.bin`.
904 @param[in] cache_dir Path to the directory where KV cache files will be saved.
905 @param[in] cache_id Index of target cache.
911 @brief Loads the KV cache memory from files in the specified directory.
913 Reads KV cache data from files within the given directory and restores them.
914 Each file is named using the format: `cache_<layer_hash>.bin`.
916 @param[in] cache_dir Path to the directory where KV cache files are saved.
921 self, cache_size: int, tail_size: int, mask: List[bool]
924 @brief Filter the tail of the KV cache memory
926 Retains the desired caches in the tail of the KV cache memory, excludes the others,
927 and shifts the remaining caches forward.
929 @param[in] cache_size The number of tokens accumulated in the KV cache so far.
930 @param[in] tail_size The tail size of the KV cache to filter (<=32).
931 @param[in] mask A mask indicating tokens to retain or exclude at the tail of the KV
934 @return New cache size after tail filtering.
940 @brief Moves the tail of the KV cache memory to the end of the head.
942 Slice the tail of the KV cache memory up to the specified size
943 and moves it to the designated cache position.
945 @param[in] num_head The size of the KV cache head where the tail is appended.
946 @param[in] num_tail The size of the KV cache tail to be moved.
947 @param[in] cache_size The total number of tokens accumulated in the KV cache so
950 @return The updated cache size after moving the tail.
955def load(path: str, model_config: Optional[ModelConfig] =
None) -> Model:
957 @brief Single-step inference API. Creates model and uploads the model
958 into NPU immediately.
960 This operation performs the Accelerator declaration, Model declaration,
961 and launch in a single step.
964 model =
Model(path, model_config)
Represents an accelerator, i.e., an NPU, used for executing models.
Represents an AI model loaded from an MXQ file.
DataType get_model_input_data_type(self)
Returns a data type for model inputs.
None launch(self, Accelerator acc)
Launches the model on the specified Accelerator, which represents the actual NPU.
None reposition_outputs(self, List[Buffer] output_bufs, List[np.ndarray] outputs, List[List[int]] seqlens=[])
Reposition output.
List[Scale] get_input_scale(self)
Returns the input quantization scale(s) of the model.
CoreMode get_core_mode(self)
Retrieves the core mode of the model.
List[CoreId] get_target_cores(self)
Returns the NPU cores the model is configured to use.
List[_Shape] _input_shape
List[CoreId] target_cores(self)
List[_Shape] _output_shape
List[Buffer] acquire_input_buffer(self, List[List[int]] seqlens=[])
Buffer Management API.
Optional[List[PinnedMemory]] infer_pinned_memory(self, List[PinnedMemory] inputs, Optional[List[PinnedMemory]] outputs=None, int cache_size=0)
Performs inference directly on pinned memory buffers (zero-copy).
List[BufferInfo] get_output_buffer_info(self)
Returns the output buffer information of the model.
str get_model_path(self)
Returns the path to the MXQ model file associated with the Model.
Optional[List[NPUData]] infer_npu_data_chw(self, List[NPUData] inputs, Optional[List[NPUData]] outputs=None, int cache_size=0)
Performs inference using NPUData in NCHW/CHW layout.
Future infer_async(self, Union[np.ndarray, List[np.ndarray]] inputs)
Asynchronous Inference.
DataType get_model_output_data_type(self)
Returns a data type for model outputs.
NPUData acquire_output_npu_data(self, List[int] shape, int idx=0, bool upload=False, Optional[DataType] dtype=None)
Acquires an NPUData for the model output at the given index.
Optional[List[NPUData]] infer_npu_data(self, List[NPUData] inputs, Optional[List[NPUData]] outputs=None, int cache_size=0)
Performs inference using NPUData for both inputs and outputs.
List[Buffer] acquire_output_buffer(self, List[List[int]] seqlens=[])
Buffer Management API.
int filter_cache_tail(self, int cache_size, int tail_size, List[bool] mask)
Filter the tail of the KV cache memory.
List[np.ndarray] _infer_to_float(self, Union[np.ndarray, List[np.ndarray],] inputs, int cache_size, Optional[bool] is_target_hwc=None)
int8_t-to-float inference Performs inference with input and output elements of type int8_t
int get_num_model_variants(self)
Returns the total number of model variants available in this model.
None load_cache_memory_from(self, str cache_dir, int cache_id=0)
Loads the KV cache memory from files in the specified directory.
bool is_target(self, CoreId core_id)
Checks if the NPU core specified by CoreId is the target of the model.
None infer_speedrun(self)
Development-only API for measuring pure NPU inference speed.
None dump_cache_memory_to(self, str cache_dir, int cache_id=0)
Dumps KV cache memory to files in the specified directory.
Future infer_async_to_float(self, Union[np.ndarray, List[np.ndarray]] inputs)
This method supports int8_t-to-float asynchronous inference.
ModelVariantHandle get_model_variant_handle(self, variant_idx)
Retrieves a handle to the specified model variant.
None load_cache_memory(self, List[bytes] bufs, int cache_id=0)
Loads the KV cache memory from buffers.
List[_Shape] get_model_output_shape(self)
Returns the output shape of the model.
List[CacheInfo] get_cache_infos(self)
Returns informations of KV-cache of the model.
None release_buffer(self, List[Buffer] buffer)
Buffer Management API.
List[bytes] dump_cache_memory(self, int cache_id=0)
Dumps the KV cache memory into buffers.
None dispose(self)
Disposes of the model loaded onto the NPU.
List[_Shape] get_model_input_shape(self)
Returns the input shape of the model.
List[Scale] get_output_scale(self)
Returns the output quantization scale(s) of the model.
None infer_buffer(self, List[Buffer] inputs, List[Buffer] outputs, List[List[int]] shape=[], int cache_size=0)
Buffer-to-Buffer inference.
List[np.ndarray] infer_to_float(self, Union[np.ndarray, List[np.ndarray],] inputs, int cache_size=0)
int8_t-to-float inference Performs inference with input and output elements of type int8_t
List[str] get_device_names(self)
Returns the supported target device name(s) this model can run on.
__init__(self, str path, Optional[ModelConfig] model_config=None)
Creates a Model object from the specified MXQ model file and configuration.
Optional[List[np.ndarray]] _infer(self, Union[np.ndarray, List[np.ndarray]] inputs, Optional[List[np.ndarray]] outputs, int cache_size, Optional[bool] is_target_hwc=None, Optional[List[BatchParam]] params=None)
Optional[List[np.ndarray]] infer(self, Union[np.ndarray, List[np.ndarray]] inputs, Optional[List[np.ndarray]] outputs=None, int cache_size=0, Optional[List[BatchParam]] params=None)
Performs inference.
NPUData acquire_input_npu_data(self, List[int] shape, int idx=0, bool upload=False, Optional[DataType] dtype=None)
Acquires an NPUData for the model input at the given index.
None reposition_inputs(self, List[np.ndarray] inputs, List[Buffer] input_bufs, List[List[int]] seqlens=[])
Reposition input.
List[BufferInfo] get_input_buffer_info(self)
Returns the input buffer information for the model.
int get_identifier(self)
Returns the model's unique identifier.
int move_cache_tail(self, int num_head, int num_tail, int cache_size)
Moves the tail of the KV cache memory to the end of the head.
A model input or output tensor that can reside on the host (CPU) or NPU.
An NPU-accessible pinned (physically contiguous) memory buffer.
A simple byte-sized buffer.
Defines the core mode for NPU execution.
Model load(str path, Optional[ModelConfig] model_config=None)
Single-step inference API.