5from typing
import List, Optional, Tuple
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 self, num_cores: Optional[int] =
None, core_ids: Optional[List[CoreId]] =
None
543 @brief Sets the model to use single-core mode for inference with a specified number
546 In single-core mode, each local core executes model inference independently.
547 The number of cores used is specified by the `num_cores` parameter, and the core
548 allocation policy is set to `CoreAllocationPolicy.Auto`, meaning the model will be
549 automatically allocated to available local cores when the model is launched to the
550 NPU, specifically when the `Model.launch()` function is called. Or The user can
551 specify a list of CoreIds to determine which cores to use for inference.
553 @note Use exactly one of `num_cores` or `core_ids`, not both.
555 @param[in] num_cores The number of local cores to use for inference.
556 @param[in] core_ids A list of CoreIds to be used for model inference.
558 @return True if the mode was successfully set, False otherwise.
560 if num_cores
is not None and core_ids
is None:
562 elif core_ids
is not None and num_cores
is None:
564 [core_id._core_id
for core_id
in core_ids]
567 "`set_single_core_mode` needs either `num_cores` and `core_ids`."
575 self, clusters: List[Cluster] = [Cluster.Cluster0, Cluster.Cluster1]
578 @brief Sets the model to use global4-core mode for inference with a specified set
581 For Aries NPU, there are two clusters, each consisting of four local cores. In
582 global4-core mode, four local cores within the same cluster work together to
583 execute the model inference.
585 @param[in] clusters A list of clusters to be used for model inference.
587 @return True if the mode was successfully set, False otherwise.
593 @brief Sets the model to use global8-core mode for inference.
595 For Aries NPU, there are two clusters, each consisting of four local cores. In
596 global8-core mode, all eight local cores across the two clusters work together to
597 execute the model inference.
599 @return True if the mode was successfully set, False otherwise.
605 @brief Gets the core mode to be applied to the model.
607 This reflects the core mode that will be used when the model is created.
609 @return The `CoreMode` to be applied to the model.
614 self, clusters: List[Cluster] = [Cluster.Cluster0, Cluster.Cluster1]
617 @brief Sets the model to use multi-core mode for batch inference.
619 In multi-core mode, on Aries NPU, the four local cores within a cluster work
620 together to process batch inference tasks efficiently. This mode is optimized for
623 @param[in] clusters A list of clusters to be used for multi-core batch inference.
625 @return True if the mode was successfully set, False otherwise.
631 @brief Gets the core allocation policy to be applied to the model.
633 This reflects the core allocation policy that will be used when the model is
636 @return The `CoreAllocationPolicy` to be applied to the model.
642 @brief Gets the number of cores to be allocated for the model.
644 This represents the number of cores that will be allocated for inference
645 when the model is launched to the NPU.
647 @return The number of cores to be allocated for the model.
653 @brief Forces the use of a specific NPU bundle.
655 This function forces the selection of a specific NPU bundle. If a non-negative
656 index is provided, the corresponding NPU bundle is selected and runs without CPU
657 offloading. If -1 is provided, all NPU bundles are used with CPU offloading
660 @param[in] npu_bundle_index The index of the NPU bundle to force. A non-negative
661 integer selects a specific NPU bundle (runs without CPU
662 offloading), or -1 to enable all NPU bundles with CPU
665 @return True if the index is valid and the NPU bundle is successfully set,
666 False if the index is invalid (less than -1).
672 @brief Retrieves the index of the forced NPU bundle.
674 This function returns the index of the NPU bundle that has been forced using the
675 `force_single_npu_bundle` function. If no NPU bundle is forced, the returned value
678 @return The index of the forced NPU bundle, or -1 if no bundle is forced.
684 @brief Enables or disables the asynchronous pipeline required for asynchronous
687 Call this function with `enable` set to `True` if you intend to use
688 `Model.infer_async()`, as the asynchronous pipeline is necessary for their operation.
690 If you are only using synchronous inference, such as `Model.infer()` or
691 `Model.infer_to_float()`, it is recommended to keep the asynchronous pipeline disabled
692 to avoid unnecessary overhead.
694 @param[in] enable Set to `True` to enable the asynchronous pipeline; set to `False`
701 @brief Returns whether the asynchronous pipeline is enabled in this configuration.
703 @return `True` if the asynchronous pipeline is enabled; `False` otherwise.
709 @brief Sets activation buffer slots for multi-activation supported model.
711 all this function if you want to set the number of activation buffer slots manually.
713 If you do not call this function, the default number of activation buffer slots
714 is set differently depending on the CoreMode.
716 - `CoreMode.Single` : 2 * (the number of target core ids)
717 - `CoreMode.Multi` : 2 * (the number of target clusters)
718 - `CoreMode.Global4` : 2 * (the number of target clusters)
719 - `CoreMode.Global8` : 2
721 @note This function has no effect on MXQ file in version earlier than MXQv7.
723 @note Currently, LLM model's activation slot is fixed to 1 and ignoring `count`.
725 @param[in] count Multi activation counts. Must be >= 1.
731 @brief Returns activation buffer slot count.
733 @note This function has no meaning on MXQ file in version earlier than MXQv7.
735 @return Activation buffer slot count.
740 def early_latencies(self) -> List[int]:
744 def finish_latencies(self) -> List[int]:
747 @early_latencies.setter
748 def early_latencies(self, latencies: List[int]):
749 """@deprecated This setting has no effect."""
752 @finish_latencies.setter
753 def finish_latencies(self, latencies: List[int]):
754 """@deprecated This setting has no effect."""
759 @brief Returns the list of NPU CoreIds to be used for model inference.
761 This function returns a list of NPU CoreIds that the model will use for
762 inference. When `set_single_core_mode(num_cores)` is called and the
763 core allocation policy is set to CoreAllocationPolicy.Auto, it will return an
766 @return A list of NPU CoreIds.
781 return "{}({})".format(
782 self.__class__.__name__,
783 ", ".join(
"{}={}".format(k, v)
for k, v
in d.items()),
788 """@brief LogLevel"""
790 Debug = _cQbRuntime.LogLevel.Debug
791 Info = _cQbRuntime.LogLevel.Info
792 Warn = _cQbRuntime.LogLevel.Warn
793 Err = _cQbRuntime.LogLevel.Err
794 Fatal = _cQbRuntime.LogLevel.Fatal
795 Off = _cQbRuntime.LogLevel.Off
798def set_log_level(level: LogLevel):
799 _cQbRuntime.set_log_level(level.value)
803 """@brief CacheType"""
805 Default = _cQbRuntime.CacheType.Default
806 Batch = _cQbRuntime.CacheType.Batch
807 Error = _cQbRuntime.CacheType.Error
811 """@brief Struct representing KV-cache information."""
815 cache_type: CacheType = CacheType.Error,
817 layer_hash: str =
"",
819 num_batches: int = 0,
829 def from_cpp(cls, _cache_info: _cQbRuntime.CacheInfo):
833 _cache_info.layer_hash,
835 _cache_info.num_batches,
839 def cache_type(self) -> CacheType:
843 def name(self) -> str:
847 def layer_hash(self) -> str:
851 def size(self) -> int:
855 def num_batches(self) -> int:
859 def cache_type(self, value: CacheType):
863 def name(self, value: str):
867 def layer_hash(self, value: str):
871 def size(self, value: int):
875 def num_batches(self, value: int):
880 """@brief DataType"""
882 Float32 = _cQbRuntime.DataType.Float32
883 Float16 = _cQbRuntime.DataType.Float16
884 Int8 = _cQbRuntime.DataType.Int8
885 Uint8 = _cQbRuntime.DataType.Uint8
886 Error = _cQbRuntime.DataType.Error
890 """@brief Struct containing BatchLLM parameters."""
894 sequence_length: int = 0,
909 return "{}({})".format(
910 self.__class__.__name__,
911 ", ".join(
"{}={}".format(k, v)
for k, v
in d.items()),
915 def sequence_length(self) -> int:
919 def cache_size(self) -> int:
923 def cache_id(self) -> int:
926 @sequence_length.setter
927 def sequence_length(self, value: int):
931 def cache_size(self, value: int):
935 def cache_id(self, value: int):
941 @brief Starts event tracing and prepares to save the trace log to a specified file.
943 The trace log is recorded in "Chrome Tracing JSON format," which can be
944 viewed at https://ui.perfetto.dev/.
946 The trace log is not written immediately; it is saved only when
947 stop_tracing_events() is called.
949 @param[in] path The file path where the trace log should be stored.
950 @return True if tracing starts successfully, False otherwise.
952 return _cQbRuntime.start_tracing_events(path)
957 @brief Stops event tracing and writes the recorded trace log.
959 This function finalizes tracing and saves the collected trace data
960 to the file specified when start_tracing_events() was called.
962 _cQbRuntime.stop_tracing_events()
967 @brief Generates a structured summary of the specified MXQ model.
969 Returns an overview of the model contained in the MXQ file, including:
970 - Target NPU hardware
971 - Supported core modes and their associated cores
972 - The total number of model variants
974 - Input and output tensor shapes
975 - A list of layers with their types, output shapes, and input layer indices
977 The summary is returned as a human-readable string in a table and is useful for
978 inspecting model compatibility, structure, and input/output shapes.
980 @param[in] mxq_path Path to the MXQ model file.
981 @return A formatted string containing the model summary.
983 return _cQbRuntime.get_model_summary(mxq_path)
988 @brief Get the number of available NPU devices.
990 @return The number of available NPU devices.
992 return _cQbRuntime.get_available_device_numbers()
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.
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.
bool set_single_core_mode(self, Optional[int] num_cores=None, Optional[List[CoreId]] core_ids=None)
Sets the model to use single-core mode for inference with a specified number of local cores.
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[int] get_available_device_numbers()
Get the number of available NPU devices.
str get_model_summary(str mxq_path)
Generates a structured summary of the specified MXQ model.
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.