5from typing
import List, Optional, Tuple, overload
10import qbruntime.qbruntime
as _cQbRuntime
19 @brief Enumerates clusters in the ARIES NPU.
21 @note The ARIES NPU consists of two clusters, each containing one global core and
22 four local cores, totaling eight local cores. REGULUS has only a single cluster
23 (Cluster0) with one local core (Core0).
26 Cluster0 = _cQbRuntime.Cluster.Cluster0
27 Cluster1 = _cQbRuntime.Cluster.Cluster1
28 Error = _cQbRuntime.Cluster.Error
33 @brief Enumerates cores within a cluster in the ARIES NPU.
35 @note The ARIES NPU consists of two clusters, each containing one global core and
36 four local cores, totaling eight local cores. REGULUS has only a single cluster
37 (Cluster0) with one local core (Core0).
40 Core0 = _cQbRuntime.Core.Core0
41 Core1 = _cQbRuntime.Core.Core1
42 Core2 = _cQbRuntime.Core.Core2
43 Core3 = _cQbRuntime.Core.Core3
44 All = _cQbRuntime.Core.All
45 GlobalCore = _cQbRuntime.Core.GlobalCore
46 Error = _cQbRuntime.Core.Error
50 """@brief Core allocation policy"""
52 Auto = _cQbRuntime.CoreAllocationPolicy.Auto
53 Manual = _cQbRuntime.CoreAllocationPolicy.Manual
57 """@brief Struct for scale values."""
63 scale_list: List[float],
65 is_asymmetric: bool =
False,
66 zero_points: Optional[List[int]] =
None,
68 self.
_scale = _cQbRuntime.Scale()
70 self.
_scale.is_uniform = is_uniform
71 self.
_scale.scale_list = scale_list
72 self.
_scale.zero_point = zero_point
73 self.
_scale.is_asymmetric = is_asymmetric
74 self.
_scale.zero_points = zero_points
if zero_points
is not None else []
77 def from_cpp(cls, _scale: _cQbRuntime.Scale):
88 def scale_list(self) -> List[float]:
89 return self.
_scale.scale_list
92 def scale(self) -> float:
96 def is_uniform(self) -> bool:
97 return self.
_scale.is_uniform
101 """Per-channel zero points for asymmetric quantization."""
102 return self.
_scale.zero_points
106 """Uniform zero point for asymmetric quantization."""
107 return self.
_scale.zero_point
111 """Indicates whether asymmetric quantization is used."""
112 return self.
_scale.is_asymmetric
115 def scale_list(self, value: List[float]):
116 self.
_scale.scale_list = value
119 def scale(self, value: float):
123 def is_uniform(self, value: bool):
124 self.
_scale.is_uniform = value
128 self.
_scale.zero_points = value
132 self.
_scale.zero_point = value
134 @is_asymmetric.setter
136 self.
_scale.is_asymmetric = value
140 @brief Returns the scale value at the specified index.
156 return "{}({})".format(
157 self.__class__.__name__,
158 ", ".join(
"{}={}".format(k, v)
for k, v
in d.items()),
164 @brief Represents a unique identifier for an NPU core.
166 A CoreId consists of a Cluster and a Core, identifying a specific core
170 def __init__(self, cluster: Cluster, core: Core):
171 self.
_core_id = _cQbRuntime.CoreId()
172 self.
_core_id.cluster = cluster.value
176 def from_cpp(cls, _core_id: _cQbRuntime.CoreId):
177 return cls(
Cluster(_core_id.cluster),
Core(_core_id.core))
180 def cluster(self) -> Cluster:
184 def core(self) -> Core:
188 def cluster(self, value: Cluster):
192 def core(self, value: Core):
197 @brief Checks if two CoreId objects are equal.
199 @return True if both CoreId objects are identical, False otherwise.
201 return self.
_core_id == other._core_id
205 @brief Compares two CoreId objects for ordering.
207 @return True if this CoreId is less than the given CoreId, False otherwise.
209 return self.
_core_id < other._core_id
213 return "{}({})".format(
214 self.__class__.__name__,
215 ", ".join(
"{}={}".format(k, v)
for k, v
in d.items()),
221 @brief A simple byte-sized buffer.
223 This struct represents a contiguous block of memory for storing byte-sized data.
226 def __init__(self, _buffer: Optional[_cQbRuntime.Buffer] =
None):
227 self.
_buffer = _cQbRuntime.Buffer()
if _buffer
is None else _buffer
230 def size(self) -> int:
234 def size(self, value: int):
237 def set_buffer(self, arr: np.ndarray):
238 self.
_buffer.set_buffer(np.ascontiguousarray(arr))
241 return f
"{self.__class__.__name__}(size={self._buffer.size})"
246 @brief Defines the core mode for NPU execution.
248 Supported core modes include single-core, multi-core, global4-core, and global8-core.
249 For detailed explanations of each mode, refer to the following functions:
251 - `ModelConfig.set_auto_core_mode()`
252 - `ModelConfig.set_single_core_mode()`
253 - `ModelConfig.set_multi_core_mode()`
254 - `ModelConfig.set_global4_core_mode()`
255 - `ModelConfig.set_global8_core_mode()`
258 Single = _cQbRuntime.CoreMode.Single
259 Multi = _cQbRuntime.CoreMode.Multi
260 Global = _cQbRuntime.CoreMode.Global
261 Global4 = _cQbRuntime.CoreMode.Global4
262 Global8 = _cQbRuntime.CoreMode.Global8
263 Auto = _cQbRuntime.CoreMode.Auto
264 Error = _cQbRuntime.CoreMode.Error
268 """@brief Struct representing input/output buffer information."""
272 original_height: int = 0,
273 original_width: int = 0,
274 original_channel: int = 0,
275 reshaped_height: int = 0,
276 reshaped_width: int = 0,
277 reshaped_channel: int = 0,
283 max_channel: int = 0,
284 max_cache_size: int = 0,
302 def from_cpp(cls, _buffer_info: _cQbRuntime.BufferInfo):
304 _buffer_info.original_height,
305 _buffer_info.original_width,
306 _buffer_info.original_channel,
307 _buffer_info.reshaped_height,
308 _buffer_info.reshaped_width,
309 _buffer_info.reshaped_channel,
312 _buffer_info.channel,
313 _buffer_info.max_height,
314 _buffer_info.max_width,
315 _buffer_info.max_channel,
316 _buffer_info.max_cache_size,
321 """Height of original input/output"""
326 """Width of original input/output"""
331 """Channel of original input/output"""
336 """Height of reshaped input/output"""
341 """Width of reshaped input/output"""
346 """Channel of reshaped input/output"""
351 """Height of NPU input/output"""
356 """Width of NPU input/output"""
361 """Channel of NPU input/output"""
366 """Maximum height of original input/output if data is sequential."""
371 """Maximum width of original input/output if data is sequential."""
376 """Maximum channel of original input/output if data is sequential."""
381 """Maximum KV-cache size, relevant for LLM models using KV cache."""
384 @original_height.setter
388 @original_width.setter
392 @original_channel.setter
396 @reshaped_height.setter
400 @reshaped_width.setter
404 @reshaped_channel.setter
409 def height(self, value: int):
413 def width(self, value: int):
432 @max_cache_size.setter
438 @brief Returns the total size of the original input/output.
440 @return The data size.
446 @brief Returns the total size of the reshaped input/output.
448 @return The data size.
454 @brief Returns the total size of the NPU input/output.
456 @return The data size.
460 def original_shape(self) -> Tuple[int, int, int]:
463 def original_shape_chw(self) -> Tuple[int, int, int]:
466 def reshaped_shape(self) -> Tuple[int, int, int]:
469 def reshaped_shape_chw(self) -> Tuple[int, int, int]:
472 def shape(self) -> Tuple[int, int, int]:
475 def shape_chw(self) -> Tuple[int, int, int]:
494 return "{}({})".format(
495 self.__class__.__name__,
496 ", ".join(
"{}={}".format(k, v)
for k, v
in d.items()),
502 @brief Configures a core mode and core allocation of a model for NPU inference.
503 The `ModelConfig` class provides methods for setting a core mode and allocating
504 cores for NPU inference. Supported core modes are single-core, multi-core,
505 global4-core, and global8-core. Users can also specify which cores to allocate for
506 the model. Additionally, the configuration offers an option to enforce the use of a
509 @note Deprecated functions are included for backward compatibility, but it is
510 recommended to use the newer core mode configuration methods.
513 def __init__(self, num_cores: Optional[int] =
None):
515 @brief Default constructor. This default-constructed object is initially set to
519 _cQbRuntime.ModelConfig()
521 else _cQbRuntime.ModelConfig(num_cores)
526 @brief Sets the model to detect CoreMode automatically.
528 In auto-core mode, the model automatically detects a supported CoreMode
529 while using all available NPU cores.
531 @note If the model has more than one CoreMode, `CoreMode.Auto` is not supported.
533 @note activation buffer slots will be reset after `set_auto_core_mode` is called.
535 @return True if the mode was successfully set, False otherwise.
540 def set_single_core_mode(self, num_cores: int) -> bool: ...
543 def set_single_core_mode(self, core_ids: List[CoreId]) -> bool: ...
545 def set_single_core_mode(self, num_cores=None, core_ids=None) -> bool:
547 @brief Sets the model to use single-core mode for inference with a specified number
550 In single-core mode, each local core executes model inference independently.
551 The number of cores used is specified by the `num_cores` parameter, and the core
552 allocation policy is set to `CoreAllocationPolicy.Auto`, meaning the model will be
553 automatically allocated to available local cores when the model is launched to the
554 NPU, specifically when the `Model.launch()` function is called. Or The user can
555 specify a list of CoreIds to determine which cores to use for inference.
557 @param[in] num_cores The number of local cores to use for inference.
558 @param[in] core_ids A list of CoreIds to be used for model inference.
560 @return True if the mode was successfully set, False otherwise.
562 @note Supported call forms (provide exactly one of `num_cores` / `core_ids`):
563 - `set_single_core_mode(num_cores)`:
564 auto-allocate `num_cores` local cores. (deprecated in latest models)
565 - `set_single_core_mode(core_ids)`:
566 use exactly the cores listed in `core_ids`.
569 if isinstance(num_cores, (list, tuple))
and core_ids
is None:
570 num_cores, core_ids =
None, num_cores
571 if num_cores
is not None and core_ids
is None:
573 elif core_ids
is not None and num_cores
is None:
575 [core_id._core_id
for core_id
in core_ids]
578 "`set_single_core_mode` needs either `num_cores` or `core_ids`."
586 self, clusters: List[Cluster] = [Cluster.Cluster0, Cluster.Cluster1]
589 @brief Sets the model to use global4-core mode for inference with a specified set
592 For Aries NPU, there are two clusters, each consisting of four local cores. In
593 global4-core mode, four local cores within the same cluster work together to
594 execute the model inference.
596 @param[in] clusters A list of clusters to be used for model inference.
598 @return True if the mode was successfully set, False otherwise.
604 @brief Sets the model to use global8-core mode for inference.
606 For Aries NPU, there are two clusters, each consisting of four local cores. In
607 global8-core mode, all eight local cores across the two clusters work together to
608 execute the model inference.
610 @return True if the mode was successfully set, False otherwise.
616 @brief Gets the core mode to be applied to the model.
618 This reflects the core mode that will be used when the model is created.
620 @return The `CoreMode` to be applied to the model.
625 self, clusters: List[Cluster] = [Cluster.Cluster0, Cluster.Cluster1]
628 @brief Sets the model to use multi-core mode for batch inference.
630 In multi-core mode, on Aries NPU, the four local cores within a cluster work
631 together to process batch inference tasks efficiently. This mode is optimized for
634 @param[in] clusters A list of clusters to be used for multi-core batch inference.
636 @return True if the mode was successfully set, False otherwise.
642 @brief Gets the core allocation policy to be applied to the model.
644 This reflects the core allocation policy that will be used when the model is
647 @return The `CoreAllocationPolicy` to be applied to the model.
653 @brief Gets the number of cores to be allocated for the model.
655 This represents the number of cores that will be allocated for inference
656 when the model is launched to the NPU.
658 @return The number of cores to be allocated for the model.
664 @brief Forces the use of a specific NPU bundle.
666 This function forces the selection of a specific NPU bundle. If a non-negative
667 index is provided, the corresponding NPU bundle is selected and runs without CPU
668 offloading. If -1 is provided, all NPU bundles are used with CPU offloading
671 @param[in] npu_bundle_index The index of the NPU bundle to force. A non-negative
672 integer selects a specific NPU bundle (runs without CPU
673 offloading), or -1 to enable all NPU bundles with CPU
676 @return True if the index is valid and the NPU bundle is successfully set,
677 False if the index is invalid (less than -1).
683 @brief Retrieves the index of the forced NPU bundle.
685 This function returns the index of the NPU bundle that has been forced using the
686 `force_single_npu_bundle` function. If no NPU bundle is forced, the returned value
689 @return The index of the forced NPU bundle, or -1 if no bundle is forced.
695 @brief Enables or disables the asynchronous pipeline required for asynchronous
698 Call this function with `enable` set to `True` if you intend to use
699 `Model.infer_async()`, as the asynchronous pipeline is necessary for their operation.
701 If you are only using synchronous inference, such as `Model.infer()` or
702 `Model.infer_to_float()`, it is recommended to keep the asynchronous pipeline disabled
703 to avoid unnecessary overhead.
705 @param[in] enable Set to `True` to enable the asynchronous pipeline; set to `False`
712 @brief Returns whether the asynchronous pipeline is enabled in this configuration.
714 @return `True` if the asynchronous pipeline is enabled; `False` otherwise.
720 @brief Sets activation buffer slots for multi-activation supported model.
722 all this function if you want to set the number of activation buffer slots manually.
724 If you do not call this function, the default number of activation buffer slots
725 is set differently depending on the CoreMode.
727 - `CoreMode.Single` : 2 * (the number of target core ids)
728 - `CoreMode.Multi` : 2 * (the number of target clusters)
729 - `CoreMode.Global4` : 2 * (the number of target clusters)
730 - `CoreMode.Global8` : 2
732 @note This function has no effect on MXQ file in version earlier than MXQv7.
734 @note Currently, LLM model's activation slot is fixed to 1 and ignoring `count`.
736 @param[in] count Multi activation counts. Must be >= 1.
742 @brief Returns activation buffer slot count.
744 @note This function has no meaning on MXQ file in version earlier than MXQv7.
746 @return Activation buffer slot count.
752 @brief Returns the list of NPU CoreIds to be used for model inference.
754 The returned list reflects only what was set on this ModelConfig.
755 What it contains depends on the configured CoreMode:
756 - Single mode via `set_single_core_mode(core_ids)`: the specified core_ids.
757 - Single mode via `set_single_core_mode(num_cores)`: empty. The actual cores
758 are resolved from the target NPU when the model is created.
759 - Multi, Global4, Global8, and Auto modes: empty. Use `get_clusters()` for the
762 @return A list of NPU CoreIds.
771 @brief Returns the list of clusters to be used for model inference.
773 The returned list reflects only what was set on this ModelConfig.
774 What it contains depends on the configured CoreMode:
775 - Multi mode via `set_multi_core_mode()` and Global4 mode via
776 `set_global4_core_mode()`: the specified clusters (defaults to all clusters).
777 - Single, Global8, and Auto modes: empty.
779 @return A list of NPU Clusters.
792 return "{}({})".format(
793 self.__class__.__name__,
794 ", ".join(
"{}={}".format(k, v)
for k, v
in d.items()),
799 """@brief LogLevel"""
801 Debug = _cQbRuntime.LogLevel.Debug
802 Info = _cQbRuntime.LogLevel.Info
803 Warn = _cQbRuntime.LogLevel.Warn
804 Err = _cQbRuntime.LogLevel.Err
805 Fatal = _cQbRuntime.LogLevel.Fatal
806 Off = _cQbRuntime.LogLevel.Off
809def set_log_level(level: LogLevel):
810 _cQbRuntime.set_log_level(level.value)
814 """@brief CacheType"""
816 Default = _cQbRuntime.CacheType.Default
817 Batch = _cQbRuntime.CacheType.Batch
818 Error = _cQbRuntime.CacheType.Error
822 """@brief Struct representing KV-cache information."""
826 cache_type: CacheType = CacheType.Error,
828 layer_hash: str =
"",
830 num_batches: int = 0,
840 def from_cpp(cls, _cache_info: _cQbRuntime.CacheInfo):
844 _cache_info.layer_hash,
846 _cache_info.num_batches,
850 def cache_type(self) -> CacheType:
854 def name(self) -> str:
858 def layer_hash(self) -> str:
862 def size(self) -> int:
866 def num_batches(self) -> int:
870 def cache_type(self, value: CacheType):
874 def name(self, value: str):
878 def layer_hash(self, value: str):
882 def size(self, value: int):
886 def num_batches(self, value: int):
891 """@brief DataType"""
893 Float32 = _cQbRuntime.DataType.Float32
894 Float16 = _cQbRuntime.DataType.Float16
895 Int8 = _cQbRuntime.DataType.Int8
896 Uint8 = _cQbRuntime.DataType.Uint8
897 BInt16 = _cQbRuntime.DataType.BInt16
898 Error = _cQbRuntime.DataType.Error
902 """@brief Struct containing BatchLLM parameters."""
906 sequence_length: int = 0,
921 return "{}({})".format(
922 self.__class__.__name__,
923 ", ".join(
"{}={}".format(k, v)
for k, v
in d.items()),
927 def sequence_length(self) -> int:
931 def cache_size(self) -> int:
935 def cache_id(self) -> int:
938 @sequence_length.setter
939 def sequence_length(self, value: int):
943 def cache_size(self, value: int):
947 def cache_id(self, value: int):
953 @brief Starts event tracing and prepares to save the trace log to a specified file.
955 The trace log is recorded in "Chrome Tracing JSON format," which can be
956 viewed at https://ui.perfetto.dev/.
958 The trace log is not written immediately; it is saved only when
959 stop_tracing_events() is called.
961 @param[in] path The file path where the trace log should be stored.
962 @return True if tracing starts successfully, False otherwise.
964 return _cQbRuntime.start_tracing_events(path)
969 @brief Stops event tracing and writes the recorded trace log.
971 This function finalizes tracing and saves the collected trace data
972 to the file specified when start_tracing_events() was called.
974 _cQbRuntime.stop_tracing_events()
979 @brief Generates a structured summary of the specified MXQ model.
981 Returns an overview of the model contained in the MXQ file, including:
983 - Supported core modes and their associated cores
984 - The total number of model variants
986 - Input and output tensor shapes
987 - A list of layers with their types, output shapes, and input layer indices
989 The summary is returned as a human-readable string in a table and is useful for
990 inspecting model compatibility, structure, and input/output shapes.
992 @param[in] mxq_path Path to the MXQ model file.
993 @return A formatted string containing the model summary.
995 return _cQbRuntime.get_model_summary(mxq_path)
1000 @brief Get the device names of the NPU devices detected on the system.
1002 @return The detected device names (e.g. "aries-rb", "regulus-ra").
1003 Empty if no NPU device is detected.
1005 return _cQbRuntime.get_available_devices()
1010 @brief Get the available device numbers of the given device.
1012 @param device_name The device name ("auto" or a name such as "aries", "aries-rb",
1013 "regulus", "regulus-ra"; case-insensitive).
1014 @return The available device numbers. Empty if `device_name` cannot be resolved.
1016 return _cQbRuntime.get_available_device_numbers(device_name)
Struct containing BatchLLM parameters.
int sequence_length(self)
Struct representing input/output buffer information.
int reshaped_width(self)
Width of reshaped input/output.
int max_channel(self)
Maximum channel of original input/output if data is sequential.
int original_height(self)
Height of original input/output.
int width(self)
Width of NPU input/output.
int max_cache_size(self)
Maximum KV-cache size, relevant for LLM models using KV cache.
int max_height(self)
Maximum height of original input/output if data is sequential.
int original_size(self)
Returns the total size of the original input/output.
int height(self)
Height of NPU input/output.
int original_width(self)
Width of original input/output.
int channel(self)
Channel of NPU input/output.
int size(self)
Returns the total size of the NPU input/output.
int max_width(self)
Maximum width of original input/output if data is sequential.
int reshaped_channel(self)
Channel of reshaped input/output.
int original_channel(self)
Channel of original input/output.
int reshaped_size(self)
Returns the total size of the reshaped input/output.
int reshaped_height(self)
Height of reshaped input/output.
A simple byte-sized buffer.
Struct representing KV-cache information.
Enumerates clusters in the ARIES NPU.
Represents a unique identifier for an NPU core.
bool __eq__(self, other)
Checks if two CoreId objects are equal.
bool __lt__(self, other)
Compares two CoreId objects for ordering.
Defines the core mode for NPU execution.
Enumerates cores within a cluster in the ARIES NPU.
Configures a core mode and core allocation of a model for NPU inference.
List[CoreId] get_core_ids(self)
Returns the list of NPU CoreIds to be used for model inference.
bool get_forced_npu_bundle_index(self)
Retrieves the index of the forced NPU bundle.
bool set_global8_core_mode(self)
Sets the model to use global8-core mode for inference.
bool set_multi_core_mode(self, List[Cluster] clusters=[Cluster.Cluster0, Cluster.Cluster1])
Sets the model to use multi-core mode for batch inference.
bool set_global_core_mode(self, List[Cluster] clusters)
bool force_single_npu_bundle(self, int npu_bundle_index)
Forces the use of a specific NPU bundle.
__init__(self, Optional[int] num_cores=None)
Default constructor.
List[Cluster] get_clusters(self)
Returns the list of clusters to be used for model inference.
CoreMode get_core_mode(self)
Gets the core mode to be applied to the model.
None set_async_pipeline_enabled(self, bool enable)
Enables or disables the asynchronous pipeline required for asynchronous inference.
bool get_async_pipeline_enabled(self)
Returns whether the asynchronous pipeline is enabled in this configuration.
int get_activation_slots(self)
Returns activation buffer slot count.
bool set_auto_core_mode(self)
Sets the model to detect CoreMode automatically.
None set_activation_slots(self, int num)
Sets activation buffer slots for multi-activation supported model.
int get_num_cores(self)
Gets the number of cores to be allocated for the model.
bool set_global4_core_mode(self, List[Cluster] clusters=[Cluster.Cluster0, Cluster.Cluster1])
Sets the model to use global4-core mode for inference with a specified set of NPU clusters.
CoreAllocationPolicy get_core_allocation_policy(self)
Gets the core allocation policy to be applied to the model.
List[int] zero_points(self)
Per-channel zero points for asymmetric quantization.
int zero_point(self)
Uniform zero point for asymmetric quantization.
bool is_asymmetric(self)
Indicates whether asymmetric quantization is used.
float __getitem__(self, int i)
Returns the scale value at the specified index.
List[float] scale_list(self)
List[str] get_available_devices()
Get the device names of the NPU devices detected on the system.
str get_model_summary(str mxq_path)
Generates a structured summary of the specified MXQ model.
List[int] get_available_device_numbers(str device_name="auto")
Get the available device numbers of the given device.
bool start_tracing_events(str path)
Starts event tracing and prepares to save the trace log to a specified file.
stop_tracing_events()
Stops event tracing and writes the recorded trace log.