API Reference

API Reference#

Mobilint SDK qb Compiler: API Reference
Mobilint SDK qb Compiler v1.0
MCS002-EN
API Reference

Mobilint qb Compiler API provides functions for compiling models from various framework(onnx, pytorch, transformers, etc.) to MXQ format. More...

Classes

class  qbcompiler.frontend.Model_Dict
 Wrapper around the Mobilint compiler to support compilation and inference workflows. More...
class  qbcompiler.calibration.preprocess.GetNpy
 Load NumPy data from an in-memory array or a .npy file. More...
class  qbcompiler.calibration.preprocess.NpyNormalize
class  qbcompiler.calibration.preprocess.NpyPad
 Pad NumPy arrays to a desired shape. More...
class  qbcompiler.calibration.preprocess.GetImage
 Retrieve an image tensor from a file path or NumPy array using OpenCV. More...
class  qbcompiler.calibration.preprocess.Pad
 Pad images to a target shape or to meet a size divisor. More...
class  qbcompiler.calibration.preprocess.Normalize
 Apply mean/std normalization to images. More...
class  qbcompiler.calibration.preprocess.ResizeTorch
class  qbcompiler.calibration.preprocess.Resize
 Resize images with optional aspect-ratio preservation. More...
class  qbcompiler.calibration.preprocess.CenterCrop
 Perform a centered crop on the image. More...
class  qbcompiler.calibration.preprocess.SetOrder
class  qbcompiler.calibration.preprocess.preproc_builder
 Build a calibration preprocessing pipeline from a YAML or dict configuration. More...
class  GetText
 Extract text strings from raw inputs. More...
class  TokenizeToEmbedding
 Convert tokenized text into embeddings using a Hugging Face model. More...
class  YoloPre
 Apply YOLO-style resize, padding, and normalization to images. More...

Functions

 qbcompiler.frontend.mxq_compile (model, str calib_data_path="", int save_subgraph_type=0, output_subgraph_path="", str model_nickname=None, str save_path=None, backend="onnx", device="cpu", feed_dict=None, dynamic_axes=None, in_dformats=None, save_sample=False, inference_scheme="single", yolo_decode_include=False, use_random_calib=False, cpu_offload=False, optimize_option=1, sample_dtype="float", buffer_mode=1, input_shape_dict=dict(), use_custom_mask=False, exclude_first_subgraph=False, Optional[CompileConfig] compile_config=None, Optional[ResourceManagementConfig] resource_management_config=None, Optional[QuantizationConfig] quantization_config=None, Optional[AdvancedQuantizationConfig] advanced_quantization_config=None, Optional[LlmConfig] llm_config=None, Optional[InputProcessConfig] input_process_config=None, **kwargs)
 Compile a model into a Mobilint eXeCUtable (MXQ) package for execution on Mobilint NPUs.
 qbcompiler.frontend.mblt_compile (str|Any model, str mblt_save_path, backend="onnx", device="cpu", feed_dict=None, dynamic_axes=None, in_dformats=None, yolo_decode_include=False, cpu_offload=False, use_custom_mask=False, exclude_first_subgraph=False, **kwargs)
 Export a model to the Mobilint .mblt format without producing an MXQ package.
 qbcompiler.frontend.run_mblt_model (str path_to_mblt, bool save_all_outputs=True, Optional[str] inference_output_path=None, Optional[int] target_subgraph=None)
 qbcompiler.calibration.make_calib_data.get_yaml (str yaml_path)
 qbcompiler.calibration.make_calib_data.make_calib_man (pre_ftn, str data_dir, str save_dir, str save_name, str anno_json=None, str file_format="%012d.jpg", int max_size=-1, bool remove_npy=False, int seed=2023, bool save_calib_msg=False, str msg_path=None)
 From images and a user-provided preprocessing function, generate calibration NumPy files and a manifest.
str qbcompiler.calibration.make_calib_data.make_calib (Union[str, dict] args_pre, str data_dir, str save_dir, str save_name=None, str anno_json=None, str file_format="%012d.jpg", int max_size=-1, bool remove_npy=False, int seed=2023, bool save_calib_msg=False, str msg_path=None)
 Create calibration NumPy files and a manifest using a YAML or dict preprocessing configuration.
List[str] qbcompiler.calibration.make_calib_data.make_calib_llm (Union[str, dict] args_pre, str dataset_name, Union[List[str], str] subset_list, str text_field, str split, str save_dir, int max_calib=512, Optional[str] save_prefix=None)
 Generate calibration embeddings for LLM models using Hugging Face datasets.
 qbcompiler.calibration.preprocess.preprocess_fnc (fnc, Datatype="Image")

Variables

dict qbcompiler.calibration.preprocess.DTYPE_GETDATA_MAP = {"Image": "GetImage", "Npy": "GetNpy", "LLM": "GetText"}

Detailed Description

Mobilint qb Compiler API provides functions for compiling models from various framework(onnx, pytorch, transformers, etc.) to MXQ format.

Function Documentation

◆ mxq_compile()

qbcompiler.frontend.mxq_compile ( model,
str calib_data_path = "",
int save_subgraph_type = 0,
output_subgraph_path = "",
str model_nickname = None,
str save_path = None,
backend = "onnx",
device = "cpu",
feed_dict = None,
dynamic_axes = None,
in_dformats = None,
save_sample = False,
inference_scheme = "single",
yolo_decode_include = False,
use_random_calib = False,
cpu_offload = False,
optimize_option = 1,
sample_dtype = "float",
buffer_mode = 1,
input_shape_dict = dict(),
use_custom_mask = False,
exclude_first_subgraph = False,
Optional[CompileConfig] compile_config = None,
Optional[ResourceManagementConfig] resource_management_config = None,
Optional[QuantizationConfig] quantization_config = None,
Optional[AdvancedQuantizationConfig] advanced_quantization_config = None,
Optional[LlmConfig] llm_config = None,
Optional[InputProcessConfig] input_process_config = None,
** kwargs )

Compile a model into a Mobilint eXeCUtable (MXQ) package for execution on Mobilint NPUs.

Parameters
modelstring or model instance. Model path. When using backend="onnx", this should be the path to an ONNX model file. When backend is "torchscript", provide a TorchScript module; when "torch", provide a standard PyTorch model. For backend="tf", pass the directory that contains the TensorFlow SavedModel graph and assets. For backend="tflite", pass the TF Lite model path.
calib_data_pathstring. Path to the calibration dataset. Accepts either a text/json file that lists NumPy files or a directory that contains the pre-processed NumPy files.
save_subgraph_typeint. Controls optional MBLT subgraph exports: 0 disables exports; 1 saves only the graph structure; 2 saves graph structure plus weights; 3 saves the graph structure split into multiple subgraphs; 4 saves both structure and weights split into multiple subgraphs.
output_subgraph_pathstring. Destination path for the exported .mblt file when save_subgraph_type is 1, 2, 3, or 4. The resulting file can be used for visualization.
model_nicknamestring. Friendly name stored in qbcompiler. Defaults to the model basename (for example, the file "/workspace/onnx/resnet50.onnx" becomes "resnet50"). Falls back to "temporary" when it cannot be inferred.
save_pathstring. Output MXQ filename. Defaults to "{model_nickname}.mxq" when omitted.
backendstring. Framework used to generate the Mobilint IR. Must be one of "onnx", "tf", "tflite", "torchscript", or "torch". Defaults to "onnx".
devicestring. Compilation and inference device: "cpu" or "gpu". Defaults to "cpu".
feed_dictdict. Example input tensors for shape inference and inference validation.
dynamic_axesdict. Marks model axes as dynamic. Keys are input names and values map dimension indices to aliases (for example {"input": {2: "seq_len"}}).
in_dformatsdict. Describes input tensor data formats.
save_samplebool. Stores input/output tensors in ./sampleInOut when True to aid debugging. Defaults to False.
inference_schemestring. NPU inference scheme. One of "single", "multi", "global", "global4", or "global8".
yolo_decode_includebool. Determines whether YOLO decode runs on NPU.
use_random_calibbool. Generates random calibration data to validate model compilability. Defaults to False.
cpu_offloadbool. Enables CPU offloading during NPU inference. Defaults to False.
optimize_optionint. Compiler optimization strategy selector.
sample_dtypestring. Data type for saved sample inference outputs: "float" or "int8".
buffer_modeint. Buffer serialization mode: 0 uses a naïve buffer, 1 uses an mmap-backed buffer. Defaults to 1.
input_shape_dict:multi-shapecompilation specification for STT/TTS models only (e.g., Conformer-CTC, MeloTTS). The dynamic axis is defined with respect to each input tensor’s shape. During compilation, the same axis is varied across all model inputs using the provided values. Currently, only a single entry key ("multi_shape0") is supported. Example: {"multi_shape0": {"axis": 2, "values": [100, 200, 300]}}
use_custom_maskbool. For non-LLM models that include a mask, use a custom mask provided as a separate input instead of the causal mask. For LLMs that incorporate RoPE, setting LLMConfig.dynamic_rope to True not only enables the use of dynamic RoPE provided via an additional input, but also activates the custom mask.
exclude_first_subgraphbool. Applies only when CPU offloading is enabled: exclude the first subgraph from the final graph if it is unsupported.
compile_configstring. Path to JSON configuration file containing all quantization-related settings (resourceManagement, quantization, advancedQuantization, llmConfig). If provided, this takes precedence over individual sub-config parameters.
resource_management_configResourceManagementConfig. Resource management configuration object.
quantization_configQuantizationConfig. Quantization configuration object.
advanced_quantization_configAdvancedQuantizationConfig. Advanced quantization configuration object.
llm_configLlmConfig. LLM configuration object.
input_process_configInputProcessConfig. Unified input processing configuration containing uint8 input handling, image channels, and preprocessing pipeline settings.
kwargsdict. Additional compiler arguments propagated to the backend implementation. Moreover, If you want to override only a subset of configuration values, you can pass them to mxq_compile as keyword arguments (kwargs), and they will be applied. Note that AdvancedQuantizationConfig and its sub-configurations are not updated automatically from kwargs. In contrast, ResourceManagementConfig, QuantizationConfig, and LlmConfig support automatic updates via each configuration class’s from_kwargs method. See Example 3 below for a usage example.
Returns
None.
Using configuration
There are two ways to configure quantization settings:
  1. Load all settings from a JSON config file:
    from qbcompiler import mxq_compile
    mxq_compile(
    model="path/to/model.onnx",
    calib_data_path="path/to/calib",
    compile_config="path/to/config.json",
    device="gpu",
    )
  2. Pass individual sub-config objects:
    from qbcompiler import mxq_compile
    from qbcompiler.configs import (
    ResourceManagementConfig,
    QuantizationConfig,
    AdvancedQuantizationConfig,
    LlmConfig,
    )
    resource_mgmt = ResourceManagementConfig(weight_dtype="float32")
    quant_cfg = QuantizationConfig(...)
    adv_quant_cfg = AdvancedQuantizationConfig(...)
    llm_cfg = LlmConfig(...)
    mxq_compile(
    model="path/to/model.onnx",
    calib_data_path="path/to/calib",
    resource_management_config=resource_mgmt,
    quantization_config=quant_cfg,
    advanced_quantization_config=adv_quant_cfg,
    llm_config=llm_cfg,
    device="gpu",
    )
  3. Automatically applied partial configuration overrides:
    from qbcompiler import mxq_compile
    mxq_compile(
    model="path/to/model.onnx",
    calib_data_path="path/to/calib",
    quantization_method=1, # per channel quantization
    quantization_mode=1, # max percentile quantization
    percentile=0.999, # percentile value for max percentile quantization
    quantization_output=0, # per layer quantization for the output layer
    device="gpu",
    )
    Please refer to the mxq_compile function and the quantization configuration section for the meaning of the quantization-related numeric values.
Compiling models with custom inputs (ONNX/Torch/TensorFlow)
Provide NumPy inputs whenever the model omits shape information so that qbcompiler can infer unknown dimensions and data formats.
from qbcompiler import mxq_compile
import numpy as np
example_input = {
"input_node_name_1": np.random.randn(1, 3, 224, 224).astype(np.float32),
"input_node_name_2": np.random.randn(1, 8, 224, 224).astype(np.float32),
"input_node_name_3": np.random.randn(1, 4, 56, 56).astype(np.float32),
}
in_dformats = {
"input_node_name_1": "NCHW",
"input_node_name_2": "NCHW",
"input_node_name_3": "NCHW",
}
onnx_model_path = "path/to/your/model.onnx"
mxq_compile(
model=onnx_model_path,
feed_dict=example_input,
in_dformats=in_dformats,
backend="onnx",
compile_config="path/to/config.json",
)

Definition at line 128 of file frontend.py.

◆ mblt_compile()

qbcompiler.frontend.mblt_compile ( str | Any model,
str mblt_save_path,
backend = "onnx",
device = "cpu",
feed_dict = None,
dynamic_axes = None,
in_dformats = None,
yolo_decode_include = False,
cpu_offload = False,
use_custom_mask = False,
exclude_first_subgraph = False,
** kwargs )

Export a model to the Mobilint .mblt format without producing an MXQ package.

Parameters
modelstring or model instance. Source model or path to compile.
mblt_save_pathstring. Output path for the .mblt artifact.
backendstring. Framework identifier ("onnx", "tf", "tflite", "torchscript", or "torch"). Defaults to "onnx".
devicestring. Compilation device ("cpu" or "gpu"). Defaults to "cpu".
feed_dictdict. Example inputs used for shape inference.
dynamic_axesdict. Declares dynamic axes per input name.
in_dformatsdict. Input dataformat metadata.
yolo_decode_includebool. Runs YOLO decode on NPU when True.
cpu_offloadbool. Enables CPU offloading for unsupported groups.
use_custom_maskbool. For non-LLM models that include a mask, use a custom mask provided as a separate input instead of the causal mask. For LLMs that incorporate RoPE, setting LLMConfig.dynamic_rope to True not only enables the use of dynamic RoPE provided via an additional input, but also activates the custom mask.
exclude_first_subgraphbool. Applies only when CPU offloading is enabled: exclude the first subgraph from the final graph if it is unsupported.
kwargsdict. Additional arguments forwarded to the compiler.
Returns
None.

Definition at line 424 of file frontend.py.

◆ run_mblt_model()

qbcompiler.frontend.run_mblt_model ( str path_to_mblt,
bool save_all_outputs = True,
Optional[str] inference_output_path = None,
Optional[int] target_subgraph = None )

Definition at line 483 of file frontend.py.

◆ get_yaml()

qbcompiler.calibration.make_calib_data.get_yaml ( str yaml_path)

Definition at line 29 of file make_calib_data.py.

◆ make_calib_man()

qbcompiler.calibration.make_calib_data.make_calib_man ( pre_ftn,
str data_dir,
str save_dir,
str save_name,
str anno_json = None,
str file_format = "%012d.jpg",
int max_size = -1,
bool remove_npy = False,
int seed = 2023,
bool save_calib_msg = False,
str msg_path = None )

From images and a user-provided preprocessing function, generate calibration NumPy files and a manifest.

Parameters
pre_ftnCallable. Pre-processing function that accepts an image path and returns a NumPy array.
data_dirstring. Directory containing the raw calibration images.
save_dirstring. Directory in which to store the generated NumPy files and metadata text file.
save_namestring. Basename for the saved assets. NumPy files are written to {save_dir}/{save_name}_npy and the manifest to {save_dir}/{save_name}.txt. Defaults to the basename of data_dir when omitted.
anno_jsonstring. Optional COCO-style annotation file. When provided, samples are randomly selected while maintaining class balance.
file_formatstring. Filename format that uses image_idx (for example "%012d.jpg").
max_sizeint. Maximum number of calibration samples. A value of -1 disables the limit.
remove_npybool. Remove existing NumPy outputs before generating new data.
seedint. Random seed applied to sampling and class-balanced selection. Defaults to 2023.
save_calib_msgbool. Persist the calibration metadata as an MSGpack file in addition to the manifest.
msg_pathstring. Explicit MSGpack output path. When omitted, the path is auto-generated by dataset name and sample count.
Returns
string. Path to the generated text file that lists the preprocessed NumPy samples.
Note
Calibration samples are written as float32 NumPy arrays derived from the pre_ftn output. When max_size is positive and the dataset is larger, a random subset is used. COCO annotations override this sampling to balance categories.

Definition at line 40 of file make_calib_data.py.

◆ make_calib()

str qbcompiler.calibration.make_calib_data.make_calib ( Union[str, dict] args_pre,
str data_dir,
str save_dir,
str save_name = None,
str anno_json = None,
str file_format = "%012d.jpg",
int max_size = -1,
bool remove_npy = False,
int seed = 2023,
bool save_calib_msg = False,
str msg_path = None )

Create calibration NumPy files and a manifest using a YAML or dict preprocessing configuration.

Parameters
args_prestring or dict. Path to a YAML file or an in-memory dictionary describing the preprocessing pipeline. See the preproc_builder class for all supported operators and parameters.
data_dirstring. Directory of calibration images.
save_dirstring. Directory where the generated NumPy files and manifest text file are stored.
save_namestring. Optional basename for outputs. Defaults to the basename of data_dir.
anno_jsonstring. Optional COCO-format annotation file used to sample images with class balance.
file_formatstring. Filename template built from image_idx (defaults to "%012d.jpg").
max_sizeint. Maximum number of calibration samples to generate; -1 keeps all available items.
remove_npybool. Remove existing NumPy outputs before running preprocessing.
seedint. Random seed used for sampling. Defaults to 2023.
save_calib_msgbool. Save calibration metadata as MSGpack alongside NumPy and text outputs.
msg_pathstring. Explicit MSGpack output path. Auto-generated from dataset name and sample count when omitted.
Returns
string. Path to the manifest text file that lists the generated NumPy samples.
Note
The preprocessing pipeline is constructed through preproc_builder and executed via make_calib_man. Use the YAML schema to combine primitives such as GetImage, Resize, Normalize, Pad, CenterCrop, and SetOrder in a Pre-Order list.

Definition at line 139 of file make_calib_data.py.

◆ make_calib_llm()

List[str] qbcompiler.calibration.make_calib_data.make_calib_llm ( Union[str, dict] args_pre,
str dataset_name,
Union[List[str], str] subset_list,
str text_field,
str split,
str save_dir,
int max_calib = 512,
Optional[str] save_prefix = None )

Generate calibration embeddings for LLM models using Hugging Face datasets.

Args: args_pre: YAML path or preprocessing configuration dictionary. Must set Datatype to "LLM". dataset_name: Name of the Hugging Face dataset to load. subset_list: List of dataset subsets (e.g. language splits) to iterate. split: HF dataset split to use. text_field: Key containing text in dataset entries. save_dir: Root directory where calibration samples are stored. max_calib: Maximum number of calibration samples per subset. save_prefix: Override prefix used in output directory naming. If None, derives from tokenizer directory name when available.

Returns: List of paths to generated calibration txt files, one per subset.

Definition at line 200 of file make_calib_data.py.

◆ preprocess_fnc()

qbcompiler.calibration.preprocess.preprocess_fnc ( fnc,
Datatype = "Image" )

Definition at line 28 of file preprocess.py.

Variable Documentation

◆ DTYPE_GETDATA_MAP

dict qbcompiler.calibration.preprocess.DTYPE_GETDATA_MAP = {"Image": "GetImage", "Npy": "GetNpy", "LLM": "GetText"}

Definition at line 24 of file preprocess.py.