frontend.py Source File

frontend.py Source File#

Mobilint SDK qb Compiler: frontend.py Source File
Mobilint SDK qb Compiler v1.3
MCS002-EN
frontend.py
Go to the documentation of this file.
1
4
5import warnings
6from collections.abc import Callable
7from typing import Any, List, Optional, Union
8
9import torch
10from qbcompiler.compiler.compiler_legacy import LegacyCompiler
11from qbcompiler.compiler.compiler_legacy import _quantization_task
12from qbcompiler.compiler.execution import (
13 execute_mblt_compile_request,
14 execute_quantize_request,
15)
16from qbcompiler.compiler.utils import validate_target_device
17from qbcompiler.configs import (
18 CompileConfig,
19 CalibrationConfig,
20 BitConfig,
21 ResourceManagementConfig,
22 HessianQuantConfig,
23 LayerBiasCorrectionConfig,
24 ModConfig,
25 LlmConfig,
26 EquivalentTransformationConfig,
27 SearchWeightScaleConfig,
28 SaveSampleConfig,
29 Uint8InputConfig,
30 PreprocessingConfig,
31)
32from qbcompiler.model_dict.backends import (
33 MODEL_DICT_BACKENDS,
34 normalize_backend,
35)
36from qbcompiler.compile_requests import (
37 UNSET,
38 MxqCompileResolveRequest,
39 build_mblt_compile_request,
40 build_quantize_request,
41)
42from qbcompiler.artifact.input import is_existing_mblt_input
43from qbcompiler.config_resolver import ConfigManager, save_compile_config
44from qbcompiler.config_resolver.deprecations import reject_hf_config
45from qbcompiler.reporting.logging import get_logger
46from qbcompiler.reporting.progress import emit_progress, progress_context
47
48logger = get_logger(__name__)
49
50
55
56
57class Model_Dict(LegacyCompiler):
58 """
59 @brief Wrapper around the Mobilint compiler to support compilation and inference workflows.
60
61 @details Capabilities include:
62 - Compilation of models into MXQ artifacts runnable on Mobilint NPUs.
63 - Inference using the full-precision high-level compiled model on CPU or GPU.
64 - Inference with the quantized model on CPU or GPU.
65 """
66
68 self,
69 model,
70 backend="onnx",
71 device="cpu",
72 feed_dict=None,
73 dynamic_axes=None,
74 in_dformats=None,
75 yolo_decode_include=False,
76 exclude_first_subgraph=False,
77 **kwargs,
78 ):
79 """
80 @brief Initialize the Mobilint compiler wrapper.
81
82 @param model string or model instance. Model path or in-memory model to compile.
83 @param backend string. Framework identifier for the model (for example "onnx"). Defaults to "onnx".
84 @param device string. Target device for inference ("cpu" or "gpu"). Defaults to "cpu".
85 @param feed_dict dict. Example inputs for shape resolution.
86 @param dynamic_axes dict. Marks model axes as dynamic.
87 @param in_dformats dict. Describes input data formats.
88 @param yolo_decode_include bool. Runs YOLO decode on NPU when @c True.
89 @param exclude_first_subgraph bool. Applies only when CPU offloading is enabled: exclude the first subgraph from the final graph if it is unsupported.
90 @param kwargs dict. Additional compiler arguments.
91 """
92
93 super().__init__(
94 model=model,
95 backend=backend,
96 device=device,
97 feed_dict=feed_dict,
98 in_dformats=in_dformats,
99 dynamic_axes=dynamic_axes,
100 yolo_decode_include=yolo_decode_include,
101 exclude_first_subgraph=exclude_first_subgraph,
102 **kwargs,
103 )
104
106 self,
107 save_subgraph_type: int = 0,
108 output_subgraph_path="",
109 compile_config: CompileConfig = None,
110 **kwargs,
111 ):
112 """
113 @brief Compile the wrapped model into an MXQ artifact.
114
115 @param save_subgraph_type int. Controls optional MBLT exports: 0 disables; 1 saves graph structure; 2 saves
116 structure and weights; 3 splits structure into multiple subgraphs; 4 splits structure and weights.
117 @param output_subgraph_path string. Destination for exported .mblt when @p save_subgraph_type is 1–4.
118 @param compile_config CompileConfig. Compile configuration object.
119 @param kwargs dict. Additional arguments forwarded to the compiler.
120
121 """
122 save_sample = kwargs.pop("save_sample", None)
123 sample_dtype = kwargs.pop("sample_dtype", None)
124 if save_sample is not None or sample_dtype is not None:
125 warnings.warn(
126 "save_sample and sample_dtype are deprecated. Use compile_config with saveSample instead.",
127 DeprecationWarning,
128 stacklevel=2,
129 )
130 if compile_config is None:
131 compile_config = CompileConfig()
132 if not compile_config.save_sample.apply:
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 compile_config = compile_config.with_save_sample(**save_sample_kwargs)
139
140 super().compile(
141 save_subgraph_type=save_subgraph_type,
142 output_subgraph_path=output_subgraph_path,
143 compile_config=compile_config,
144 **kwargs,
145 )
146
147
148def mxq_compile(
149 model,
150 target_device: str,
151 calib_data_path: Union[str, List[str]] = UNSET,
152 save_subgraph_type: int = 0,
153 output_subgraph_path="",
154 save_path: Union[str, List[str]] = UNSET,
155 backend="onnx",
156 # -- ModelDict params --
157 feed_dict=None,
158 dynamic_axes=None,
159 in_dformats=None,
160 yolo_decode_include=False,
161 exclude_first_subgraph=False,
162 # -- CompileConfig-overridable (UNSET = defer to config) --
163 device=UNSET,
164 inference_scheme=UNSET,
165 use_random_calib=UNSET,
166 cpu_offload=UNSET,
167 optimize_option=UNSET,
168 buffer_mode=UNSET,
169 input_shape_dict=UNSET,
170 force_npu_input_reposition=UNSET,
171 force_npu_output_reposition=UNSET,
172 image_channels=UNSET,
173 split_blocks=UNSET,
174 split_parts=UNSET,
175 # -- Config objects --
176 config_preset: Optional[str] = None,
177 compile_config: Optional[CompileConfig] = None,
178 resource_management_config: Optional[ResourceManagementConfig] = None,
179 calibration_config: Optional[CalibrationConfig] = None,
180 bit_config: Optional[BitConfig] = None,
181 llm_config: Optional[LlmConfig] = None,
182 hessian_quant_config: Optional[HessianQuantConfig] = None,
183 mod_config: Optional[ModConfig] = None,
184 equivalent_transformation_config: Optional[EquivalentTransformationConfig] = None,
185 search_weight_scale_config: Optional[SearchWeightScaleConfig] = None,
186 save_sample_config: Optional[SaveSampleConfig] = None,
187 uint8_input_config: Optional[Uint8InputConfig] = None,
188 preprocessing_config: Optional[PreprocessingConfig] = None,
189 layer_bias_correction=UNSET,
190 layer_bias_correction_config: Optional[LayerBiasCorrectionConfig] = None,
191 model_part: Optional[str] = None,
192 model_part_options: Optional[dict] = None,
193 config_save_path: Optional[str] = None,
194 **kwargs,
195):
196 """
197 @brief Compile a model into a Mobilint eXeCUtable (MXQ) package for execution on Mobilint NPUs.
198
199 @details When no explicit value is provided for a parameter marked with @c UNSET, the default
200 from CompileConfig is used. This allows a compile_config file or object to supply the value
201 without being overridden by function-level defaults.
202
203 Configuration is resolved in priority order (highest to lowest):
204 1. Explicitly passed function arguments
205 2. Individual sub-config objects (calibration_config, llm_config, etc.)
206 3. kwargs partial overrides (quantization_method, weight_dtype, etc.)
207 4. compile_config (CompileConfig object or JSON/YAML file) or config_preset
208 5. CompileConfig field defaults
209
210 @param model string or model instance. Model path. When using @c backend="onnx", this should be the path to an ONNX
211 model file. When @c backend is "torchscript", provide a TorchScript module; when "torch", provide a standard
212 PyTorch model. For @c backend="tf", pass the directory that contains the TensorFlow SavedModel graph and assets. For
213 @c backend="tflite", pass the TF Lite model path.
214 @param calib_data_path string or list of strings. Path(s) to the calibration dataset. Accepts either a text/json file
215 that lists NumPy files or a directory that contains the pre-processed NumPy files.
216 @param save_subgraph_type int. Controls optional MBLT subgraph exports: 0 disables exports; 1 saves only the graph
217 structure; 2 saves graph structure plus weights; 3 saves the graph structure split into multiple subgraphs; 4 saves
218 both structure and weights split into multiple subgraphs. Defaults to 0.
219 @param output_subgraph_path string. Destination path for the exported .mblt file when @p save_subgraph_type is 1–4.
220 The resulting file can be used for visualization. Defaults to "".
221 @param save_path string or list of strings. Output MXQ filename(s). When omitted, defaults to "{model_name}.mxq"
222 derived from the model path basename.
223 @param backend string. Framework used to generate the Mobilint IR. Case-insensitive, so "ONNX" and "onnx" are
224 the same backend. "onnx" and "torch" are parsed by the current parser; "tf" (also spelled "tensorflow"), "tflite" and
225 "torchscript" go through the legacy parser. Any other value raises @c ValueError. Defaults to "onnx". When @p model is a path to an already-compiled .mblt file (the
226 output of @c mblt_compile()), it is compiled directly with MXQ regardless of the @p backend value,
227 and the file is validated beforehand; it must be a runnable
228 artifact produced by @c mblt_compile() rather than a @c save_subgraph_type preview export.
229 @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.
230 @param device string. Compilation and inference device: "cpu" or "gpu". When omitted, uses CompileConfig default.
231 @param feed_dict dict. Example input tensors for shape inference and inference validation.
232 @param dynamic_axes dict. Marks model axes as dynamic. Keys are input names and values map dimension indices to
233 aliases (for example {"input": {2: "seq_len"}}).
234 @param in_dformats dict. Describes input tensor data formats.
235 @param inference_scheme string. NPU inference scheme. One of "single", "multi", "global", "global4", or
236 "global8". When omitted, uses CompileConfig default.
237 @param yolo_decode_include bool. Determines whether YOLO decode runs on NPU. Defaults to @c False.
238 @param use_random_calib bool. Generates random calibration data to validate model compilability.
239 When omitted, uses CompileConfig default.
240 @param cpu_offload bool. Enables CPU offloading during NPU inference. When omitted, uses CompileConfig default.
241 @param optimize_option int. Compiler optimization strategy selector. When omitted, uses CompileConfig default.
242 @param buffer_mode int. Buffer serialization mode: 0 uses a naive buffer, 1 uses an mmap-backed buffer.
243 When omitted, uses CompileConfig default.
244 @param input_shape_dict dict. Multi-shape compilation specification for STT/TTS models only (e.g., Conformer-CTC,
245 MeloTTS). The dynamic axis is defined with respect to each input tensor's shape. During compilation, the same axis
246 is varied across all model inputs using the provided values. Currently, only a single entry key ("multi_shape0") is
247 supported. Example: {"multi_shape0": {"axis": 2, "values": [100, 200, 300]}}
248 @param force_npu_input_reposition bool. Force input reposition operations to run on NPU instead of CPU.
249 When omitted, uses CompileConfig default.
250 @param force_npu_output_reposition bool. Force output reposition operations to run on NPU instead of CPU.
251 When omitted, uses CompileConfig default.
252 @param image_channels int. Number of image channels (0 for auto-detect).
253 When omitted, uses CompileConfig default.
254 @param split_blocks list of int. Multi-MXQ split points by transformer block index.
255 Only supported for LLM models. When omitted, uses CompileConfig default.
256 @param split_parts int. Evenly split transformer blocks into N MXQ parts.
257 Only supported for LLM models. When omitted, uses CompileConfig default.
258 @param layer_bias_correction bool. Enables calibration-derived layer bias correction.
259 When omitted, uses @p layer_bias_correction_config or the CompileConfig value.
260 @param exclude_first_subgraph bool. Applies only when CPU offloading is enabled: exclude the first subgraph from
261 the final graph if it is unsupported. Defaults to @c False.
262 @param config_preset string. Name of a built-in configuration preset. When provided, loads the preset
263 via CompileConfig.from_preset(). Defaults to None (no preset). Available presets:
264 - "classification": Image classification models (ResNet, EfficientNet, ViT, etc.)
265 - "detection": Object detection models (YOLO, SSD, DETR, etc.)
266 - "classification_torchvision": Torchvision classification models with standard preprocessing
267 - "yolo_640": YOLO detection models with 640x640 letterbox preprocessing
268 - "yolo_1280": YOLO detection models with 1280x1280 letterbox preprocessing
269 - "llm": Large Language Models (LLaMA, Qwen, Gemma, etc.)
270 - "llm_fast": LLM with faster compilation (less accuracy optimization)
271 - "vision_transformer": Vision Transformer models (ViT, DeiT, Swin, etc.)
272 - "multimodal": Multimodal models (CLIP, BLIP, LLaVA, etc.)
273 @param compile_config CompileConfig or string. CompileConfig object or path to JSON/YAML configuration file
274 containing all compilation settings (resourceManagement, calibration, bit, hessianQuant, mod, llm, etc.).
275 @param config_save_path string. When provided, the fully resolved configuration - the normalized
276 CompileConfig after every layer of the precedence order above has been applied, including all
277 sub-configurations - is written to this path before compilation starts. The format follows the path
278 suffix: ".yaml"/".yml" produce YAML, anything else produces JSON. Parent directories are created as
279 needed. The saved file can be fed back as @p compile_config to reproduce the same compilation.
280 Defaults to None (no config file is written).
281 @param resource_management_config ResourceManagementConfig. Resource management configuration object.
282 @param calibration_config CalibrationConfig. Calibration configuration object.
283 @param bit_config BitConfig. Bit configuration object for quantization precision settings.
284 @param llm_config LlmConfig. LLM configuration object.
285 @param hessian_quant_config HessianQuantConfig. HessianQuant (Hessian-based Quantization) configuration object.
286 @param layer_bias_correction_config LayerBiasCorrectionConfig. Calibration-derived layer bias correction settings.
287 @param model_part string. Selects a specific part of a torch model to parse ("vision", "language",
288 "encoder", ...). Typically used to support models with complex architectures (e.g. Qwen3-VL) by compiling
289 one part at a time. Parts a model declares: parser.patcher.parts.available_parts(model).
290 A model declaring exactly one part resolves it from None; one declaring several requires a name.
291 @param model_part_options dict. Extra arguments for the named part (e.g. {"mel_frames": 100} for Qwen3-ASR audio).
292 @param mod_config ModConfig. MOD (Metric-based Optimization and Distillation) configuration object.
293 @param equivalent_transformation_config EquivalentTransformationConfig. Configuration for equivalent
294 transformations like SmoothQuant.
295 @param search_weight_scale_config SearchWeightScaleConfig. Configuration for weight scale search.
296 @param save_sample_config SaveSampleConfig. Configuration for sample data generation and saving.
297 @param uint8_input_config Uint8InputConfig. Configuration for uint8 input handling.
298 @param preprocessing_config PreprocessingConfig. Preprocessing pipeline configuration.
299 @param kwargs dict. Additional compiler arguments. Supports partial config overrides such as
300 @c quantization_method, @c quantization_mode, @c percentile, @c weight_dtype, @c ram_usage,
301 @c max_sequence_length, etc. Also accepts deprecated parameters (@c quantization_config,
302 @c advanced_quantization_config, @c input_process_config, @c save_sample, @c sample_dtype)
303 which will emit DeprecationWarning.
304 @return None.
305
306 @par Using configuration
307 There are three ways to configure quantization settings:
308
309 1. Load all settings from a JSON/YAML config file:
310 @code{.py}
311 from qbcompiler import mxq_compile
312
313 mxq_compile(
314 model="path/to/model.onnx",
315 target_device="aries-rb",
316 calib_data_path="path/to/calib",
317 compile_config="path/to/config.json", # or config.yaml
318 device="gpu",
319 )
320 @endcode
321
322 2. Pass individual sub-config objects:
323 @code{.py}
324 from qbcompiler import mxq_compile
325 from qbcompiler.configs import (
326 ResourceManagementConfig,
327 CalibrationConfig,
328 BitConfig,
329 HessianQuantConfig,
330 ModConfig,
331 LlmConfig,
332 )
333
334 resource_mgmt = ResourceManagementConfig(weight_dtype="float32")
335 calib_cfg = CalibrationConfig(method=1, mode=1)
336 bit_cfg = BitConfig(...)
337 hessian_quant_cfg = HessianQuantConfig(apply=True)
338 mod_cfg = ModConfig(apply=False)
339 llm_cfg = LlmConfig(apply=True)
340
341 mxq_compile(
342 model="path/to/model.onnx",
343 target_device="aries-rb",
344 calib_data_path="path/to/calib",
345 resource_management_config=resource_mgmt,
346 calibration_config=calib_cfg,
347 bit_config=bit_cfg,
348 hessian_quant_config=hessian_quant_cfg,
349 mod_config=mod_cfg,
350 llm_config=llm_cfg,
351 device="gpu",
352 )
353 @endcode
354
355 3. Automatically applied partial configuration overrides:
356 @code{.py}
357 from qbcompiler import mxq_compile
358
359 mxq_compile(
360 model="path/to/model.onnx",
361 target_device="aries-rb",
362 calib_data_path="path/to/calib",
363 quantization_method=1, # per channel quantization
364 quantization_mode=1, # max percentile quantization
365 percentile=0.999, # percentile value for max percentile quantization
366 quantization_output=0, # per layer quantization for the output layer
367 device="gpu",
368 )
369 @endcode
370 Please refer to the mxq_compile function and the quantization configuration section for the meaning of the quantization-related numeric values.
371
372
373 @par Compiling models with custom inputs (ONNX/Torch/TensorFlow)
374 Provide NumPy inputs whenever the model omits shape information so that qbcompiler can infer unknown dimensions and data
375 formats.
376
377 @code{.py}
378 from qbcompiler import mxq_compile
379 import numpy as np
380
381 example_input = {
382 "input_node_name_1": np.random.randn(1, 3, 224, 224).astype(np.float32),
383 "input_node_name_2": np.random.randn(1, 8, 224, 224).astype(np.float32),
384 "input_node_name_3": np.random.randn(1, 4, 56, 56).astype(np.float32),
385 }
386
387 in_dformats = {
388 "input_node_name_1": "NCHW",
389 "input_node_name_2": "NCHW",
390 "input_node_name_3": "NCHW",
391 }
392
393 onnx_model_path = "path/to/your/model.onnx"
394 mxq_compile(
395 model=onnx_model_path,
396 target_device="aries-rb",
397 feed_dict=example_input,
398 in_dformats=in_dformats,
399 backend="onnx",
400 compile_config="path/to/config.json",
401 )
402 @endcode
403 """
404 target_device = validate_target_device(target_device)
405 reject_hf_config(kwargs)
406
407 if is_existing_mblt_input(model):
408 if model_part is not None or model_part_options is not None:
409 raise ValueError(
410 "model_part / model_part_options apply to parsing a live model; "
411 f"{model!r} is an already-parsed .mblt. Pass the part when "
412 "producing the mblt (mblt_compile), or pass the source model here."
413 )
415 mblt=model,
416 calib_data_path=calib_data_path,
417 save_path=save_path,
418 backend=backend,
419 device=device,
420 inference_scheme=inference_scheme,
421 use_random_calib=use_random_calib,
422 cpu_offload=cpu_offload,
423 optimize_option=optimize_option,
424 buffer_mode=buffer_mode,
425 input_shape_dict=input_shape_dict,
426 force_npu_input_reposition=force_npu_input_reposition,
427 force_npu_output_reposition=force_npu_output_reposition,
428 image_channels=image_channels,
429 split_blocks=split_blocks,
430 split_parts=split_parts,
431 config_preset=config_preset,
432 compile_config=compile_config,
433 resource_management_config=resource_management_config,
434 calibration_config=calibration_config,
435 bit_config=bit_config,
436 llm_config=llm_config,
437 hessian_quant_config=hessian_quant_config,
438 mod_config=mod_config,
439 equivalent_transformation_config=equivalent_transformation_config,
440 search_weight_scale_config=search_weight_scale_config,
441 save_sample_config=save_sample_config,
442 uint8_input_config=uint8_input_config,
443 preprocessing_config=preprocessing_config,
444 layer_bias_correction=layer_bias_correction,
445 layer_bias_correction_config=layer_bias_correction_config,
446 config_save_path=config_save_path,
447 target_device=target_device,
448 **kwargs,
449 )
450 return
451
453 model=model,
454 calib_data_path=calib_data_path,
455 save_subgraph_type=save_subgraph_type,
456 output_subgraph_path=output_subgraph_path,
457 save_path=save_path,
458 backend=backend,
459 feed_dict=feed_dict,
460 dynamic_axes=dynamic_axes,
461 in_dformats=in_dformats,
462 yolo_decode_include=yolo_decode_include,
463 exclude_first_subgraph=exclude_first_subgraph,
464 device=device,
465 inference_scheme=inference_scheme,
466 use_random_calib=use_random_calib,
467 cpu_offload=cpu_offload,
468 optimize_option=optimize_option,
469 buffer_mode=buffer_mode,
470 input_shape_dict=input_shape_dict,
471 force_npu_input_reposition=force_npu_input_reposition,
472 force_npu_output_reposition=force_npu_output_reposition,
473 image_channels=image_channels,
474 split_blocks=split_blocks,
475 split_parts=split_parts,
476 config_preset=config_preset,
477 compile_config=compile_config,
478 resource_management_config=resource_management_config,
479 calibration_config=calibration_config,
480 bit_config=bit_config,
481 llm_config=llm_config,
482 hessian_quant_config=hessian_quant_config,
483 mod_config=mod_config,
484 equivalent_transformation_config=equivalent_transformation_config,
485 search_weight_scale_config=search_weight_scale_config,
486 save_sample_config=save_sample_config,
487 uint8_input_config=uint8_input_config,
488 preprocessing_config=preprocessing_config,
489 layer_bias_correction=layer_bias_correction,
490 layer_bias_correction_config=layer_bias_correction_config,
491 model_part=model_part,
492 model_part_options=model_part_options,
493 config_save_path=config_save_path,
494 target_device=target_device,
495 **kwargs,
496 )
497
498
500 model,
501 target_device: str,
502 calib_data_path: Union[str, List[str]] = UNSET,
503 save_subgraph_type: int = 0,
504 output_subgraph_path="",
505 save_path: Union[str, List[str]] = UNSET,
506 backend="onnx",
507 # -- ModelDict params --
508 feed_dict=None,
509 dynamic_axes=None,
510 in_dformats=None,
511 yolo_decode_include=False,
512 exclude_first_subgraph=False,
513 # -- CompileConfig-overridable (UNSET = defer to config) --
514 device=UNSET,
515 inference_scheme=UNSET,
516 use_random_calib=UNSET,
517 cpu_offload=UNSET,
518 optimize_option=UNSET,
519 buffer_mode=UNSET,
520 input_shape_dict=UNSET,
521 force_npu_input_reposition=UNSET,
522 force_npu_output_reposition=UNSET,
523 image_channels=UNSET,
524 split_blocks=UNSET,
525 split_parts=UNSET,
526 # -- Config objects --
527 config_preset: Optional[str] = None,
528 compile_config: Optional[CompileConfig] = None,
529 resource_management_config: Optional[ResourceManagementConfig] = None,
530 calibration_config: Optional[CalibrationConfig] = None,
531 bit_config: Optional[BitConfig] = None,
532 llm_config: Optional[LlmConfig] = None,
533 hessian_quant_config: Optional[HessianQuantConfig] = None,
534 mod_config: Optional[ModConfig] = None,
535 equivalent_transformation_config: Optional[EquivalentTransformationConfig] = None,
536 search_weight_scale_config: Optional[SearchWeightScaleConfig] = None,
537 save_sample_config: Optional[SaveSampleConfig] = None,
538 uint8_input_config: Optional[Uint8InputConfig] = None,
539 preprocessing_config: Optional[PreprocessingConfig] = None,
540 layer_bias_correction=UNSET,
541 layer_bias_correction_config: Optional[LayerBiasCorrectionConfig] = None,
542 model_part: Optional[str] = None,
543 model_part_options: Optional[dict] = None,
544 config_save_path: Optional[str] = None,
545 **kwargs,
546):
547 """
548 @brief Compile a raw framework model (ONNX / PyTorch / TensorFlow / TF-Lite) into an MXQ package.
549
550 @details This is the raw-model half of @c mxq_compile(): it parses the model into
551 Mobilint IR and then quantizes and compiles it in one pass. The parameters, their
552 defaults, and the configuration precedence rules are identical to @c mxq_compile() —
553 see that function for the full reference and usage examples.
554
555 Passing the path of an existing @c .mblt file here raises @c ValueError; use
556 @c mxq_compile_from_mblt() for that input instead. @c mxq_compile() routes between
557 the two automatically.
558
559 @param model string or model instance. Raw model or path to one. Must not be an
560 existing @c .mblt file.
561 @param target_device string. Target NPU device (for example "aries-rb").
562 @return None.
563 """
564 if is_existing_mblt_input(model):
565 raise ValueError(
566 "mxq_compile_from_source() does not accept an existing .mblt file. Call "
567 "mxq_compile_from_mblt() instead, or mxq_compile() to route automatically."
568 )
569
570 target_device = validate_target_device(target_device)
571 backend = normalize_backend(backend)
572 reject_hf_config(kwargs)
573
574 if backend in MODEL_DICT_BACKENDS:
576 model=model,
577 calib_data_path=calib_data_path,
578 save_subgraph_type=save_subgraph_type,
579 output_subgraph_path=output_subgraph_path,
580 save_path=save_path,
581 backend=backend,
582 target_device=target_device,
583 feed_dict=feed_dict,
584 dynamic_axes=dynamic_axes,
585 in_dformats=in_dformats,
586 yolo_decode_include=yolo_decode_include,
587 exclude_first_subgraph=exclude_first_subgraph,
588 device=device,
589 inference_scheme=inference_scheme,
590 use_random_calib=use_random_calib,
591 cpu_offload=cpu_offload,
592 optimize_option=optimize_option,
593 buffer_mode=buffer_mode,
594 input_shape_dict=input_shape_dict,
595 force_npu_input_reposition=force_npu_input_reposition,
596 force_npu_output_reposition=force_npu_output_reposition,
597 image_channels=image_channels,
598 split_blocks=split_blocks,
599 split_parts=split_parts,
600 layer_bias_correction=layer_bias_correction,
601 config_preset=config_preset,
602 compile_config=compile_config,
603 config_save_path=config_save_path,
604 resource_management_config=resource_management_config,
605 calibration_config=calibration_config,
606 bit_config=bit_config,
607 llm_config=llm_config,
608 hessian_quant_config=hessian_quant_config,
609 layer_bias_correction_config=layer_bias_correction_config,
610 mod_config=mod_config,
611 equivalent_transformation_config=equivalent_transformation_config,
612 search_weight_scale_config=search_weight_scale_config,
613 save_sample_config=save_sample_config,
614 uint8_input_config=uint8_input_config,
615 preprocessing_config=preprocessing_config,
616 model_part=model_part,
617 model_part_options=model_part_options,
618 **kwargs,
619 )
620 return
621
622 if model_part is not None or model_part_options is not None:
623 raise ValueError(
624 "model_part / model_part_options are only implemented for the "
625 f"{', '.join(sorted(MODEL_DICT_BACKENDS))} backends; backend="
626 f"{backend!r} parses through the legacy parser, which selects the "
627 "submodule to compile in the model-specific script instead."
628 )
629
631 model=model,
632 target_device=target_device,
633 calib_data_path=calib_data_path,
634 save_subgraph_type=save_subgraph_type,
635 output_subgraph_path=output_subgraph_path,
636 save_path=save_path,
637 backend=backend,
638 feed_dict=feed_dict,
639 dynamic_axes=dynamic_axes,
640 in_dformats=in_dformats,
641 yolo_decode_include=yolo_decode_include,
642 exclude_first_subgraph=exclude_first_subgraph,
643 device=device,
644 inference_scheme=inference_scheme,
645 use_random_calib=use_random_calib,
646 cpu_offload=cpu_offload,
647 optimize_option=optimize_option,
648 buffer_mode=buffer_mode,
649 input_shape_dict=input_shape_dict,
650 force_npu_input_reposition=force_npu_input_reposition,
651 force_npu_output_reposition=force_npu_output_reposition,
652 image_channels=image_channels,
653 split_blocks=split_blocks,
654 split_parts=split_parts,
655 config_preset=config_preset,
656 compile_config=compile_config,
657 resource_management_config=resource_management_config,
658 calibration_config=calibration_config,
659 bit_config=bit_config,
660 llm_config=llm_config,
661 hessian_quant_config=hessian_quant_config,
662 mod_config=mod_config,
663 equivalent_transformation_config=equivalent_transformation_config,
664 search_weight_scale_config=search_weight_scale_config,
665 save_sample_config=save_sample_config,
666 uint8_input_config=uint8_input_config,
667 preprocessing_config=preprocessing_config,
668 layer_bias_correction=layer_bias_correction,
669 layer_bias_correction_config=layer_bias_correction_config,
670 config_save_path=config_save_path,
671 **kwargs,
672 )
673
674
676 *,
677 model,
678 target_device: str,
679 calib_data_path: Union[str, List[str]] = UNSET,
680 save_subgraph_type: int = 0,
681 output_subgraph_path="",
682 save_path: Union[str, List[str]] = UNSET,
683 backend="onnx",
684 feed_dict=None,
685 dynamic_axes=None,
686 in_dformats=None,
687 yolo_decode_include=False,
688 exclude_first_subgraph=False,
689 device=UNSET,
690 inference_scheme=UNSET,
691 use_random_calib=UNSET,
692 cpu_offload=UNSET,
693 optimize_option=UNSET,
694 buffer_mode=UNSET,
695 input_shape_dict=UNSET,
696 force_npu_input_reposition=UNSET,
697 force_npu_output_reposition=UNSET,
698 image_channels=UNSET,
699 split_blocks=UNSET,
700 split_parts=UNSET,
701 config_preset: Optional[str] = None,
702 compile_config: Optional[CompileConfig] = None,
703 resource_management_config: Optional[ResourceManagementConfig] = None,
704 calibration_config: Optional[CalibrationConfig] = None,
705 bit_config: Optional[BitConfig] = None,
706 llm_config: Optional[LlmConfig] = None,
707 hessian_quant_config: Optional[HessianQuantConfig] = None,
708 mod_config: Optional[ModConfig] = None,
709 equivalent_transformation_config: Optional[EquivalentTransformationConfig] = None,
710 search_weight_scale_config: Optional[SearchWeightScaleConfig] = None,
711 save_sample_config: Optional[SaveSampleConfig] = None,
712 uint8_input_config: Optional[Uint8InputConfig] = None,
713 preprocessing_config: Optional[PreprocessingConfig] = None,
714 layer_bias_correction=UNSET,
715 layer_bias_correction_config: Optional[LayerBiasCorrectionConfig] = None,
716 config_save_path: Optional[str] = None,
717 **kwargs,
718) -> None:
719 """Quantize and compile through the legacy ``Model_Dict`` parser.
720
721 Reached for the backends the pipeline does not implement -- tf, tflite, hf,
722 torchscript and the model-specific misc parsers. Configuration resolution
723 goes through the same ``ConfigManager.resolve_mxq_compile`` the pipeline
724 path uses, so only the parser differs; the kwargs it hands back are the
725 ones the bindings registry did not consume, which is what the parser gets.
726
727 Callers route here through :func:`mxq_compile_from_source`, which has
728 already validated ``target_device`` and normalized ``backend``.
729 """
730 resolved = ConfigManager.resolve_mxq_compile(
731 MxqCompileResolveRequest(
732 model=model,
733 calib_data_path=calib_data_path,
734 save_path=save_path,
735 device=device,
736 inference_scheme=inference_scheme,
737 use_random_calib=use_random_calib,
738 cpu_offload=cpu_offload,
739 optimize_option=optimize_option,
740 buffer_mode=buffer_mode,
741 input_shape_dict=input_shape_dict,
742 force_npu_input_reposition=force_npu_input_reposition,
743 force_npu_output_reposition=force_npu_output_reposition,
744 image_channels=image_channels,
745 split_blocks=split_blocks,
746 split_parts=split_parts,
747 layer_bias_correction=layer_bias_correction,
748 config_preset=config_preset,
749 compile_config=compile_config,
750 resource_management_config=resource_management_config,
751 calibration_config=calibration_config,
752 bit_config=bit_config,
753 llm_config=llm_config,
754 hessian_quant_config=hessian_quant_config,
755 layer_bias_correction_config=layer_bias_correction_config,
756 mod_config=mod_config,
757 equivalent_transformation_config=equivalent_transformation_config,
758 search_weight_scale_config=search_weight_scale_config,
759 save_sample_config=save_sample_config,
760 uint8_input_config=uint8_input_config,
761 preprocessing_config=preprocessing_config,
762 kwargs=kwargs,
763 )
764 )
765 compile_cfg = resolved.compile_config
766 # Whatever the bindings registry did not claim belongs to the parser.
767 kwargs = resolved.remaining_kwargs
768
769 resolved_device = resolved.resolved_device
770
771 if config_save_path is not None:
772 save_compile_config(compile_cfg, config_save_path)
773
774 if is_existing_mblt_input(model):
775 _quantization_task(
776 model, compile_config=compile_cfg, target_device=target_device
777 )
778 else:
779 model_dict = Model_Dict(
780 model=model,
781 backend=backend,
782 target_device=target_device,
783 device=resolved_device,
784 feed_dict=feed_dict,
785 in_dformats=in_dformats,
786 dynamic_axes=dynamic_axes,
787 yolo_decode_include=yolo_decode_include,
788 exclude_first_subgraph=exclude_first_subgraph,
789 **kwargs,
790 )
791 model_dict.compile(
792 save_subgraph_type=save_subgraph_type,
793 output_subgraph_path=output_subgraph_path,
794 compile_config=compile_cfg,
795 )
796 torch.cuda.empty_cache()
797 del model_dict
798
799
801 mblt: str,
802 target_device: str,
803 calib_data_path: Union[str, List[str]] = UNSET,
804 save_path: Union[str, List[str]] = UNSET,
805 backend="onnx",
806 device=UNSET,
807 inference_scheme=UNSET,
808 use_random_calib=UNSET,
809 cpu_offload=UNSET,
810 optimize_option=UNSET,
811 buffer_mode=UNSET,
812 input_shape_dict=UNSET,
813 force_npu_input_reposition=UNSET,
814 force_npu_output_reposition=UNSET,
815 image_channels=UNSET,
816 split_blocks=UNSET,
817 split_parts=UNSET,
818 config_preset: Optional[str] = None,
819 compile_config: Optional[CompileConfig] = None,
820 resource_management_config: Optional[ResourceManagementConfig] = None,
821 calibration_config: Optional[CalibrationConfig] = None,
822 bit_config: Optional[BitConfig] = None,
823 llm_config: Optional[LlmConfig] = None,
824 hessian_quant_config: Optional[HessianQuantConfig] = None,
825 mod_config: Optional[ModConfig] = None,
826 equivalent_transformation_config: Optional[EquivalentTransformationConfig] = None,
827 search_weight_scale_config: Optional[SearchWeightScaleConfig] = None,
828 save_sample_config: Optional[SaveSampleConfig] = None,
829 uint8_input_config: Optional[Uint8InputConfig] = None,
830 preprocessing_config: Optional[PreprocessingConfig] = None,
831 layer_bias_correction=UNSET,
832 layer_bias_correction_config: Optional[LayerBiasCorrectionConfig] = None,
833 config_save_path: Optional[str] = None,
834 **kwargs,
835):
836 """
837 @brief Compile an existing Mobilint IR (@c .mblt) file into an MXQ package.
838
839 @details This is the pre-parsed half of @c mxq_compile(): parsing already happened
840 (via @c mblt_compile()), so this function only quantizes and compiles. Quantization
841 parameters, their defaults, and the configuration precedence rules are identical to
842 @c mxq_compile() — see that function for the full reference and usage examples.
843
844 Parser-only arguments (@c save_subgraph_type, @c output_subgraph_path, @c feed_dict,
845 @c dynamic_axes, @c in_dformats, @c yolo_decode_include, @c exclude_first_subgraph)
846 are absent because the graph is already parsed. @c mxq_compile() accepts them for
847 backward compatibility and drops them when routing here.
848
849 @param mblt string. Path to a runnable @c .mblt produced by @c mblt_compile(). The
850 file is validated up front; a @c save_subgraph_type preview export is rejected.
851 @param target_device string. Target NPU device (for example "aries-rb").
852 @param backend string. Retained for backward compatibility and ignored: the graph is
853 already parsed, so no parser backend is selected.
854 @return None.
855
856 @exception ValueError @p mblt is not an existing @c .mblt file, or it is not a
857 runnable artifact for the requested @p cpu_offload setting.
858 """
859 target_device = validate_target_device(target_device)
860 reject_hf_config(kwargs)
861
862 if not is_existing_mblt_input(mblt):
863 raise ValueError(
864 f"mxq_compile_from_mblt() requires an existing .mblt file, got {mblt!r}. "
865 "Produce one with mblt_compile() first."
866 )
867 # The artifact itself is validated in the pipeline planner, where
868 # cpu_offload has been resolved against compile_config / config_preset.
869
871 model=mblt,
872 calib_data_path=calib_data_path,
873 save_path=save_path,
874 backend=backend,
875 device=device,
876 inference_scheme=inference_scheme,
877 use_random_calib=use_random_calib,
878 cpu_offload=cpu_offload,
879 optimize_option=optimize_option,
880 buffer_mode=buffer_mode,
881 input_shape_dict=input_shape_dict,
882 force_npu_input_reposition=force_npu_input_reposition,
883 force_npu_output_reposition=force_npu_output_reposition,
884 image_channels=image_channels,
885 split_blocks=split_blocks,
886 split_parts=split_parts,
887 config_preset=config_preset,
888 compile_config=compile_config,
889 resource_management_config=resource_management_config,
890 calibration_config=calibration_config,
891 bit_config=bit_config,
892 llm_config=llm_config,
893 hessian_quant_config=hessian_quant_config,
894 mod_config=mod_config,
895 equivalent_transformation_config=equivalent_transformation_config,
896 search_weight_scale_config=search_weight_scale_config,
897 save_sample_config=save_sample_config,
898 uint8_input_config=uint8_input_config,
899 preprocessing_config=preprocessing_config,
900 layer_bias_correction=layer_bias_correction,
901 layer_bias_correction_config=layer_bias_correction_config,
902 config_save_path=config_save_path,
903 target_device=target_device,
904 **kwargs,
905 )
906
907
908def mblt_compile(
909 model: str | Any,
910 mblt_save_path: str,
911 target_device: str,
912 backend="onnx",
913 device="cpu",
914 feed_dict=None,
915 dynamic_axes=None,
916 in_dformats=None,
917 yolo_decode_include=False,
918 cpu_offload=False,
919 exclude_first_subgraph=False,
920 model_part: Optional[str] = None,
921 model_part_options: Optional[dict] = None,
922 **kwargs,
923):
924 """
925 @brief Export a model to the Mobilint .mblt format without producing an MXQ package.
926
927 @param model string or model instance. Source model or path to compile.
928 @param mblt_save_path string. Output path for the .mblt artifact.
929 @param backend string. Framework identifier, case-insensitive. "onnx" and "torch" are parsed by the current
930 parser; "tf" (also spelled "tensorflow"), "tflite" and "torchscript" go through the legacy parser.
931 Any other value raises @c ValueError. Defaults to "onnx".
932 @param device string. Compilation device ("cpu" or "gpu"). Defaults to "cpu".
933 @param feed_dict dict. Example inputs used for shape inference.
934 @param dynamic_axes dict. Declares dynamic axes per input name.
935 @param in_dformats dict. Input dataformat metadata.
936 @param yolo_decode_include bool. Runs YOLO decode on NPU when True.
937 @param cpu_offload bool. Enables CPU offloading for unsupported groups.
938 @param exclude_first_subgraph bool. Applies only when CPU offloading is enabled: exclude the first subgraph from the final graph if it is unsupported.
939 @param model_part string. Selects a specific part of a torch model to parse ("vision", "language",
940 "encoder", ...). Typically used to support models with complex architectures (e.g. Qwen3-VL) by compiling
941 one part at a time. Parts a model declares: parser.patcher.parts.available_parts(model).
942 A model declaring exactly one part resolves it from None; one declaring several requires a name.
943 @param model_part_options dict. Extra arguments for the named part (e.g. {"mel_frames": 100} for Qwen3-ASR audio).
944 @param kwargs dict. Additional arguments forwarded to the compiler.
945 @return None.
946 """
948 model=model,
949 mblt_save_path=mblt_save_path,
950 target_device=target_device,
951 backend=backend,
952 device=device,
953 feed_dict=feed_dict,
954 dynamic_axes=dynamic_axes,
955 in_dformats=in_dformats,
956 yolo_decode_include=yolo_decode_include,
957 cpu_offload=cpu_offload,
958 exclude_first_subgraph=exclude_first_subgraph,
959 model_part=model_part,
960 model_part_options=model_part_options,
961 **kwargs,
962 )
963
964
966 model: str | Any,
967 mblt_save_path: str,
968 target_device: str,
969 backend="onnx",
970 device=UNSET,
971 feed_dict=None,
972 dynamic_axes=None,
973 in_dformats=None,
974 yolo_decode_include=False,
975 cpu_offload=UNSET,
976 exclude_first_subgraph=False,
977 model_part: Optional[str] = None,
978 model_part_options: Optional[dict] = None,
979 **kwargs,
980) -> None:
981 """Route a compile-to-mblt call to the pipeline or the legacy parser.
982
983 Shared by :func:`mblt_compile` and :func:`mblt_compile_with_callback` so
984 both validate ``target_device``, normalize ``backend`` and pick the parser
985 the same way. ``device`` / ``cpu_offload`` default to ``UNSET`` here rather
986 than to concrete values: that is what lets the callback wrapper forward only
987 the flags its caller actually set and leave the rest to the merged
988 ``CompileConfig``. :func:`mblt_compile` keeps its own historical
989 ``"cpu"`` / ``False`` defaults and passes them explicitly.
990 """
991 target_device = validate_target_device(target_device)
992 backend = normalize_backend(backend)
993 reject_hf_config(kwargs)
994
995 if backend in MODEL_DICT_BACKENDS:
997 model=model,
998 mblt_save_path=mblt_save_path,
999 backend=backend,
1000 target_device=target_device,
1001 device=device,
1002 feed_dict=feed_dict,
1003 dynamic_axes=dynamic_axes,
1004 in_dformats=in_dformats,
1005 yolo_decode_include=yolo_decode_include,
1006 cpu_offload=cpu_offload,
1007 exclude_first_subgraph=exclude_first_subgraph,
1008 model_part=model_part,
1009 model_part_options=model_part_options,
1010 **kwargs,
1011 )
1012 return
1013
1014 if model_part is not None or model_part_options is not None:
1015 raise ValueError(
1016 "model_part / model_part_options are only implemented for the "
1017 f"{', '.join(sorted(MODEL_DICT_BACKENDS))} backends; backend="
1018 f"{backend!r} parses through the legacy parser, which selects the "
1019 "submodule to compile in the model-specific script instead."
1020 )
1021
1023 model=model,
1024 mblt_save_path=mblt_save_path,
1025 target_device=target_device,
1026 backend=backend,
1027 device=device,
1028 feed_dict=feed_dict,
1029 dynamic_axes=dynamic_axes,
1030 in_dformats=in_dformats,
1031 yolo_decode_include=yolo_decode_include,
1032 cpu_offload=cpu_offload,
1033 exclude_first_subgraph=exclude_first_subgraph,
1034 **kwargs,
1035 )
1036
1037
1039 *,
1040 model: str | Any,
1041 mblt_save_path: str,
1042 target_device: str,
1043 backend: str,
1044 device=UNSET,
1045 feed_dict=None,
1046 dynamic_axes=None,
1047 in_dformats=None,
1048 yolo_decode_include=False,
1049 cpu_offload=UNSET,
1050 exclude_first_subgraph=False,
1051 **kwargs,
1052) -> None:
1053 """Export to ``.mblt`` through the legacy ``Model_Dict`` parser.
1054
1055 Reached for the backends the pipeline does not implement -- tf, tflite, hf,
1056 torchscript and the model-specific misc parsers. This parser has no
1057 ``CompileConfig`` fallback for ``device`` / ``cpu_offload``, so an unset
1058 value takes :func:`mblt_compile`'s documented default.
1059 """
1060 device = "cpu" if device is UNSET else device
1061 cpu_offload = False if cpu_offload is UNSET else cpu_offload
1062
1063 model_dict = Model_Dict(
1064 model=model,
1065 backend=backend,
1066 target_device=target_device,
1067 device=device,
1068 feed_dict=feed_dict,
1069 dynamic_axes=dynamic_axes,
1070 in_dformats=in_dformats,
1071 yolo_decode_include=yolo_decode_include,
1072 exclude_first_subgraph=exclude_first_subgraph,
1073 **kwargs,
1074 )
1075
1076 model_dict.mblt_compile(
1077 model,
1078 mblt_save_path=mblt_save_path,
1079 backend=backend,
1080 cpu_offload=cpu_offload,
1081 **kwargs,
1082 )
1083
1084
1086 model,
1087 target_device: str,
1088 calib_data_path: Union[str, List[str]] = UNSET,
1089 save_subgraph_type: int = 0,
1090 output_subgraph_path="",
1091 save_path: Union[str, List[str]] = UNSET,
1092 backend="onnx",
1093 feed_dict=None,
1094 dynamic_axes=None,
1095 in_dformats=None,
1096 yolo_decode_include=False,
1097 exclude_first_subgraph=False,
1098 device=UNSET,
1099 inference_scheme=UNSET,
1100 use_random_calib=UNSET,
1101 cpu_offload=UNSET,
1102 optimize_option=UNSET,
1103 buffer_mode=UNSET,
1104 input_shape_dict=UNSET,
1105 force_npu_input_reposition=UNSET,
1106 force_npu_output_reposition=UNSET,
1107 image_channels=UNSET,
1108 split_blocks=UNSET,
1109 split_parts=UNSET,
1110 config_preset: Optional[str] = None,
1111 compile_config: Optional[CompileConfig | str] = None,
1112 resource_management_config: Optional[ResourceManagementConfig] = None,
1113 calibration_config: Optional[CalibrationConfig] = None,
1114 bit_config: Optional[BitConfig] = None,
1115 llm_config: Optional[LlmConfig] = None,
1116 hessian_quant_config: Optional[HessianQuantConfig] = None,
1117 mod_config: Optional[ModConfig] = None,
1118 equivalent_transformation_config: Optional[EquivalentTransformationConfig] = None,
1119 search_weight_scale_config: Optional[SearchWeightScaleConfig] = None,
1120 save_sample_config: Optional[SaveSampleConfig] = None,
1121 uint8_input_config: Optional[Uint8InputConfig] = None,
1122 preprocessing_config: Optional[PreprocessingConfig] = None,
1123 layer_bias_correction=UNSET,
1124 layer_bias_correction_config: Optional[LayerBiasCorrectionConfig] = None,
1125 model_part: Optional[str] = None,
1126 model_part_options: Optional[dict] = None,
1127 config_save_path: Optional[str] = None,
1128 **kwargs,
1129) -> None:
1130 """Quantize and compile through the ConfigManager-resolved pipeline.
1131
1132 Serves the backends in ``MODEL_DICT_BACKENDS``; the callers
1133 (:func:`mxq_compile_from_source`, :func:`mxq_compile_from_mblt`) have
1134 already validated ``target_device`` and normalized ``backend``.
1135 """
1136 request = build_quantize_request(
1137 model=model,
1138 save_path=save_path,
1139 backend=backend,
1140 target_device=target_device,
1141 feed_dict=feed_dict,
1142 dynamic_axes=dynamic_axes,
1143 in_dformats=in_dformats,
1144 yolo_decode_include=yolo_decode_include,
1145 exclude_first_subgraph=exclude_first_subgraph,
1146 save_subgraph_type=save_subgraph_type,
1147 output_subgraph_path=output_subgraph_path,
1148 calib_data_path=calib_data_path,
1149 device=device,
1150 inference_scheme=inference_scheme,
1151 use_random_calib=use_random_calib,
1152 cpu_offload=cpu_offload,
1153 optimize_option=optimize_option,
1154 buffer_mode=buffer_mode,
1155 input_shape_dict=input_shape_dict,
1156 force_npu_input_reposition=force_npu_input_reposition,
1157 force_npu_output_reposition=force_npu_output_reposition,
1158 image_channels=image_channels,
1159 split_blocks=split_blocks,
1160 split_parts=split_parts,
1161 layer_bias_correction=layer_bias_correction,
1162 config_preset=config_preset,
1163 compile_config=compile_config,
1164 resource_management_config=resource_management_config,
1165 calibration_config=calibration_config,
1166 bit_config=bit_config,
1167 llm_config=llm_config,
1168 hessian_quant_config=hessian_quant_config,
1169 layer_bias_correction_config=layer_bias_correction_config,
1170 mod_config=mod_config,
1171 equivalent_transformation_config=equivalent_transformation_config,
1172 search_weight_scale_config=search_weight_scale_config,
1173 save_sample_config=save_sample_config,
1174 uint8_input_config=uint8_input_config,
1175 preprocessing_config=preprocessing_config,
1176 model_part=model_part,
1177 model_part_options=model_part_options,
1178 **kwargs,
1179 )
1180 resolved_request = ConfigManager.resolve_quantize_request(request)
1181 if config_save_path is not None:
1182 # Written before the (potentially hours-long) compile starts, so the
1183 # record survives a failure. Two fields still hold their defaults here
1184 # because ``MxqCompileStage`` fills them at execution time:
1185 # ``model_paths`` -- which for a raw-model input is a throwaway path in
1186 # the pipeline tempdir -- and ``runtime_options.version``.
1187 save_compile_config(resolved_request.compile_config, config_save_path)
1188 execute_quantize_request(resolved_request)
1189
1190
1192 model: str | object,
1193 target_device: str,
1194 mblt_save_path: str,
1195 backend="onnx",
1196 device: object = UNSET,
1197 feed_dict=None,
1198 dynamic_axes=None,
1199 in_dformats=None,
1200 yolo_decode_include=False,
1201 cpu_offload: object = UNSET,
1202 exclude_first_subgraph=False,
1203 model_part: Optional[str] = None,
1204 model_part_options: Optional[dict] = None,
1205 config_preset: Optional[str] = None,
1206 compile_config: Optional[CompileConfig | str] = None,
1207 compilation_mode: Optional[str] = None,
1208 **kwargs,
1209) -> None:
1210 """Export to ``.mblt`` through the ConfigManager-resolved pipeline.
1211
1212 ``compilation_mode`` is an internal knob: one of
1213 ``{"release", "dev", "debug"}`` or ``None`` (default) to defer to the
1214 ``MBLT_APP_ENV`` environment variable. When set it overrides the env
1215 and drives the parser's ``inference_validation`` / ``device_alloc``
1216 / ``log_level`` cascade — the same preset as ``MBLT_APP_ENV``. Not
1217 surfaced in the CLI on purpose; intended for in-process scripts and
1218 tests that want scoped dev-mode validation without mutating
1219 process-wide environment.
1220 """
1221 request = build_mblt_compile_request(
1222 model=model,
1223 mblt_save_path=mblt_save_path,
1224 backend=backend,
1225 target_device=target_device,
1226 device=device,
1227 feed_dict=feed_dict,
1228 dynamic_axes=dynamic_axes,
1229 in_dformats=in_dformats,
1230 yolo_decode_include=yolo_decode_include,
1231 cpu_offload=cpu_offload,
1232 exclude_first_subgraph=exclude_first_subgraph,
1233 model_part=model_part,
1234 model_part_options=model_part_options,
1235 config_preset=config_preset,
1236 compile_config=compile_config,
1237 compilation_mode=compilation_mode,
1238 **kwargs,
1239 )
1240 resolved_request = ConfigManager.resolve_mblt_compile_request(request)
1241 execute_mblt_compile_request(resolved_request)
1242
1243
1245 model: str,
1246 mblt_save_path: str,
1247 target_device: str,
1248 backend: str = "onnx",
1249 device: Optional[str] = None,
1250 cpu_offload: Optional[bool] = None,
1251 config_preset: Optional[str] = None,
1252 compile_config: Optional[CompileConfig | str] = None,
1253 compilation_mode: Optional[str] = None,
1254 *,
1255 progress_callback: Callable[[int, str], None],
1256) -> None:
1257 """Compile-to-mblt entry point with progress callbacks.
1258
1259 Only forwards explicitly-set values so the ``UNSET`` defaults (and the
1260 merged ``CompileConfig`` behind them) apply when the caller omits a flag --
1261 which is why this goes through ``_mblt_compile_dispatch`` rather than
1262 :func:`mblt_compile`, whose own ``device`` / ``cpu_offload`` defaults would
1263 override the config. ``target_device`` is required and has no config
1264 fallback — callers (e.g. the CLI) validate it via
1265 ``validate_target_device`` before invoking (QC-228).
1266 """
1267 call_kwargs: dict[str, Any] = {
1268 "model": model,
1269 "mblt_save_path": mblt_save_path,
1270 "backend": backend,
1271 "target_device": target_device,
1272 }
1273 if device is not None:
1274 call_kwargs["device"] = device
1275 if cpu_offload is not None:
1276 call_kwargs["cpu_offload"] = cpu_offload
1277 if config_preset is not None:
1278 call_kwargs["config_preset"] = config_preset
1279 if compile_config is not None:
1280 call_kwargs["compile_config"] = compile_config
1281 if compilation_mode is not None:
1282 call_kwargs["compilation_mode"] = compilation_mode
1283
1284 with progress_context(progress_callback):
1285 emit_progress(0, "Initializing compiler")
1286 _mblt_compile_dispatch(**call_kwargs)
1287 emit_progress(100, "Complete")
1288
1289
1291 model: str,
1292 target_device: str,
1293 save_path: str,
1294 backend: str = "onnx",
1295 device: Optional[str] = None,
1296 calib_data_path: Optional[Union[str, List[str]]] = None,
1297 use_random_calib: Optional[bool] = None,
1298 config_preset: Optional[str] = None,
1299 compile_config: Optional[CompileConfig | str] = None,
1300 config_save_path: Optional[str] = None,
1301 *,
1302 progress_callback: Callable[[int, str], None],
1303) -> None:
1304 """Compile/quantize entry point with progress callbacks.
1305
1306 ``target_device`` is required and has no config fallback — callers
1307 (e.g. the CLI) validate it via ``validate_target_device`` before
1308 invoking, and the wrapper forwards it unconditionally (QC-228).
1309
1310 Like :func:`mblt_compile_with_callback`, only explicitly-set values are
1311 forwarded, so :func:`mxq_compile`'s ``UNSET`` defaults (and the merged
1312 ``CompileConfig`` behind them) still apply to whatever the caller omits.
1313 ``config_save_path`` passes straight through, and the resolved config is
1314 written there before compilation starts; this is what backs the CLI's
1315 ``--config-save-path`` on ``quantize`` / ``compile``.
1316 """
1317 call_kwargs: dict[str, object] = {
1318 "model": model,
1319 "save_path": save_path,
1320 "backend": backend,
1321 "target_device": target_device,
1322 }
1323 if device is not None:
1324 call_kwargs["device"] = device
1325 if calib_data_path is not None:
1326 call_kwargs["calib_data_path"] = calib_data_path
1327 if use_random_calib is not None:
1328 call_kwargs["use_random_calib"] = use_random_calib
1329 if config_preset is not None:
1330 call_kwargs["config_preset"] = config_preset
1331 if compile_config is not None:
1332 call_kwargs["compile_config"] = compile_config
1333 if config_save_path is not None:
1334 call_kwargs["config_save_path"] = config_save_path
1335
1336 with progress_context(progress_callback):
1337 emit_progress(0, "Initializing compiler")
1338 mxq_compile(**call_kwargs)
1339 emit_progress(100, "Complete")
1340
1341
1342
Unified compilation configuration for Mobilint MXQ compilation.
Definition models.py:1848
Wrapper around the Mobilint compiler to support compilation and inference workflows.
Definition frontend.py:57
__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.
Definition frontend.py:78
compile(self, int save_subgraph_type=0, output_subgraph_path="", CompileConfig compile_config=None, **kwargs)
Compile the wrapped model into an MXQ artifact.
Definition frontend.py:111
None _mblt_compile_dispatch(str|Any model, str mblt_save_path, str target_device, backend="onnx", device=UNSET, feed_dict=None, dynamic_axes=None, in_dformats=None, yolo_decode_include=False, cpu_offload=UNSET, exclude_first_subgraph=False, Optional[str] model_part=None, Optional[dict] model_part_options=None, **kwargs)
Route a compile-to-mblt call to the pipeline or the legacy parser.
Definition frontend.py:980
None _mxq_compile_pipeline(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[HessianQuantConfig] hessian_quant_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, layer_bias_correction=UNSET, Optional[LayerBiasCorrectionConfig] layer_bias_correction_config=None, Optional[str] model_part=None, Optional[dict] model_part_options=None, Optional[str] config_save_path=None, **kwargs)
Quantize and compile through the ConfigManager-resolved pipeline.
Definition frontend.py:1129
None _mxq_compile_legacy(*, 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[HessianQuantConfig] hessian_quant_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, layer_bias_correction=UNSET, Optional[LayerBiasCorrectionConfig] layer_bias_correction_config=None, Optional[str] config_save_path=None, **kwargs)
Quantize and compile through the legacy Model_Dict parser.
Definition frontend.py:718
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[HessianQuantConfig] hessian_quant_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, layer_bias_correction=UNSET, Optional[LayerBiasCorrectionConfig] layer_bias_correction_config=None, Optional[str] model_part=None, Optional[dict] model_part_options=None, Optional[str] config_save_path=None, **kwargs)
Compile a model into a Mobilint eXeCUtable (MXQ) package for execution on Mobilint NPUs.
Definition frontend.py:195
None _mblt_compile_pipeline(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] model_part=None, Optional[dict] model_part_options=None, Optional[str] config_preset=None, Optional[CompileConfig|str] compile_config=None, Optional[str] compilation_mode=None, **kwargs)
Export to .mblt through the ConfigManager-resolved pipeline.
Definition frontend.py:1209
mxq_compile_from_source(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[HessianQuantConfig] hessian_quant_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, layer_bias_correction=UNSET, Optional[LayerBiasCorrectionConfig] layer_bias_correction_config=None, Optional[str] model_part=None, Optional[dict] model_part_options=None, Optional[str] config_save_path=None, **kwargs)
Compile a raw framework model (ONNX / PyTorch / TensorFlow / TF-Lite) into an MXQ package.
Definition frontend.py:546
None _mblt_compile_legacy(*, str|Any model, str mblt_save_path, str target_device, str backend, device=UNSET, feed_dict=None, dynamic_axes=None, in_dformats=None, yolo_decode_include=False, cpu_offload=UNSET, exclude_first_subgraph=False, **kwargs)
Export to .mblt through the legacy Model_Dict parser.
Definition frontend.py:1052
mxq_compile_from_mblt(str mblt, str target_device, Union[str, List[str]] calib_data_path=UNSET, Union[str, List[str]] save_path=UNSET, backend="onnx", 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[HessianQuantConfig] hessian_quant_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, layer_bias_correction=UNSET, Optional[LayerBiasCorrectionConfig] layer_bias_correction_config=None, Optional[str] config_save_path=None, **kwargs)
Compile an existing Mobilint IR (.mblt) file into an MXQ package.
Definition frontend.py:835
None mxq_compile_with_callback(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, Optional[str] config_save_path=None, *, Callable[[int, str], None] progress_callback)
Compile/quantize entry point with progress callbacks.
Definition frontend.py:1303
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, Optional[str] model_part=None, Optional[dict] model_part_options=None, **kwargs)
Export a model to the Mobilint .mblt format without producing an MXQ package.
Definition frontend.py:923
None mblt_compile_with_callback(str model, str mblt_save_path, str target_device, 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)
Compile-to-mblt entry point with progress callbacks.
Definition frontend.py:1256
Auto-generated config module from config_schema.yaml.
Definition __init__.py:1