6from pathlib
import Path
11from qubee.compiler.compiler
import Compiler
12from qubee.compiler.compiler
import _quantization_task
14from qubee.version
import __version__
25 @brief Wrapper around the Mobilint compiler to support compilation and inference workflows.
27 @details Capabilities include:
28 - Compilation of models into MXQ artifacts runnable on Mobilint NPUs.
29 - Inference using the full-precision high-level compiled model on CPU or GPU.
30 - Inference with the quantized model on CPU or GPU.
41 yolo_decode_include=False,
45 @brief Initialize the Mobilint compiler wrapper.
47 @param model string or model instance. Model path or in-memory model to compile.
48 @param backend string. Framework identifier for the model (for example "onnx"). Defaults to "onnx".
49 @param device string. Target device for inference ("cpu" or "gpu"). Defaults to "cpu".
50 @param feed_dict dict. Example inputs for shape resolution.
51 @param dynamic_axes dict. Marks model axes as dynamic.
52 @param in_dformats dict. Describes input data formats.
53 @param yolo_decode_include bool. Runs YOLO decode on NPU when @c True.
54 @param kwargs dict. Additional compiler arguments.
61 in_dformats=in_dformats,
62 dynamic_axes=dynamic_axes,
63 yolo_decode_include=yolo_decode_include,
69 calib_data_path: str =
None,
70 save_path: str =
None,
71 save_subgraph_type: int = 0,
72 output_subgraph_path=
"",
73 model_nickname: str =
None,
75 use_random_calib=
False,
76 inference_scheme=
"single",
78 singlecore_compile=
False,
80 sample_dtype: str =
"float",
83 quant_config=QuantConfig.default_config(),
87 @brief Compile the wrapped model into an MXQ artifact.
89 @param calib_data_path string. Calibration dataset directory or meta file (.txt/.json) listing NumPy samples.
90 @param save_path string. Output MXQ filename.
91 @param save_subgraph_type int. Controls optional MBLT exports: 0 disables; 1 saves graph structure; 2 saves
92 structure and weights; 3 splits structure into multiple subgraphs; 4 splits structure and weights.
93 @param output_subgraph_path string. Destination for exported .mblt when @p save_subgraph_type is 1–4.
94 @param model_nickname string. Friendly name stored in qubee for faster recompile.
95 @param save_sample bool. Persists inputs/outputs for debugging in ./sampleInOut.
96 @param use_random_calib bool. Uses randomly generated calibration samples when @c True.
97 @param inference_scheme string. NPU inference configuration ("single", "multi", "global", etc.).
98 @param cpu_offload bool. Enables CPU offload for unsupported groups.
99 @param singlecore_compile bool. Forces single-core compilation for large DRAM usage.
100 @param optimize_option int. Compiler optimization selector.
101 @param sample_dtype string. Data type used for saved sample outputs.
102 @param preprocess_dict dict. Additional preprocessing metadata.
103 @param buffer_mode int. Buffer serialization mode (0 naive, 1 mmap).
104 @param quant_config QuantConfig. Quantization configuration object.
105 @param kwargs dict. Additional arguments forwarded to the compiler.
108 calib_data_path=calib_data_path,
110 save_subgraph_type=save_subgraph_type,
111 output_subgraph_path=output_subgraph_path,
112 model_nickname=model_nickname,
113 save_sample=save_sample,
114 inference_scheme=inference_scheme,
115 use_random_calib=use_random_calib,
116 cpu_offload=cpu_offload,
117 singlecore_compile=singlecore_compile,
118 optimize_option=optimize_option,
119 sample_dtype=sample_dtype,
120 preprocess_dict=preprocess_dict,
121 buffer_mode=buffer_mode,
122 quant_config=quant_config,
129 calib_data_path: str =
"",
130 save_subgraph_type: int = 0,
131 output_subgraph_path=
"",
132 model_nickname: str =
None,
133 save_path: str =
None,
139 quantize_method=
"maxpercentile",
140 quantize_percentile=0.9999,
144 act_scale_min=0.0005,
148 inference_scheme=
"single",
149 yolo_decode_include=
False,
150 use_random_calib=
False,
152 singlecore_compile=
False,
154 quant_output=
"layer",
155 sample_dtype=
"float",
156 preprocess_dict=
None,
158 weight_dtype=
"float32",
159 use_gpu_only_for_calibration=
False,
160 input_shape_dict=dict(),
161 adaq_config=AdaQuantConfig.default_config(),
162 optq_config=OptqConfig.default_config(),
163 mod_config=ModConfig.default_config(),
164 layer_config=LayerConfig.default_config(),
165 llm_config=LlmConfig.default_config(),
166 quantbit_config=QuantBitConfig.default_config(),
170 @brief Compile a model into a Mobilint eXeCUtable (MXQ) package for execution on Mobilint NPUs.
172 @param model string or model instance. Model path. When using @c backend="onnx", this should be the path to an ONNX
173 model file. When @c backend is "torchscript", provide a TorchScript module; when "torch", provide a standard
174 PyTorch model. For @c backend="tf", pass the directory that contains the TensorFlow SavedModel graph and assets. For
175 @c backend="tflite", pass the TF Lite model path.
176 @param calib_data_path string. Path to the calibration dataset. Accepts either a text/json file that lists NumPy
177 files or a directory that contains the pre-processed NumPy files.
178 @param save_subgraph_type int. Controls optional MBLT subgraph exports: 0 disables exports; 1 saves only the graph
179 structure; 2 saves graph structure plus weights; 3 saves the graph structure split into multiple subgraphs; 4 saves
180 both structure and weights split into multiple subgraphs.
181 @param output_subgraph_path string. Destination path for the exported .mblt file when @p save_subgraph_type is 1, 2,
182 3, or 4. The resulting file can be used for visualization.
183 @param model_nickname string. Friendly name stored in qubee. Defaults to the model basename (for example, the file
184 "/workspace/onnx/resnet50.onnx" becomes "resnet50"). Falls back to "temporary" when it cannot be inferred.
185 @param save_path string. Output MXQ filename. Defaults to "{model_nickname}.mxq" when omitted.
186 @param backend string. Framework used to generate the Mobilint IR. Must be one of "onnx", "tf", "tflite",
187 "torchscript", or "torch". Defaults to "onnx".
188 @param device string. Compilation and inference device: "cpu" or "gpu". Defaults to "cpu".
189 @param feed_dict dict. Example input tensors for shape inference and inference validation.
190 @param dynamic_axes dict. Marks model axes as dynamic. Keys are input names and values map dimension indices to
191 aliases (for example {"input": {2: "seq_len"}}).
192 @param in_dformats dict. Describes input tensor data formats.
193 @param quantize_method string. Quantization method. Supported values are "Max", "Percentile", "MaxPercentile",
194 "FastPercentile", and "KL". Defaults to "Percentile".
195 @param quantize_percentile float. Percentile value for percentile-based quantization; valid range is 0 to 1. Example
196 values: 0.999 or 0.9999. Defaults to 0.9999.
197 @param topk_ratio float. Applicable to "MaxPercentile" quantization; controls how much data is used for calibration.
198 Recommended values are 0.01 or lower; defaults to 0.01.
199 @param smooth_factor float. Gaussian kernel smoothing factor required for KL-divergence estimation. Defaults to 1.6.
200 @param min_clip_ratio float. Ratio applied to minimum clipping of output scales. Defaults to -1 (disabled).
201 @param act_scale_min float. Minimum activation scale used during quantization. Defaults to 0.0005.
202 @param is_quant_ch bool. Enables multi-channel quantization when @c True; defaults to @c True.
203 @param is_asym_quant bool. Enables asymmetric quantization when @c True; defaults to @c False.
204 @param save_sample bool. Stores input/output tensors in ./sampleInOut when @c True to aid debugging. Defaults to
206 @param inference_scheme string. NPU inference scheme. One of "single", "multi", "global", "global4", or
208 @param yolo_decode_include bool. Determines whether YOLO decode runs on NPU.
209 @param use_random_calib bool. Generates random calibration data to validate model compilability. Defaults to @c
211 @param cpu_offload bool. Enables CPU offloading during NPU inference. Defaults to @c False.
212 @param singlecore_compile bool. Uses singlecore compilation to maximize DRAM usage. Defaults to @c False.
213 @param optimize_option int. Compiler optimization strategy selector.
214 @param quant_output string. Quantization applied to the output layer. Accepts "layer" (per-layer), "ch"
215 (per-channel; only when @p is_quant_ch is True), or "sigmoid" (use sigmoid-based scaling). Defaults to "layer".
216 @param sample_dtype string. Data type for saved sample inference outputs: "float" or "int8".
217 @param preprocess_dict int. Identifier for additional pre-processing metadata.
218 @param buffer_mode int. Buffer serialization mode: 0 uses a naïve buffer, 1 uses an mmap-backed buffer. Defaults to
220 @param weight_dtype string. Weight dtype for calibration. Defaults to "float32".
221 @param use_gpu_only_for_calibration bool. Restricts GPU usage to calibration passes. Defaults to @c False.
222 @param input_shape_dict dict. Optional HWC input shape dictionary used for multi-shape compilation (for example
223 {"input0": [[224, 224, 3], [256, 256, 3]]}).
224 @param adaq_config AdaQuantConfig. Configures the AdaQuant algorithm, including learning rates for weights, bias,
225 scales, batch size, and loop epochs. Defaults to disabled values.
226 @param optq_config OptqConfig. Configures OPTQ, such as activation-order sorting, block size, and percentile
228 @param mod_config ModConfig. Enables Mobilint Optimal Distillation algorithm overrides when provided.
229 @param layer_config LayerConfig. Supplies per-layer overrides for enabling MOD/OPTQ, activation bit precision, and
230 minimum activation scale values.
231 @param llm_config LLMConfig. Large-language-model compilation options such as maximum sequence length, cache length,
232 calibration sequence length, mask usage, starting DRAM offset, global-core utilization, batch size, and NPU core IDs.
233 @param quantbit_config QuantBitConfig. Controls bit precision for Transformer submodules and optional import/export
234 of per-layer precision configurations.
235 @param kwargs dict. Additional compiler arguments propagated to the backend implementation.
238 @par Tips for choosing quantization methods and selecting arguments
239 Increase the percentile value to widen the quantization interval. "Percentile" samples the calibration histogram and
240 typically starts between 0.9999 and 0.999999. "FastPercentile" relies on reduced, smoothed samples and favors values
241 between 0.99 and 0.99999. "MaxPercentile" operates on min/max stacks and commonly uses 0.9 to 0.9999. Channel-wise
242 quantization (@p is_quant_ch=True) mitigates per-channel activation variance at the cost of longer compile times.
243 Choose @p quant_output="ch" when output variance is channel-dependent; otherwise use "layer".
245 @par Compiling models with custom inputs (ONNX/Torch/TensorFlow)
246 Provide NumPy inputs whenever the model omits shape information so that qubee can infer unknown dimensions and data
250 from qubee import mxq_compile
254 "input_node_name_1": np.random.randn(1, 3, 224, 224).astype(np.float32),
255 "input_node_name_2": np.random.randn(1, 8, 224, 224).astype(np.float32),
256 "input_node_name_3": np.random.randn(1, 4, 56, 56).astype(np.float32),
260 "input_node_name_1": "NCHW",
261 "input_node_name_2": "NCHW",
262 "input_node_name_3": "NCHW",
265 onnx_model_path = "path/to/your/model.onnx"
267 model=onnx_model_path,
268 feed_dict=example_input,
269 in_dformats=in_dformats,
274 if model_nickname
and isinstance(model_nickname, str):
275 model_name = model_nickname
276 elif isinstance(model, str):
277 model_name = Path(model).stem
279 if save_path
is None:
280 raise ValueError(
"Please set the save_path with .mxq extension")
282 if save_path
is None:
283 save_path = f
"{model_name}.mxq"
285 quant_config = get_quant_config(
286 quantize_percentile=quantize_percentile,
287 topk_ratio=topk_ratio,
288 smooth_factor=smooth_factor,
289 quantize_method=quantize_method,
290 quant_output=quant_output,
291 is_quant_ch=is_quant_ch,
292 is_asym_quant=is_asym_quant,
293 weight_dtype=weight_dtype,
294 use_gpu_only_for_calibration=use_gpu_only_for_calibration,
295 input_shape_dict=input_shape_dict,
296 adaq_config=adaq_config,
297 optq_config=optq_config,
298 mod_config=mod_config,
299 layer_config=layer_config,
300 llm_config=llm_config,
301 quantbit_config=quantbit_config,
302 min_clip_ratio=min_clip_ratio,
303 act_scale_min=act_scale_min,
305 if isinstance(model, str)
and model.endswith(
".mblt")
and os.path.isfile(model):
306 compile_config = get_compile_config(
307 calib_data_path=calib_data_path,
308 use_random_calib=use_random_calib,
310 save_msgpack_name=
None,
311 model_nickname=model_name,
312 inference_scheme=inference_scheme,
313 save_sample=save_sample,
314 cpu_offload=cpu_offload,
315 singlecore_compile=singlecore_compile,
316 optimize_option=optimize_option,
317 sample_dtype=sample_dtype,
318 preprocess_dict=preprocess_dict,
320 quant_config=quant_config,
322 _quantization_task(model, device, compile_config=compile_config)
329 in_dformats=in_dformats,
330 dynamic_axes=dynamic_axes,
331 yolo_decode_include=yolo_decode_include,
335 model_nickname=model_name,
336 calib_data_path=calib_data_path,
338 save_subgraph_type=save_subgraph_type,
339 output_subgraph_path=output_subgraph_path,
340 save_sample=save_sample,
341 inference_scheme=inference_scheme,
342 use_random_calib=use_random_calib,
343 cpu_offload=cpu_offload,
344 singlecore_compile=singlecore_compile,
345 optimize_option=optimize_option,
346 sample_dtype=sample_dtype,
347 preprocess_dict=preprocess_dict,
348 buffer_mode=buffer_mode,
349 quant_config=quant_config,
351 torch.cuda.empty_cache()
363 yolo_decode_include=
False,
368 @brief Export a model to the Mobilint .mblt format without producing an MXQ package.
370 @param model string or model instance. Source model or path to compile.
371 @param mblt_save_path string. Output path for the .mblt artifact.
372 @param backend string. Framework identifier ("onnx", "tf", "tflite", "torchscript", or "torch"). Defaults to
374 @param device string. Compilation device ("cpu" or "gpu"). Defaults to "cpu".
375 @param feed_dict dict. Example inputs used for shape inference.
376 @param dynamic_axes dict. Declares dynamic axes per input name.
377 @param in_dformats dict. Input dataformat metadata.
378 @param yolo_decode_include bool. Runs YOLO decode on NPU when True.
379 @param cpu_offload bool. Enables CPU offloading for unsupported groups.
380 @param kwargs dict. Additional arguments forwarded to the compiler.
388 dynamic_axes=dynamic_axes,
389 in_dformats=in_dformats,
390 yolo_decode_include=yolo_decode_include,
394 model_dict.mblt_compile(
396 mblt_save_path=mblt_save_path,
398 cpu_offload=cpu_offload,
405 save_all_outputs: bool =
True,
406 inference_output_path: Optional[str] =
None,
407 target_subgraph: Optional[int] =
None,
409 from qubee.model_dict.common.model_dict
import ValueDict
410 from qubee.model_dict.inference.model
import ModelInference
411 from qubee.model_dict.serialize
import load_mblt_model
413 assert path_to_mblt.endswith(
".mblt")
414 if not save_all_outputs:
415 raise NotImplementedError(
416 f
"save_all_outputs={save_all_outputs} is not supported yet."
419 raise NotImplementedError(
420 f
"target_subgraph={target_subgraph} is not supported yet."
424 if not inference_output_path:
425 inference_output_path = str(pathlib.Path(path_to_mblt).with_suffix(
".infer"))
428 md, wd = load_mblt_model(path_to_mblt, load_weight=
True)
429 for sg
in md.subgraphs:
430 for iidx
in sg.inputs:
431 inact = sg.activations[iidx]
432 if inact.name
in set(md.inputs):
433 vd[inact.name] = numpy.random.random(tuple(map(int, inact.src_shape)))
435 model_inference = ModelInference(
439 save_all_outputs=save_all_outputs,
440 inference_all_outputs_write_path=inference_output_path,
443 model_inference.run_inference(use_value_dict_data_for_next_input=
False)
Wrapper around the Mobilint compiler to support compilation and inference workflows.
__init__(self, model, backend="onnx", device="cpu", feed_dict=None, dynamic_axes=None, in_dformats=None, yolo_decode_include=False, **kwargs)
Initialize the Mobilint compiler wrapper.
compile(self, str calib_data_path=None, str save_path=None, int save_subgraph_type=0, output_subgraph_path="", str model_nickname=None, save_sample=False, use_random_calib=False, inference_scheme="single", cpu_offload=False, singlecore_compile=False, optimize_option=0, str sample_dtype="float", preprocess_dict=None, buffer_mode=1, quant_config=QuantConfig.default_config(), **kwargs)
Compile the wrapped model into an MXQ artifact.
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, quantize_method="maxpercentile", quantize_percentile=0.9999, topk_ratio=0.01, smooth_factor=1.6, min_clip_ratio=-1, act_scale_min=0.0005, is_quant_ch=True, is_asym_quant=False, save_sample=False, inference_scheme="single", yolo_decode_include=False, use_random_calib=False, cpu_offload=False, singlecore_compile=False, optimize_option=0, quant_output="layer", sample_dtype="float", preprocess_dict=None, buffer_mode=1, weight_dtype="float32", use_gpu_only_for_calibration=False, input_shape_dict=dict(), adaq_config=AdaQuantConfig.default_config(), optq_config=OptqConfig.default_config(), mod_config=ModConfig.default_config(), layer_config=LayerConfig.default_config(), llm_config=LlmConfig.default_config(), quantbit_config=QuantBitConfig.default_config(), **kwargs)
Compile a model into a Mobilint eXeCUtable (MXQ) package for execution on Mobilint NPUs.
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, **kwargs)
Export a model to the Mobilint .mblt format without producing an MXQ package.