8from collections.abc
import Callable
9from typing
import Any, List, Optional, Union
12from qbcompiler.compiler.compiler
import Compiler
13from qbcompiler.compiler.compiler
import _quantization_task
14from qbcompiler.compiler.utils
import validate_target_device
15from qbcompiler.configs
import (
19 ResourceManagementConfig,
23 EquivalentTransformationConfig,
24 SearchWeightScaleConfig,
29from qbcompiler.config_resolver
import (
33 ResolvedQuantizeRequest_V2,
34 MbltCompileRequest_V2,
35 ResolvedMbltCompileRequest_V2,
36 UNSET
as CONFIG_MANAGER_UNSET,
37 apply_compile_config_bindings,
39from qbcompiler.logging
import get_logger
40from qbcompiler.progress
import emit_progress, progress_context
42logger = get_logger(__name__)
45"""Sentinel to distinguish 'not passed' from explicit defaults."""
48def _to_config_manager_unset_V2(value: object) -> object:
49 """Translate frontend-local ``_UNSET`` values to ConfigManager ``UNSET``."""
51 return CONFIG_MANAGER_UNSET
55def _resolve_deprecated_kwargs(
60 equivalent_transformation_config,
61 search_weight_scale_config,
67 """Extract and resolve deprecated parameters from kwargs into modern equivalents.
69 Mutates kwargs by popping consumed deprecated keys.
70 Returns a tuple of resolved sub-config values.
72 quantization_config = kwargs.pop(
"quantization_config",
None)
73 if quantization_config
is not None and calibration_config
is None:
75 "quantization_config is deprecated. Use calibration_config instead.",
79 calibration_config = quantization_config
81 advanced_quantization_config = kwargs.pop(
"advanced_quantization_config",
None)
82 if advanced_quantization_config
is not None:
84 "advanced_quantization_config is deprecated. Use individual configs "
85 "(optq_config, mod_config, equivalent_transformation_config, search_weight_scale_config) instead.",
89 if hasattr(advanced_quantization_config,
"optq")
and optq_config
is None:
90 optq_config = advanced_quantization_config.optq
91 if hasattr(advanced_quantization_config,
"mod")
and mod_config
is None:
92 mod_config = advanced_quantization_config.mod
94 hasattr(advanced_quantization_config,
"equivalent_transformation")
95 and equivalent_transformation_config
is None
97 equivalent_transformation_config = (
98 advanced_quantization_config.equivalent_transformation
101 hasattr(advanced_quantization_config,
"search_weight_scale")
102 and search_weight_scale_config
is None
104 search_weight_scale_config = (
105 advanced_quantization_config.search_weight_scale
108 input_process_config = kwargs.pop(
"input_process_config",
None)
109 if input_process_config
is not None:
111 "input_process_config is deprecated. Use uint8_input_config and preprocessing_config instead.",
115 if hasattr(input_process_config,
"uint8_input")
and uint8_input_config
is None:
116 uint8_input_config = input_process_config.uint8_input
118 hasattr(input_process_config,
"preprocessing")
119 and preprocessing_config
is None
121 preprocessing_config = input_process_config.preprocessing
123 save_sample = kwargs.pop(
"save_sample",
None)
124 sample_dtype = kwargs.pop(
"sample_dtype",
None)
126 save_sample
is not None or sample_dtype
is not None
127 )
and save_sample_config
is None:
129 "save_sample and sample_dtype are deprecated. Use save_sample_config instead.",
133 save_sample_kwargs = {}
134 if save_sample
is not None:
135 save_sample_kwargs[
"apply"] = save_sample
136 if sample_dtype
is not None:
137 save_sample_kwargs[
"dtype"] = sample_dtype
138 save_sample_config = SaveSampleConfig(**save_sample_kwargs)
144 equivalent_transformation_config,
145 search_weight_scale_config,
147 preprocessing_config,
152def _normalize_quantize_request_V2(
155 save_path: Union[str, List[str]] = _UNSET,
156 backend: str =
"onnx",
157 target_device: Optional[str] =
None,
161 yolo_decode_include: bool =
False,
162 exclude_first_subgraph: bool =
False,
163 save_subgraph_type: int = 0,
164 output_subgraph_path: str =
"",
165 calib_data_path: Union[str, List[str]] = _UNSET,
167 inference_scheme=_UNSET,
168 use_random_calib=_UNSET,
170 optimize_option=_UNSET,
172 input_shape_dict=_UNSET,
173 force_npu_input_reposition=_UNSET,
174 force_npu_output_reposition=_UNSET,
175 image_channels=_UNSET,
178 config_preset: Optional[str] =
None,
179 compile_config: Optional[CompileConfig | str] =
None,
180 resource_management_config: Optional[ResourceManagementConfig] =
None,
181 calibration_config: Optional[CalibrationConfig] =
None,
182 bit_config: Optional[BitConfig] =
None,
183 llm_config: Optional[LlmConfig] =
None,
184 optq_config: Optional[OptqConfig] =
None,
185 mod_config: Optional[ModConfig] =
None,
186 equivalent_transformation_config: Optional[EquivalentTransformationConfig] =
None,
187 search_weight_scale_config: Optional[SearchWeightScaleConfig] =
None,
188 save_sample_config: Optional[SaveSampleConfig] =
None,
189 uint8_input_config: Optional[Uint8InputConfig] =
None,
190 preprocessing_config: Optional[PreprocessingConfig] =
None,
192) -> QuantizeRequest_V2:
193 """Build a canonical V2 quantize request without executing side effects."""
194 return QuantizeRequest_V2(
196 save_path=_to_config_manager_unset_V2(save_path),
197 parser_options=ParserOptions_V2(
199 target_device=target_device,
201 dynamic_axes=dynamic_axes,
202 in_dformats=in_dformats,
203 yolo_decode_include=yolo_decode_include,
204 exclude_first_subgraph=exclude_first_subgraph,
205 extra_kwargs=dict(kwargs),
207 save_subgraph_type=save_subgraph_type,
208 output_subgraph_path=output_subgraph_path,
209 calib_data_path=_to_config_manager_unset_V2(calib_data_path),
210 device=_to_config_manager_unset_V2(device),
211 inference_scheme=_to_config_manager_unset_V2(inference_scheme),
212 use_random_calib=_to_config_manager_unset_V2(use_random_calib),
213 cpu_offload=_to_config_manager_unset_V2(cpu_offload),
214 optimize_option=_to_config_manager_unset_V2(optimize_option),
215 buffer_mode=_to_config_manager_unset_V2(buffer_mode),
216 input_shape_dict=_to_config_manager_unset_V2(input_shape_dict),
217 force_npu_input_reposition=_to_config_manager_unset_V2(
218 force_npu_input_reposition
220 force_npu_output_reposition=_to_config_manager_unset_V2(
221 force_npu_output_reposition
223 image_channels=_to_config_manager_unset_V2(image_channels),
224 split_blocks=_to_config_manager_unset_V2(split_blocks),
225 split_parts=_to_config_manager_unset_V2(split_parts),
226 config_preset=config_preset,
227 compile_config=compile_config,
228 resource_management_config=resource_management_config,
229 calibration_config=calibration_config,
230 bit_config=bit_config,
231 llm_config=llm_config,
232 optq_config=optq_config,
233 mod_config=mod_config,
234 equivalent_transformation_config=equivalent_transformation_config,
235 search_weight_scale_config=search_weight_scale_config,
236 save_sample_config=save_sample_config,
237 uint8_input_config=uint8_input_config,
238 preprocessing_config=preprocessing_config,
242def _normalize_mblt_compile_request_V2(
246 backend: str =
"onnx",
247 target_device: Optional[str] =
None,
248 device: object = _UNSET,
252 yolo_decode_include: bool =
False,
253 cpu_offload: object = _UNSET,
254 exclude_first_subgraph: bool =
False,
255 config_preset: Optional[str] =
None,
256 compile_config: Optional[CompileConfig | str] =
None,
257 compilation_mode: Optional[str] =
None,
259) -> MbltCompileRequest_V2:
260 """Build a canonical V2 compile-to-mblt request without side effects."""
261 return MbltCompileRequest_V2(
263 mblt_save_path=mblt_save_path,
264 parser_options=ParserOptions_V2(
266 target_device=target_device,
268 dynamic_axes=dynamic_axes,
269 in_dformats=in_dformats,
270 yolo_decode_include=yolo_decode_include,
271 exclude_first_subgraph=exclude_first_subgraph,
272 extra_kwargs=dict(kwargs),
274 device=_to_config_manager_unset_V2(device),
275 cpu_offload=_to_config_manager_unset_V2(cpu_offload),
276 config_preset=config_preset,
277 compile_config=compile_config,
278 compilation_mode=compilation_mode,
282def _is_existing_mblt_input_V2(model: object) -> bool:
283 """Return ``True`` when *model* is a readable existing ``.mblt`` file."""
284 return isinstance(model, str)
and model.endswith(
".mblt")
and os.path.isfile(model)
287def _validate_mblt_for_mxq_compile_V2(model: str, cpu_offload: object) ->
None:
288 """Validate an existing ``.mblt`` used as an ``mxq_compile`` input.
290 Only weight-bearing, properly partitioned ``.mblt`` files produced by
291 ``mblt_compile()`` can be quantized. This surfaces actionable guidance for
292 the common failure modes up front instead of a cryptic downstream error:
294 * No weights, or a single subgraph carrying unsupported ops -> error (a
295 preview export is not a runnable artifact; regenerate with
297 * ``cpu_offload=False`` with more than one subgraph -> error (the graph
298 cannot run without CPU offloading).
299 * ``cpu_offload=True`` with a single subgraph -> error (nothing to
300 offload; recompile with ``cpu_offload=False``).
303 def _read_mblt_graph_info(path: str):
304 """Return ``(has_weights, subgraphs)`` for the .mblt at *path*.
306 Both accepted flavors are supported: ``mblt.serialize.SerializeMeta``
307 detects the on-disk format from the trailing magic number, then the
308 legacy qbcompiler layout is read with qbcompiler's own serializer and
309 the mblt-graph layout with the mblt-graph serializer. Only the header
310 and graph structure are deserialized — weight data is never read.
312 from mblt.serialize
import SerializeMeta
as MbltSerializeMeta
314 if MbltSerializeMeta.read_header(path).is_legacy:
315 from qbcompiler.model_dict.serialize
import SerializeMeta
317 header = SerializeMeta.get_header(path)
318 subgraphs = SerializeMeta.get_model_dict(path, header=header).subgraphs
320 header = MbltSerializeMeta.read_header(path)
321 subgraphs = MbltSerializeMeta.get_model_dict(path).subgraphs
322 return header.num_buffers > 0, subgraphs
324 has_weights, subgraphs = _read_mblt_graph_info(model)
325 num_subgraphs = len(subgraphs)
326 effective_cpu_offload =
False if cpu_offload
is _UNSET
else bool(cpu_offload)
331 "The provided .mblt is not a runnable artifact and cannot be quantized "
332 "into an MXQ package (it looks like a `save_subgraph_type` preview "
333 "export). Recompile a runnable .mblt with `mblt_compile()` and use that "
334 "file as the `mxq_compile()` input instead."
338 raise ValueError(not_runnable_msg)
340 if num_subgraphs == 1:
344 if effective_cpu_offload:
346 "cpu_offload=True requires the model to contain multiple "
347 "subgraphs, but the provided .mblt contains a single subgraph. "
348 "Call `mxq_compile()` again with the `cpu_offload` argument set "
353 if sg.unsupported
or any(op.unsupported
for op
in sg.operators):
354 raise ValueError(not_runnable_msg)
359 if not effective_cpu_offload:
361 f
"cpu_offload=False cannot compile a model with {num_subgraphs} "
362 "subgraphs. Call `mxq_compile()` again with the `cpu_offload` "
363 "argument set to True"
367def _execute_quantize_request_V2(request: ResolvedQuantizeRequest_V2) ->
None:
368 """Execute a resolved V2 quantize request via the CompilerV2 pipeline.
372 * ``.mblt`` input on disk → single-stage pipeline of
373 :class:`MxqCompileStage` (the dominant ``quantize`` CLI case).
374 * Raw model input → two-stage pipeline
375 (:class:`MBLTCompileStage` writes an intermediate ``.mblt`` into
376 the pipeline's tempdir; :class:`MxqCompileStage` picks it up via
377 ``ctx.artifacts["mblt_path"]``).
379 logger.debug(
"MXQ compile: CompilerV2 pipeline path")
380 from qbcompiler.compiler.compiler_v2
import (
388 stages: list[PipelineStage] = []
389 if not _is_existing_mblt_input_V2(request.model):
394 parser_options=request.parser_options,
395 resolved_device=request.resolved_device,
396 resolved_cpu_offload=request.compile_config.cpu_offload,
397 target_device=request.parser_options.target_device,
398 save_subgraph_type=request.save_subgraph_type,
399 output_subgraph_path=request.output_subgraph_path,
404 mxq_input = request.model
409 compile_config=request.compile_config,
410 target_device=request.parser_options.target_device,
414 with CompilerV2(ResolvedPipeline(stages=tuple(stages)))
as compiler:
416 torch.cuda.empty_cache()
419def _execute_mblt_compile_request_V2(request: ResolvedMbltCompileRequest_V2) ->
None:
420 """Execute a resolved V2 compile-to-mblt request via the CompilerV2 pipeline.
422 Imported lazily so the pipeline module is only loaded on first use.
424 from qbcompiler.compiler.compiler_v2
import (
430 stage = MBLTCompileStage(
432 save_path=request.mblt_save_path,
433 parser_options=request.parser_options,
434 resolved_device=request.resolved_device,
435 resolved_cpu_offload=request.resolved_cpu_offload,
436 target_device=request.resolved_target_device,
437 compilation_mode=request.resolved_compilation_mode,
439 with CompilerV2(ResolvedPipeline(stages=(stage,)))
as compiler:
454 @brief Wrapper around the Mobilint compiler to support compilation and inference workflows.
456 @details Capabilities include:
457 - Compilation of models into MXQ artifacts runnable on Mobilint NPUs.
458 - Inference using the full-precision high-level compiled model on CPU or GPU.
459 - Inference with the quantized model on CPU or GPU.
470 yolo_decode_include=False,
471 exclude_first_subgraph=False,
475 @brief Initialize the Mobilint compiler wrapper.
477 @param model string or model instance. Model path or in-memory model to compile.
478 @param backend string. Framework identifier for the model (for example "onnx"). Defaults to "onnx".
479 @param device string. Target device for inference ("cpu" or "gpu"). Defaults to "cpu".
480 @param feed_dict dict. Example inputs for shape resolution.
481 @param dynamic_axes dict. Marks model axes as dynamic.
482 @param in_dformats dict. Describes input data formats.
483 @param yolo_decode_include bool. Runs YOLO decode on NPU when @c True.
484 @param exclude_first_subgraph bool. Applies only when CPU offloading is enabled: exclude the first subgraph from the final graph if it is unsupported.
485 @param kwargs dict. Additional compiler arguments.
493 in_dformats=in_dformats,
494 dynamic_axes=dynamic_axes,
495 yolo_decode_include=yolo_decode_include,
496 exclude_first_subgraph=exclude_first_subgraph,
502 save_subgraph_type: int = 0,
503 output_subgraph_path=
"",
504 compile_config: CompileConfig =
None,
508 @brief Compile the wrapped model into an MXQ artifact.
510 @param save_subgraph_type int. Controls optional MBLT exports: 0 disables; 1 saves graph structure; 2 saves
511 structure and weights; 3 splits structure into multiple subgraphs; 4 splits structure and weights.
512 @param output_subgraph_path string. Destination for exported .mblt when @p save_subgraph_type is 1–4.
513 @param compile_config CompileConfig. Compile configuration object.
514 @param kwargs dict. Additional arguments forwarded to the compiler.
517 save_sample = kwargs.pop(
"save_sample",
None)
518 sample_dtype = kwargs.pop(
"sample_dtype",
None)
519 if save_sample
is not None or sample_dtype
is not None:
521 "save_sample and sample_dtype are deprecated. Use compile_config with saveSample instead.",
525 if compile_config
is None:
526 compile_config = CompileConfig()
527 if not compile_config.save_sample.apply:
528 save_sample_kwargs = {}
529 if save_sample
is not None:
530 save_sample_kwargs[
"apply"] = save_sample
531 if sample_dtype
is not None:
532 save_sample_kwargs[
"dtype"] = sample_dtype
533 compile_config = compile_config.with_save_sample(**save_sample_kwargs)
536 save_subgraph_type=save_subgraph_type,
537 output_subgraph_path=output_subgraph_path,
538 compile_config=compile_config,
546 calib_data_path: Union[str, List[str]] = _UNSET,
547 save_subgraph_type: int = 0,
548 output_subgraph_path=
"",
549 save_path: Union[str, List[str]] = _UNSET,
555 yolo_decode_include=
False,
556 exclude_first_subgraph=
False,
559 inference_scheme=_UNSET,
560 use_random_calib=_UNSET,
562 optimize_option=_UNSET,
564 input_shape_dict=_UNSET,
565 force_npu_input_reposition=_UNSET,
566 force_npu_output_reposition=_UNSET,
567 image_channels=_UNSET,
571 config_preset: Optional[str] =
None,
572 compile_config: Optional[CompileConfig] =
None,
573 resource_management_config: Optional[ResourceManagementConfig] =
None,
574 calibration_config: Optional[CalibrationConfig] =
None,
575 bit_config: Optional[BitConfig] =
None,
576 llm_config: Optional[LlmConfig] =
None,
577 optq_config: Optional[OptqConfig] =
None,
578 mod_config: Optional[ModConfig] =
None,
579 equivalent_transformation_config: Optional[EquivalentTransformationConfig] =
None,
580 search_weight_scale_config: Optional[SearchWeightScaleConfig] =
None,
581 save_sample_config: Optional[SaveSampleConfig] =
None,
582 uint8_input_config: Optional[Uint8InputConfig] =
None,
583 preprocessing_config: Optional[PreprocessingConfig] =
None,
587 @brief Compile a model into a Mobilint eXeCUtable (MXQ) package for execution on Mobilint NPUs.
589 @details When no explicit value is provided for a parameter marked with @c _UNSET, the default
590 from CompileConfig is used. This allows a compile_config file or object to supply the value
591 without being overridden by function-level defaults.
593 Configuration is resolved in priority order (highest to lowest):
594 1. Explicitly passed function arguments
595 2. Individual sub-config objects (calibration_config, llm_config, etc.)
596 3. kwargs partial overrides (quantization_method, weight_dtype, etc.)
597 4. compile_config (CompileConfig object or JSON/YAML file) or config_preset
598 5. CompileConfig field defaults
600 @param model string or model instance. Model path. When using @c backend="onnx", this should be the path to an ONNX
601 model file. When @c backend is "torchscript", provide a TorchScript module; when "torch", provide a standard
602 PyTorch model. For @c backend="tf", pass the directory that contains the TensorFlow SavedModel graph and assets. For
603 @c backend="tflite", pass the TF Lite model path.
604 @param calib_data_path string or list of strings. Path(s) to the calibration dataset. Accepts either a text/json file
605 that lists NumPy files or a directory that contains the pre-processed NumPy files.
606 @param save_subgraph_type int. Controls optional MBLT subgraph exports: 0 disables exports; 1 saves only the graph
607 structure; 2 saves graph structure plus weights; 3 saves the graph structure split into multiple subgraphs; 4 saves
608 both structure and weights split into multiple subgraphs. Defaults to 0.
609 @param output_subgraph_path string. Destination path for the exported .mblt file when @p save_subgraph_type is 1–4.
610 The resulting file can be used for visualization. Defaults to "".
611 @param save_path string or list of strings. Output MXQ filename(s). When omitted, defaults to "{model_name}.mxq"
612 derived from the model path basename.
613 @param backend string. Framework used to generate the Mobilint IR. Must be one of "onnx", "tf", "tflite",
614 "torchscript", or "torch". Defaults to "onnx". When @p model is a path to an already-compiled .mblt file (the
615 output of @c mblt_compile()), it is compiled directly with MXQ regardless of the @p backend value,
616 and the file is validated beforehand; it must be a runnable
617 artifact produced by @c mblt_compile() rather than a @c save_subgraph_type preview export.
618 @param target_device string. Target NPU device for parser/compiler configuration (for example "aries-rb"). Required by execution paths that parse or quantize a model.
619 @param device string. Compilation and inference device: "cpu" or "gpu". When omitted, uses CompileConfig default.
620 @param feed_dict dict. Example input tensors for shape inference and inference validation.
621 @param dynamic_axes dict. Marks model axes as dynamic. Keys are input names and values map dimension indices to
622 aliases (for example {"input": {2: "seq_len"}}).
623 @param in_dformats dict. Describes input tensor data formats.
624 @param inference_scheme string. NPU inference scheme. One of "single", "multi", "global", "global4", or
625 "global8". When omitted, uses CompileConfig default.
626 @param yolo_decode_include bool. Determines whether YOLO decode runs on NPU. Defaults to @c False.
627 @param use_random_calib bool. Generates random calibration data to validate model compilability.
628 When omitted, uses CompileConfig default.
629 @param cpu_offload bool. Enables CPU offloading during NPU inference. When omitted, uses CompileConfig default.
630 @param optimize_option int. Compiler optimization strategy selector. When omitted, uses CompileConfig default.
631 @param buffer_mode int. Buffer serialization mode: 0 uses a naive buffer, 1 uses an mmap-backed buffer.
632 When omitted, uses CompileConfig default.
633 @param input_shape_dict dict. Multi-shape compilation specification for STT/TTS models only (e.g., Conformer-CTC,
634 MeloTTS). The dynamic axis is defined with respect to each input tensor's shape. During compilation, the same axis
635 is varied across all model inputs using the provided values. Currently, only a single entry key ("multi_shape0") is
636 supported. Example: {"multi_shape0": {"axis": 2, "values": [100, 200, 300]}}
637 @param force_npu_input_reposition bool. Force input reposition operations to run on NPU instead of CPU.
638 When omitted, uses CompileConfig default.
639 @param force_npu_output_reposition bool. Force output reposition operations to run on NPU instead of CPU.
640 When omitted, uses CompileConfig default.
641 @param image_channels int. Number of image channels (0 for auto-detect).
642 When omitted, uses CompileConfig default.
643 @param split_blocks list of int. Multi-MXQ split points by transformer block index.
644 Only supported for LLM models. When omitted, uses CompileConfig default.
645 @param split_parts int. Evenly split transformer blocks into N MXQ parts.
646 Only supported for LLM models. When omitted, uses CompileConfig default.
647 @param exclude_first_subgraph bool. Applies only when CPU offloading is enabled: exclude the first subgraph from
648 the final graph if it is unsupported. Defaults to @c False.
649 @param config_preset string. Name of a built-in configuration preset. When provided, loads the preset
650 via CompileConfig.from_preset(). Defaults to None (no preset). Available presets:
651 - "classification": Image classification models (ResNet, EfficientNet, ViT, etc.)
652 - "detection": Object detection models (YOLO, SSD, DETR, etc.)
653 - "classification_torchvision": Torchvision classification models with standard preprocessing
654 - "yolo_640": YOLO detection models with 640x640 letterbox preprocessing
655 - "yolo_1280": YOLO detection models with 1280x1280 letterbox preprocessing
656 - "llm": Large Language Models (LLaMA, Qwen, Gemma, etc.)
657 - "llm_fast": LLM with faster compilation (less accuracy optimization)
658 - "vision_transformer": Vision Transformer models (ViT, DeiT, Swin, etc.)
659 - "multimodal": Multimodal models (CLIP, BLIP, LLaVA, etc.)
660 @param compile_config CompileConfig or string. CompileConfig object or path to JSON/YAML configuration file
661 containing all compilation settings (resourceManagement, calibration, bit, optq, mod, llm, etc.).
662 @param resource_management_config ResourceManagementConfig. Resource management configuration object.
663 @param calibration_config CalibrationConfig. Calibration configuration object.
664 @param bit_config BitConfig. Bit configuration object for quantization precision settings.
665 @param llm_config LlmConfig. LLM configuration object.
666 @param optq_config OptqConfig. OPTQ (Optimal Brain Quantization) configuration object.
667 @param mod_config ModConfig. MOD (Metric-based Optimization and Distillation) configuration object.
668 @param equivalent_transformation_config EquivalentTransformationConfig. Configuration for equivalent
669 transformations like SmoothQuant.
670 @param search_weight_scale_config SearchWeightScaleConfig. Configuration for weight scale search.
671 @param save_sample_config SaveSampleConfig. Configuration for sample data generation and saving.
672 @param uint8_input_config Uint8InputConfig. Configuration for uint8 input handling.
673 @param preprocessing_config PreprocessingConfig. Preprocessing pipeline configuration.
674 @param kwargs dict. Additional compiler arguments. Supports partial config overrides such as
675 @c quantization_method, @c quantization_mode, @c percentile, @c weight_dtype, @c ram_usage,
676 @c max_sequence_length, etc. Also accepts deprecated parameters (@c quantization_config,
677 @c advanced_quantization_config, @c input_process_config, @c save_sample, @c sample_dtype)
678 which will emit DeprecationWarning.
681 @par Using configuration
682 There are three ways to configure quantization settings:
684 1. Load all settings from a JSON/YAML config file:
686 from qbcompiler import mxq_compile
689 model="path/to/model.onnx",
690 target_device="aries-rb",
691 calib_data_path="path/to/calib",
692 compile_config="path/to/config.json", # or config.yaml
697 2. Pass individual sub-config objects:
699 from qbcompiler import mxq_compile
700 from qbcompiler.configs import (
701 ResourceManagementConfig,
709 resource_mgmt = ResourceManagementConfig(weight_dtype="float32")
710 calib_cfg = CalibrationConfig(method=1, mode=1)
711 bit_cfg = BitConfig(...)
712 optq_cfg = OptqConfig(apply=True)
713 mod_cfg = ModConfig(apply=False)
714 llm_cfg = LlmConfig(apply=True)
717 model="path/to/model.onnx",
718 target_device="aries-rb",
719 calib_data_path="path/to/calib",
720 resource_management_config=resource_mgmt,
721 calibration_config=calib_cfg,
723 optq_config=optq_cfg,
730 3. Automatically applied partial configuration overrides:
732 from qbcompiler import mxq_compile
735 model="path/to/model.onnx",
736 target_device="aries-rb",
737 calib_data_path="path/to/calib",
738 quantization_method=1, # per channel quantization
739 quantization_mode=1, # max percentile quantization
740 percentile=0.999, # percentile value for max percentile quantization
741 quantization_output=0, # per layer quantization for the output layer
745 Please refer to the mxq_compile function and the quantization configuration section for the meaning of the quantization-related numeric values.
748 @par Compiling models with custom inputs (ONNX/Torch/TensorFlow)
749 Provide NumPy inputs whenever the model omits shape information so that qbcompiler can infer unknown dimensions and data
753 from qbcompiler import mxq_compile
757 "input_node_name_1": np.random.randn(1, 3, 224, 224).astype(np.float32),
758 "input_node_name_2": np.random.randn(1, 8, 224, 224).astype(np.float32),
759 "input_node_name_3": np.random.randn(1, 4, 56, 56).astype(np.float32),
763 "input_node_name_1": "NCHW",
764 "input_node_name_2": "NCHW",
765 "input_node_name_3": "NCHW",
768 onnx_model_path = "path/to/your/model.onnx"
770 model=onnx_model_path,
771 target_device="aries-rb",
772 feed_dict=example_input,
773 in_dformats=in_dformats,
775 compile_config="path/to/config.json",
779 target_device = validate_target_device(target_device)
781 if _is_existing_mblt_input_V2(model):
782 _validate_mblt_for_mxq_compile_V2(model, cpu_offload)
784 if backend ==
"onnx" or _is_existing_mblt_input_V2(model):
787 calib_data_path=calib_data_path,
788 save_subgraph_type=save_subgraph_type,
789 output_subgraph_path=output_subgraph_path,
792 target_device=target_device,
794 dynamic_axes=dynamic_axes,
795 in_dformats=in_dformats,
796 yolo_decode_include=yolo_decode_include,
797 exclude_first_subgraph=exclude_first_subgraph,
799 inference_scheme=inference_scheme,
800 use_random_calib=use_random_calib,
801 cpu_offload=cpu_offload,
802 optimize_option=optimize_option,
803 buffer_mode=buffer_mode,
804 input_shape_dict=input_shape_dict,
805 force_npu_input_reposition=force_npu_input_reposition,
806 force_npu_output_reposition=force_npu_output_reposition,
807 image_channels=image_channels,
808 split_blocks=split_blocks,
809 split_parts=split_parts,
810 config_preset=config_preset,
811 compile_config=compile_config,
812 resource_management_config=resource_management_config,
813 calibration_config=calibration_config,
814 bit_config=bit_config,
815 llm_config=llm_config,
816 optq_config=optq_config,
817 mod_config=mod_config,
818 equivalent_transformation_config=equivalent_transformation_config,
819 search_weight_scale_config=search_weight_scale_config,
820 save_sample_config=save_sample_config,
821 uint8_input_config=uint8_input_config,
822 preprocessing_config=preprocessing_config,
832 equivalent_transformation_config,
833 search_weight_scale_config,
835 preprocessing_config,
837 ) = _resolve_deprecated_kwargs(
838 calibration_config=calibration_config,
839 optq_config=optq_config,
840 mod_config=mod_config,
841 equivalent_transformation_config=equivalent_transformation_config,
842 search_weight_scale_config=search_weight_scale_config,
843 uint8_input_config=uint8_input_config,
844 preprocessing_config=preprocessing_config,
845 save_sample_config=save_sample_config,
850 if config_preset
is not None:
851 compile_cfg = CompileConfig.from_preset(config_preset)
852 elif compile_config
is None:
853 compile_cfg = CompileConfig()
854 elif isinstance(compile_config, CompileConfig):
855 compile_cfg = compile_config
856 elif isinstance(compile_config, str):
857 compile_cfg = CompileConfig.from_file(compile_config)
860 "compile_config must be a CompileConfig object or a path to JSON/YAML configuration file"
869 "save_path": _to_config_manager_unset_V2(save_path),
870 "calib_data_path": _to_config_manager_unset_V2(calib_data_path),
871 "use_random_calib": _to_config_manager_unset_V2(use_random_calib),
872 "inference_scheme": _to_config_manager_unset_V2(inference_scheme),
873 "cpu_offload": _to_config_manager_unset_V2(cpu_offload),
874 "optimize_option": _to_config_manager_unset_V2(optimize_option),
875 "buffer_mode": _to_config_manager_unset_V2(buffer_mode),
876 "input_shape_dict": _to_config_manager_unset_V2(input_shape_dict),
877 "device": _to_config_manager_unset_V2(device),
878 "force_npu_input_reposition": _to_config_manager_unset_V2(
879 force_npu_input_reposition
881 "force_npu_output_reposition": _to_config_manager_unset_V2(
882 force_npu_output_reposition
884 "image_channels": _to_config_manager_unset_V2(image_channels),
885 "split_blocks": _to_config_manager_unset_V2(split_blocks),
886 "split_parts": _to_config_manager_unset_V2(split_parts),
887 "resource_management_config": resource_management_config,
888 "calibration_config": calibration_config,
889 "bit_config": bit_config,
890 "llm_config": llm_config,
891 "optq_config": optq_config,
892 "mod_config": mod_config,
893 "equivalent_transformation_config": equivalent_transformation_config,
894 "search_weight_scale_config": search_weight_scale_config,
895 "save_sample_config": save_sample_config,
896 "uint8_input_config": uint8_input_config,
897 "preprocessing_config": preprocessing_config,
899 compile_cfg, kwargs = apply_compile_config_bindings(
900 compile_cfg, kwargs=kwargs, request_values=request_values
904 resolved_device = compile_cfg.device
906 if isinstance(model, str)
and model.endswith(
".mblt")
and os.path.isfile(model):
908 model, compile_config=compile_cfg, target_device=target_device
914 target_device=target_device,
915 device=resolved_device,
917 in_dformats=in_dformats,
918 dynamic_axes=dynamic_axes,
919 yolo_decode_include=yolo_decode_include,
920 exclude_first_subgraph=exclude_first_subgraph,
924 save_subgraph_type=save_subgraph_type,
925 output_subgraph_path=output_subgraph_path,
926 compile_config=compile_cfg,
928 torch.cuda.empty_cache()
941 yolo_decode_include=
False,
943 exclude_first_subgraph=
False,
947 @brief Export a model to the Mobilint .mblt format without producing an MXQ package.
949 @param model string or model instance. Source model or path to compile.
950 @param mblt_save_path string. Output path for the .mblt artifact.
951 @param backend string. Framework identifier ("onnx", "tf", "tflite", "torchscript", or "torch"). Defaults to
953 @param device string. Compilation device ("cpu" or "gpu"). Defaults to "cpu".
954 @param feed_dict dict. Example inputs used for shape inference.
955 @param dynamic_axes dict. Declares dynamic axes per input name.
956 @param in_dformats dict. Input dataformat metadata.
957 @param yolo_decode_include bool. Runs YOLO decode on NPU when True.
958 @param cpu_offload bool. Enables CPU offloading for unsupported groups.
959 @param exclude_first_subgraph bool. Applies only when CPU offloading is enabled: exclude the first subgraph from the final graph if it is unsupported.
960 @param kwargs dict. Additional arguments forwarded to the compiler.
963 target_device = validate_target_device(target_device)
964 if backend ==
"onnx":
967 mblt_save_path=mblt_save_path,
969 target_device=target_device,
972 dynamic_axes=dynamic_axes,
973 in_dformats=in_dformats,
974 yolo_decode_include=yolo_decode_include,
975 cpu_offload=cpu_offload,
976 exclude_first_subgraph=exclude_first_subgraph,
984 target_device=target_device,
987 dynamic_axes=dynamic_axes,
988 in_dformats=in_dformats,
989 yolo_decode_include=yolo_decode_include,
990 exclude_first_subgraph=exclude_first_subgraph,
994 model_dict.mblt_compile(
996 mblt_save_path=mblt_save_path,
998 cpu_offload=cpu_offload,
1006 calib_data_path: Union[str, List[str]] = _UNSET,
1007 save_subgraph_type: int = 0,
1008 output_subgraph_path=
"",
1009 save_path: Union[str, List[str]] = _UNSET,
1014 yolo_decode_include=
False,
1015 exclude_first_subgraph=
False,
1017 inference_scheme=_UNSET,
1018 use_random_calib=_UNSET,
1020 optimize_option=_UNSET,
1022 input_shape_dict=_UNSET,
1023 force_npu_input_reposition=_UNSET,
1024 force_npu_output_reposition=_UNSET,
1025 image_channels=_UNSET,
1026 split_blocks=_UNSET,
1028 config_preset: Optional[str] =
None,
1029 compile_config: Optional[CompileConfig | str] =
None,
1030 resource_management_config: Optional[ResourceManagementConfig] =
None,
1031 calibration_config: Optional[CalibrationConfig] =
None,
1032 bit_config: Optional[BitConfig] =
None,
1033 llm_config: Optional[LlmConfig] =
None,
1034 optq_config: Optional[OptqConfig] =
None,
1035 mod_config: Optional[ModConfig] =
None,
1036 equivalent_transformation_config: Optional[EquivalentTransformationConfig] =
None,
1037 search_weight_scale_config: Optional[SearchWeightScaleConfig] =
None,
1038 save_sample_config: Optional[SaveSampleConfig] =
None,
1039 uint8_input_config: Optional[Uint8InputConfig] =
None,
1040 preprocessing_config: Optional[PreprocessingConfig] =
None,
1043 """V2 compile/quantize entry point backed only by ConfigManager resolution."""
1044 request_V2 = _normalize_quantize_request_V2(
1046 save_path=save_path,
1048 target_device=target_device,
1049 feed_dict=feed_dict,
1050 dynamic_axes=dynamic_axes,
1051 in_dformats=in_dformats,
1052 yolo_decode_include=yolo_decode_include,
1053 exclude_first_subgraph=exclude_first_subgraph,
1054 save_subgraph_type=save_subgraph_type,
1055 output_subgraph_path=output_subgraph_path,
1056 calib_data_path=calib_data_path,
1058 inference_scheme=inference_scheme,
1059 use_random_calib=use_random_calib,
1060 cpu_offload=cpu_offload,
1061 optimize_option=optimize_option,
1062 buffer_mode=buffer_mode,
1063 input_shape_dict=input_shape_dict,
1064 force_npu_input_reposition=force_npu_input_reposition,
1065 force_npu_output_reposition=force_npu_output_reposition,
1066 image_channels=image_channels,
1067 split_blocks=split_blocks,
1068 split_parts=split_parts,
1069 config_preset=config_preset,
1070 compile_config=compile_config,
1071 resource_management_config=resource_management_config,
1072 calibration_config=calibration_config,
1073 bit_config=bit_config,
1074 llm_config=llm_config,
1075 optq_config=optq_config,
1076 mod_config=mod_config,
1077 equivalent_transformation_config=equivalent_transformation_config,
1078 search_weight_scale_config=search_weight_scale_config,
1079 save_sample_config=save_sample_config,
1080 uint8_input_config=uint8_input_config,
1081 preprocessing_config=preprocessing_config,
1084 resolved_request_V2 = ConfigManager.resolve_quantize_request_V2(request_V2)
1085 _execute_quantize_request_V2(resolved_request_V2)
1089 model: str | object,
1091 mblt_save_path: str,
1093 device: object = _UNSET,
1097 yolo_decode_include=
False,
1098 cpu_offload: object = _UNSET,
1099 exclude_first_subgraph=
False,
1100 config_preset: Optional[str] =
None,
1101 compile_config: Optional[CompileConfig | str] =
None,
1102 compilation_mode: Optional[str] =
None,
1105 """V2 compile-to-mblt entry point backed only by ConfigManager resolution.
1107 ``compilation_mode`` is an internal knob: one of
1108 ``{"release", "dev", "debug"}`` or ``None`` (default) to defer to the
1109 ``MBLT_APP_ENV`` environment variable. When set it overrides the env
1110 and drives the parser's ``inference_validation`` / ``device_alloc``
1111 / ``log_level`` cascade — the same preset as ``MBLT_APP_ENV``. Not
1112 surfaced in the CLI on purpose; intended for in-process scripts and
1113 tests that want scoped dev-mode validation without mutating
1114 process-wide environment.
1116 request_V2 = _normalize_mblt_compile_request_V2(
1118 mblt_save_path=mblt_save_path,
1120 target_device=target_device,
1122 feed_dict=feed_dict,
1123 dynamic_axes=dynamic_axes,
1124 in_dformats=in_dformats,
1125 yolo_decode_include=yolo_decode_include,
1126 cpu_offload=cpu_offload,
1127 exclude_first_subgraph=exclude_first_subgraph,
1128 config_preset=config_preset,
1129 compile_config=compile_config,
1130 compilation_mode=compilation_mode,
1133 resolved_request_V2 = ConfigManager.resolve_mblt_compile_request_V2(request_V2)
1134 _execute_mblt_compile_request_V2(resolved_request_V2)
1140 mblt_save_path: str,
1141 backend: str =
"onnx",
1142 device: Optional[str] =
None,
1143 cpu_offload: Optional[bool] =
None,
1144 config_preset: Optional[str] =
None,
1145 compile_config: Optional[CompileConfig | str] =
None,
1146 compilation_mode: Optional[str] =
None,
1148 progress_callback: Callable[[int, str],
None],
1150 """V2 compile-to-mblt entry point with progress callbacks.
1152 Only forwards explicitly-set values so ``mblt_compile_V2``'s ``_UNSET``
1153 defaults (and the merged ``CompileConfig`` behind them) apply when the
1154 caller omits a flag.
1156 call_kwargs: dict[str, Any] = {
1158 "mblt_save_path": mblt_save_path,
1160 "target_device": target_device,
1162 if device
is not None:
1163 call_kwargs[
"device"] = device
1164 if cpu_offload
is not None:
1165 call_kwargs[
"cpu_offload"] = cpu_offload
1166 if config_preset
is not None:
1167 call_kwargs[
"config_preset"] = config_preset
1168 if compile_config
is not None:
1169 call_kwargs[
"compile_config"] = compile_config
1170 if compilation_mode
is not None:
1171 call_kwargs[
"compilation_mode"] = compilation_mode
1173 with progress_context(progress_callback):
1174 emit_progress(0,
"Initializing compiler")
1176 emit_progress(100,
"Complete")
1183 backend: str =
"onnx",
1184 device: Optional[str] =
None,
1185 calib_data_path: Optional[Union[str, List[str]]] =
None,
1186 use_random_calib: Optional[bool] =
None,
1187 config_preset: Optional[str] =
None,
1188 compile_config: Optional[CompileConfig | str] =
None,
1190 progress_callback: Callable[[int, str],
None],
1192 """V2 compile/quantize entry point with progress callbacks."""
1193 call_kwargs: dict[str, object] = {
1195 "save_path": save_path,
1198 if device
is not None:
1199 call_kwargs[
"device"] = device
1200 if target_device
is not None:
1201 call_kwargs[
"target_device"] = target_device
1202 if calib_data_path
is not None:
1203 call_kwargs[
"calib_data_path"] = calib_data_path
1204 if use_random_calib
is not None:
1205 call_kwargs[
"use_random_calib"] = use_random_calib
1206 if config_preset
is not None:
1207 call_kwargs[
"config_preset"] = config_preset
1208 if compile_config
is not None:
1209 call_kwargs[
"compile_config"] = compile_config
1211 with progress_context(progress_callback):
1212 emit_progress(0,
"Initializing compiler")
1214 emit_progress(100,
"Complete")
1223 save_all_outputs: bool =
True,
1224 inference_output_path: Optional[str] =
None,
1225 target_subgraph: Optional[int] =
None,
1227 from qbcompiler.model_dict.common.model_dict
import ValueDict
1228 from qbcompiler.model_dict.inference.model
import ModelInference
1229 from qbcompiler.model_dict.serialize
import load_mblt_model
1231 assert path_to_mblt.endswith(
".mblt")
1232 if not save_all_outputs:
1233 raise NotImplementedError(
1234 f
"save_all_outputs={save_all_outputs} is not supported yet."
1237 raise NotImplementedError(
1238 f
"target_subgraph={target_subgraph} is not supported yet."
1242 if not inference_output_path:
1243 inference_output_path = str(pathlib.Path(path_to_mblt).with_suffix(
".infer"))
1246 md, wd = load_mblt_model(path_to_mblt, load_weight=
True)
1247 for sg
in md.subgraphs:
1248 for iidx
in sg.inputs:
1249 inact = sg.activations[iidx]
1250 if inact.name
in set(md.inputs):
1251 vd[inact.name] = numpy.random.random(tuple(map(int, inact.src_shape)))
1253 model_inference = ModelInference(
1257 save_all_outputs=save_all_outputs,
1258 inference_all_outputs_write_path=inference_output_path,
1261 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, exclude_first_subgraph=False, **kwargs)
Initialize the Mobilint compiler wrapper.
compile(self, int save_subgraph_type=0, output_subgraph_path="", CompileConfig compile_config=None, **kwargs)
Compile the wrapped model into an MXQ artifact.
None mxq_compile_with_callback_V2(str model, str target_device, str save_path, str backend="onnx", Optional[str] device=None, Optional[Union[str, List[str]]] calib_data_path=None, Optional[bool] use_random_calib=None, Optional[str] config_preset=None, Optional[CompileConfig|str] compile_config=None, *, Callable[[int, str], None] progress_callback)
V2 compile/quantize entry point with progress callbacks.
mblt_compile(str|Any model, str mblt_save_path, str target_device, backend="onnx", device="cpu", feed_dict=None, dynamic_axes=None, in_dformats=None, yolo_decode_include=False, cpu_offload=False, exclude_first_subgraph=False, **kwargs)
Export a model to the Mobilint .mblt format without producing an MXQ package.
None mblt_compile_V2(str|object model, str target_device, str mblt_save_path, backend="onnx", object device=_UNSET, feed_dict=None, dynamic_axes=None, in_dformats=None, yolo_decode_include=False, object cpu_offload=_UNSET, exclude_first_subgraph=False, Optional[str] config_preset=None, Optional[CompileConfig|str] compile_config=None, Optional[str] compilation_mode=None, **kwargs)
V2 compile-to-mblt entry point backed only by ConfigManager resolution.
None mblt_compile_with_callback_V2(str model, str target_device, str mblt_save_path, str backend="onnx", Optional[str] device=None, Optional[bool] cpu_offload=None, Optional[str] config_preset=None, Optional[CompileConfig|str] compile_config=None, Optional[str] compilation_mode=None, *, Callable[[int, str], None] progress_callback)
V2 compile-to-mblt entry point with progress callbacks.
mxq_compile(model, str target_device, Union[str, List[str]] calib_data_path=_UNSET, int save_subgraph_type=0, output_subgraph_path="", Union[str, List[str]] save_path=_UNSET, backend="onnx", feed_dict=None, dynamic_axes=None, in_dformats=None, yolo_decode_include=False, exclude_first_subgraph=False, device=_UNSET, inference_scheme=_UNSET, use_random_calib=_UNSET, cpu_offload=_UNSET, optimize_option=_UNSET, buffer_mode=_UNSET, input_shape_dict=_UNSET, force_npu_input_reposition=_UNSET, force_npu_output_reposition=_UNSET, image_channels=_UNSET, split_blocks=_UNSET, split_parts=_UNSET, Optional[str] config_preset=None, Optional[CompileConfig] compile_config=None, Optional[ResourceManagementConfig] resource_management_config=None, Optional[CalibrationConfig] calibration_config=None, Optional[BitConfig] bit_config=None, Optional[LlmConfig] llm_config=None, Optional[OptqConfig] optq_config=None, Optional[ModConfig] mod_config=None, Optional[EquivalentTransformationConfig] equivalent_transformation_config=None, Optional[SearchWeightScaleConfig] search_weight_scale_config=None, Optional[SaveSampleConfig] save_sample_config=None, Optional[Uint8InputConfig] uint8_input_config=None, Optional[PreprocessingConfig] preprocessing_config=None, **kwargs)
Compile a model into a Mobilint eXeCUtable (MXQ) package for execution on Mobilint NPUs.
None mxq_compile_V2(model, str target_device, Union[str, List[str]] calib_data_path=_UNSET, int save_subgraph_type=0, output_subgraph_path="", Union[str, List[str]] save_path=_UNSET, backend="onnx", feed_dict=None, dynamic_axes=None, in_dformats=None, yolo_decode_include=False, exclude_first_subgraph=False, device=_UNSET, inference_scheme=_UNSET, use_random_calib=_UNSET, cpu_offload=_UNSET, optimize_option=_UNSET, buffer_mode=_UNSET, input_shape_dict=_UNSET, force_npu_input_reposition=_UNSET, force_npu_output_reposition=_UNSET, image_channels=_UNSET, split_blocks=_UNSET, split_parts=_UNSET, Optional[str] config_preset=None, Optional[CompileConfig|str] compile_config=None, Optional[ResourceManagementConfig] resource_management_config=None, Optional[CalibrationConfig] calibration_config=None, Optional[BitConfig] bit_config=None, Optional[LlmConfig] llm_config=None, Optional[OptqConfig] optq_config=None, Optional[ModConfig] mod_config=None, Optional[EquivalentTransformationConfig] equivalent_transformation_config=None, Optional[SearchWeightScaleConfig] search_weight_scale_config=None, Optional[SaveSampleConfig] save_sample_config=None, Optional[Uint8InputConfig] uint8_input_config=None, Optional[PreprocessingConfig] preprocessing_config=None, **kwargs)
V2 compile/quantize entry point backed only by ConfigManager resolution.