frontend.py Source File

frontend.py Source File#

Mobilint SDK qb Compiler: frontend.py Source File
Mobilint SDK qb Compiler v1.2
MCS002-EN
frontend.py
Go to the documentation of this file.
1
4
5import os
6import pathlib
7import warnings
8from collections.abc import Callable
9from typing import Any, List, Optional, Union
10
11import torch
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 (
16 CompileConfig,
17 CalibrationConfig,
18 BitConfig,
19 ResourceManagementConfig,
20 OptqConfig,
21 ModConfig,
22 LlmConfig,
23 EquivalentTransformationConfig,
24 SearchWeightScaleConfig,
25 SaveSampleConfig,
26 Uint8InputConfig,
27 PreprocessingConfig,
28)
29from qbcompiler.config_resolver import (
30 ConfigManager,
31 ParserOptions_V2,
32 QuantizeRequest_V2,
33 ResolvedQuantizeRequest_V2,
34 MbltCompileRequest_V2,
35 ResolvedMbltCompileRequest_V2,
36 UNSET as CONFIG_MANAGER_UNSET,
37 apply_compile_config_bindings,
38)
39from qbcompiler.logging import get_logger
40from qbcompiler.progress import emit_progress, progress_context
41
42logger = get_logger(__name__)
43
44_UNSET = object()
45"""Sentinel to distinguish 'not passed' from explicit defaults."""
46
47
48def _to_config_manager_unset_V2(value: object) -> object:
49 """Translate frontend-local ``_UNSET`` values to ConfigManager ``UNSET``."""
50 if value is _UNSET:
51 return CONFIG_MANAGER_UNSET
52 return value
53
54
55def _resolve_deprecated_kwargs(
56 *,
57 calibration_config,
58 optq_config,
59 mod_config,
60 equivalent_transformation_config,
61 search_weight_scale_config,
62 uint8_input_config,
63 preprocessing_config,
64 save_sample_config,
65 **kwargs,
66):
67 """Extract and resolve deprecated parameters from kwargs into modern equivalents.
68
69 Mutates kwargs by popping consumed deprecated keys.
70 Returns a tuple of resolved sub-config values.
71 """
72 quantization_config = kwargs.pop("quantization_config", None)
73 if quantization_config is not None and calibration_config is None:
74 warnings.warn(
75 "quantization_config is deprecated. Use calibration_config instead.",
76 DeprecationWarning,
77 stacklevel=3,
78 )
79 calibration_config = quantization_config
80
81 advanced_quantization_config = kwargs.pop("advanced_quantization_config", None)
82 if advanced_quantization_config is not None:
83 warnings.warn(
84 "advanced_quantization_config is deprecated. Use individual configs "
85 "(optq_config, mod_config, equivalent_transformation_config, search_weight_scale_config) instead.",
86 DeprecationWarning,
87 stacklevel=3,
88 )
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
93 if (
94 hasattr(advanced_quantization_config, "equivalent_transformation")
95 and equivalent_transformation_config is None
96 ):
97 equivalent_transformation_config = (
98 advanced_quantization_config.equivalent_transformation
99 )
100 if (
101 hasattr(advanced_quantization_config, "search_weight_scale")
102 and search_weight_scale_config is None
103 ):
104 search_weight_scale_config = (
105 advanced_quantization_config.search_weight_scale
106 )
107
108 input_process_config = kwargs.pop("input_process_config", None)
109 if input_process_config is not None:
110 warnings.warn(
111 "input_process_config is deprecated. Use uint8_input_config and preprocessing_config instead.",
112 DeprecationWarning,
113 stacklevel=3,
114 )
115 if hasattr(input_process_config, "uint8_input") and uint8_input_config is None:
116 uint8_input_config = input_process_config.uint8_input
117 if (
118 hasattr(input_process_config, "preprocessing")
119 and preprocessing_config is None
120 ):
121 preprocessing_config = input_process_config.preprocessing
122
123 save_sample = kwargs.pop("save_sample", None)
124 sample_dtype = kwargs.pop("sample_dtype", None)
125 if (
126 save_sample is not None or sample_dtype is not None
127 ) and save_sample_config is None:
128 warnings.warn(
129 "save_sample and sample_dtype are deprecated. Use save_sample_config instead.",
130 DeprecationWarning,
131 stacklevel=3,
132 )
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)
139
140 return (
141 calibration_config,
142 optq_config,
143 mod_config,
144 equivalent_transformation_config,
145 search_weight_scale_config,
146 uint8_input_config,
147 preprocessing_config,
148 save_sample_config,
149 )
150
151
152def _normalize_quantize_request_V2(
153 *,
154 model,
155 save_path: Union[str, List[str]] = _UNSET,
156 backend: str = "onnx",
157 target_device: Optional[str] = None,
158 feed_dict=None,
159 dynamic_axes=None,
160 in_dformats=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,
166 device=_UNSET,
167 inference_scheme=_UNSET,
168 use_random_calib=_UNSET,
169 cpu_offload=_UNSET,
170 optimize_option=_UNSET,
171 buffer_mode=_UNSET,
172 input_shape_dict=_UNSET,
173 force_npu_input_reposition=_UNSET,
174 force_npu_output_reposition=_UNSET,
175 image_channels=_UNSET,
176 split_blocks=_UNSET,
177 split_parts=_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,
191 **kwargs,
192) -> QuantizeRequest_V2:
193 """Build a canonical V2 quantize request without executing side effects."""
194 return QuantizeRequest_V2(
195 model=model,
196 save_path=_to_config_manager_unset_V2(save_path),
197 parser_options=ParserOptions_V2(
198 backend=backend,
199 target_device=target_device,
200 feed_dict=feed_dict,
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),
206 ),
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
219 ),
220 force_npu_output_reposition=_to_config_manager_unset_V2(
221 force_npu_output_reposition
222 ),
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,
239 )
240
241
242def _normalize_mblt_compile_request_V2(
243 *,
244 model: str | object,
245 mblt_save_path: str,
246 backend: str = "onnx",
247 target_device: Optional[str] = None,
248 device: object = _UNSET,
249 feed_dict=None,
250 dynamic_axes=None,
251 in_dformats=None,
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,
258 **kwargs,
259) -> MbltCompileRequest_V2:
260 """Build a canonical V2 compile-to-mblt request without side effects."""
261 return MbltCompileRequest_V2(
262 model=model,
263 mblt_save_path=mblt_save_path,
264 parser_options=ParserOptions_V2(
265 backend=backend,
266 target_device=target_device,
267 feed_dict=feed_dict,
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),
273 ),
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,
279 )
280
281
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)
285
286
287def _validate_mblt_for_mxq_compile_V2(model: str, cpu_offload: object) -> None:
288 """Validate an existing ``.mblt`` used as an ``mxq_compile`` input.
289
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:
293
294 * No weights, or a single subgraph carrying unsupported ops -> error (a
295 preview export is not a runnable artifact; regenerate with
296 ``mblt_compile()``).
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``).
301 """
302
303 def _read_mblt_graph_info(path: str):
304 """Return ``(has_weights, subgraphs)`` for the .mblt at *path*.
305
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.
311 """
312 from mblt.serialize import SerializeMeta as MbltSerializeMeta
313
314 if MbltSerializeMeta.read_header(path).is_legacy:
315 from qbcompiler.model_dict.serialize import SerializeMeta
316
317 header = SerializeMeta.get_header(path)
318 subgraphs = SerializeMeta.get_model_dict(path, header=header).subgraphs
319 else:
320 header = MbltSerializeMeta.read_header(path)
321 subgraphs = MbltSerializeMeta.get_model_dict(path).subgraphs
322 return header.num_buffers > 0, subgraphs
323
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)
327
328 # A file with no weights, or a single subgraph that carries unsupported
329 # ops, is a preview export rather than a runnable artifact.
330 not_runnable_msg = (
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."
335 )
336
337 if not has_weights:
338 raise ValueError(not_runnable_msg)
339
340 if num_subgraphs == 1:
341 sg = subgraphs[0]
342
343 # cpu_offload=True has nothing to offload with a single subgraph.
344 if effective_cpu_offload:
345 raise ValueError(
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 "
349 "to False."
350 )
351
352 # A single subgraph carrying unsupported ops is not NPU-runnable.
353 if sg.unsupported or any(op.unsupported for op in sg.operators):
354 raise ValueError(not_runnable_msg)
355 return
356
357 # More than one subgraph: the unsupported subgraphs can only execute when
358 # CPU offloading is enabled.
359 if not effective_cpu_offload:
360 raise ValueError(
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"
364 )
365
366
367def _execute_quantize_request_V2(request: ResolvedQuantizeRequest_V2) -> None:
368 """Execute a resolved V2 quantize request via the CompilerV2 pipeline.
369
370 Routing:
371
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"]``).
378 """
379 logger.debug("MXQ compile: CompilerV2 pipeline path")
380 from qbcompiler.compiler.compiler_v2 import (
381 CompilerV2,
382 MBLTCompileStage,
383 MxqCompileStage,
384 PipelineStage,
385 ResolvedPipeline,
386 )
387
388 stages: list[PipelineStage] = []
389 if not _is_existing_mblt_input_V2(request.model):
390 stages.append(
391 MBLTCompileStage(
392 model=request.model,
393 save_path="", # auto → ctx.tempdir/intermediate.mblt
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,
400 )
401 )
402 mxq_input = None # read from ctx.artifacts["mblt_path"]
403 else:
404 mxq_input = request.model
405
406 stages.append(
407 MxqCompileStage(
408 mblt_path=mxq_input,
409 compile_config=request.compile_config,
410 target_device=request.parser_options.target_device,
411 )
412 )
413
414 with CompilerV2(ResolvedPipeline(stages=tuple(stages))) as compiler:
415 compiler.run()
416 torch.cuda.empty_cache()
417
418
419def _execute_mblt_compile_request_V2(request: ResolvedMbltCompileRequest_V2) -> None:
420 """Execute a resolved V2 compile-to-mblt request via the CompilerV2 pipeline.
421
422 Imported lazily so the pipeline module is only loaded on first use.
423 """
424 from qbcompiler.compiler.compiler_v2 import (
425 CompilerV2,
426 MBLTCompileStage,
427 ResolvedPipeline,
428 )
429
430 stage = MBLTCompileStage(
431 model=request.model,
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,
438 )
439 with CompilerV2(ResolvedPipeline(stages=(stage,))) as compiler:
440 # progress_callback is None so ambient progress_context (installed
441 # by mblt_compile_with_callback_V2) keeps receiving stage events.
442 compiler.run()
443
444
445
450
451
452class Model_Dict(Compiler):
453 """
454 @brief Wrapper around the Mobilint compiler to support compilation and inference workflows.
455
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.
460 """
461
463 self,
464 model,
465 backend="onnx",
466 device="cpu",
467 feed_dict=None,
468 dynamic_axes=None,
469 in_dformats=None,
470 yolo_decode_include=False,
471 exclude_first_subgraph=False,
472 **kwargs,
473 ):
474 """
475 @brief Initialize the Mobilint compiler wrapper.
476
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.
486 """
487
488 super().__init__(
489 model=model,
490 backend=backend,
491 device=device,
492 feed_dict=feed_dict,
493 in_dformats=in_dformats,
494 dynamic_axes=dynamic_axes,
495 yolo_decode_include=yolo_decode_include,
496 exclude_first_subgraph=exclude_first_subgraph,
497 **kwargs,
498 )
499
501 self,
502 save_subgraph_type: int = 0,
503 output_subgraph_path="",
504 compile_config: CompileConfig = None,
505 **kwargs,
506 ):
507 """
508 @brief Compile the wrapped model into an MXQ artifact.
509
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.
515
516 """
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:
520 warnings.warn(
521 "save_sample and sample_dtype are deprecated. Use compile_config with saveSample instead.",
522 DeprecationWarning,
523 stacklevel=2,
524 )
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)
534
535 super().compile(
536 save_subgraph_type=save_subgraph_type,
537 output_subgraph_path=output_subgraph_path,
538 compile_config=compile_config,
539 **kwargs,
540 )
541
542
543def mxq_compile(
544 model,
545 target_device: str,
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,
550 backend="onnx",
551 # -- ModelDict params --
552 feed_dict=None,
553 dynamic_axes=None,
554 in_dformats=None,
555 yolo_decode_include=False,
556 exclude_first_subgraph=False,
557 # -- CompileConfig-overridable (_UNSET = defer to config) --
558 device=_UNSET,
559 inference_scheme=_UNSET,
560 use_random_calib=_UNSET,
561 cpu_offload=_UNSET,
562 optimize_option=_UNSET,
563 buffer_mode=_UNSET,
564 input_shape_dict=_UNSET,
565 force_npu_input_reposition=_UNSET,
566 force_npu_output_reposition=_UNSET,
567 image_channels=_UNSET,
568 split_blocks=_UNSET,
569 split_parts=_UNSET,
570 # -- Config objects --
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,
584 **kwargs,
585):
586 """
587 @brief Compile a model into a Mobilint eXeCUtable (MXQ) package for execution on Mobilint NPUs.
588
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.
592
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
599
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.
679 @return None.
680
681 @par Using configuration
682 There are three ways to configure quantization settings:
683
684 1. Load all settings from a JSON/YAML config file:
685 @code{.py}
686 from qbcompiler import mxq_compile
687
688 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
693 device="gpu",
694 )
695 @endcode
696
697 2. Pass individual sub-config objects:
698 @code{.py}
699 from qbcompiler import mxq_compile
700 from qbcompiler.configs import (
701 ResourceManagementConfig,
702 CalibrationConfig,
703 BitConfig,
704 OptqConfig,
705 ModConfig,
706 LlmConfig,
707 )
708
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)
715
716 mxq_compile(
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,
722 bit_config=bit_cfg,
723 optq_config=optq_cfg,
724 mod_config=mod_cfg,
725 llm_config=llm_cfg,
726 device="gpu",
727 )
728 @endcode
729
730 3. Automatically applied partial configuration overrides:
731 @code{.py}
732 from qbcompiler import mxq_compile
733
734 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
742 device="gpu",
743 )
744 @endcode
745 Please refer to the mxq_compile function and the quantization configuration section for the meaning of the quantization-related numeric values.
746
747
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
750 formats.
751
752 @code{.py}
753 from qbcompiler import mxq_compile
754 import numpy as np
755
756 example_input = {
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),
760 }
761
762 in_dformats = {
763 "input_node_name_1": "NCHW",
764 "input_node_name_2": "NCHW",
765 "input_node_name_3": "NCHW",
766 }
767
768 onnx_model_path = "path/to/your/model.onnx"
769 mxq_compile(
770 model=onnx_model_path,
771 target_device="aries-rb",
772 feed_dict=example_input,
773 in_dformats=in_dformats,
774 backend="onnx",
775 compile_config="path/to/config.json",
776 )
777 @endcode
778 """
779 target_device = validate_target_device(target_device)
780
781 if _is_existing_mblt_input_V2(model):
782 _validate_mblt_for_mxq_compile_V2(model, cpu_offload)
783
784 if backend == "onnx" or _is_existing_mblt_input_V2(model):
786 model=model,
787 calib_data_path=calib_data_path,
788 save_subgraph_type=save_subgraph_type,
789 output_subgraph_path=output_subgraph_path,
790 save_path=save_path,
791 backend=backend,
792 target_device=target_device,
793 feed_dict=feed_dict,
794 dynamic_axes=dynamic_axes,
795 in_dformats=in_dformats,
796 yolo_decode_include=yolo_decode_include,
797 exclude_first_subgraph=exclude_first_subgraph,
798 device=device,
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,
823 **kwargs,
824 )
825 return
826
827 # --- Handle deprecated kwargs ---
828 (
829 calibration_config,
830 optq_config,
831 mod_config,
832 equivalent_transformation_config,
833 search_weight_scale_config,
834 uint8_input_config,
835 preprocessing_config,
836 save_sample_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,
846 **kwargs,
847 )
848
849 # --- Step 1: Base CompileConfig ---
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)
858 else:
859 raise ValueError(
860 "compile_config must be a CompileConfig object or a path to JSON/YAML configuration file"
861 )
862
863 # --- Steps 2-4: Apply sub-config replacements, partial-kwarg
864 # overrides, and external named-arg overrides through the unified
865 # bindings registry shared with ConfigManager.resolve_mxq_compile.
866 # See docs/config-manager-partial-kwargs-bugs.md for the rationale.
867 request_values = {
868 "model": model,
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
880 ),
881 "force_npu_output_reposition": _to_config_manager_unset_V2(
882 force_npu_output_reposition
883 ),
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,
898 }
899 compile_cfg, kwargs = apply_compile_config_bindings(
900 compile_cfg, kwargs=kwargs, request_values=request_values
901 )
902
903 # Resolve values from final config for downstream use
904 resolved_device = compile_cfg.device
905
906 if isinstance(model, str) and model.endswith(".mblt") and os.path.isfile(model):
907 _quantization_task(
908 model, compile_config=compile_cfg, target_device=target_device
909 )
910 else:
911 model_dict = Model_Dict(
912 model=model,
913 backend=backend,
914 target_device=target_device,
915 device=resolved_device,
916 feed_dict=feed_dict,
917 in_dformats=in_dformats,
918 dynamic_axes=dynamic_axes,
919 yolo_decode_include=yolo_decode_include,
920 exclude_first_subgraph=exclude_first_subgraph,
921 **kwargs,
922 )
923 model_dict.compile(
924 save_subgraph_type=save_subgraph_type,
925 output_subgraph_path=output_subgraph_path,
926 compile_config=compile_cfg,
927 )
928 torch.cuda.empty_cache()
929 del model_dict
930
931
932def mblt_compile(
933 model: str | Any,
934 mblt_save_path: str,
935 target_device: str,
936 backend="onnx",
937 device="cpu",
938 feed_dict=None,
939 dynamic_axes=None,
940 in_dformats=None,
941 yolo_decode_include=False,
942 cpu_offload=False,
943 exclude_first_subgraph=False,
944 **kwargs,
945):
946 """
947 @brief Export a model to the Mobilint .mblt format without producing an MXQ package.
948
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
952 "onnx".
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.
961 @return None.
962 """
963 target_device = validate_target_device(target_device)
964 if backend == "onnx":
966 model=model,
967 mblt_save_path=mblt_save_path,
968 backend=backend,
969 target_device=target_device,
970 device=device,
971 feed_dict=feed_dict,
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,
977 **kwargs,
978 )
979 return
980
981 model_dict = Model_Dict(
982 model=model,
983 backend=backend,
984 target_device=target_device,
985 device=device,
986 feed_dict=feed_dict,
987 dynamic_axes=dynamic_axes,
988 in_dformats=in_dformats,
989 yolo_decode_include=yolo_decode_include,
990 exclude_first_subgraph=exclude_first_subgraph,
991 **kwargs,
992 )
993
994 model_dict.mblt_compile(
995 model,
996 mblt_save_path=mblt_save_path,
997 backend=backend,
998 cpu_offload=cpu_offload,
999 **kwargs,
1000 )
1001
1002
1003def mxq_compile_V2(
1004 model,
1005 target_device: str,
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,
1010 backend="onnx",
1011 feed_dict=None,
1012 dynamic_axes=None,
1013 in_dformats=None,
1014 yolo_decode_include=False,
1015 exclude_first_subgraph=False,
1016 device=_UNSET,
1017 inference_scheme=_UNSET,
1018 use_random_calib=_UNSET,
1019 cpu_offload=_UNSET,
1020 optimize_option=_UNSET,
1021 buffer_mode=_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,
1027 split_parts=_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,
1041 **kwargs,
1042) -> None:
1043 """V2 compile/quantize entry point backed only by ConfigManager resolution."""
1044 request_V2 = _normalize_quantize_request_V2(
1045 model=model,
1046 save_path=save_path,
1047 backend=backend,
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,
1057 device=device,
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,
1082 **kwargs,
1083 )
1084 resolved_request_V2 = ConfigManager.resolve_quantize_request_V2(request_V2)
1085 _execute_quantize_request_V2(resolved_request_V2)
1086
1087
1088def mblt_compile_V2(
1089 model: str | object,
1090 target_device: str,
1091 mblt_save_path: str,
1092 backend="onnx",
1093 device: object = _UNSET,
1094 feed_dict=None,
1095 dynamic_axes=None,
1096 in_dformats=None,
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,
1103 **kwargs,
1104) -> None:
1105 """V2 compile-to-mblt entry point backed only by ConfigManager resolution.
1106
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.
1115 """
1116 request_V2 = _normalize_mblt_compile_request_V2(
1117 model=model,
1118 mblt_save_path=mblt_save_path,
1119 backend=backend,
1120 target_device=target_device,
1121 device=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,
1131 **kwargs,
1132 )
1133 resolved_request_V2 = ConfigManager.resolve_mblt_compile_request_V2(request_V2)
1134 _execute_mblt_compile_request_V2(resolved_request_V2)
1135
1136
1138 model: str,
1139 target_device: str,
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,
1147 *,
1148 progress_callback: Callable[[int, str], None],
1149) -> None:
1150 """V2 compile-to-mblt entry point with progress callbacks.
1151
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.
1155 """
1156 call_kwargs: dict[str, Any] = {
1157 "model": model,
1158 "mblt_save_path": mblt_save_path,
1159 "backend": backend,
1160 "target_device": target_device,
1161 }
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
1172
1173 with progress_context(progress_callback):
1174 emit_progress(0, "Initializing compiler")
1175 mblt_compile_V2(**call_kwargs)
1176 emit_progress(100, "Complete")
1177
1178
1180 model: str,
1181 target_device: str,
1182 save_path: str,
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,
1189 *,
1190 progress_callback: Callable[[int, str], None],
1191) -> None:
1192 """V2 compile/quantize entry point with progress callbacks."""
1193 call_kwargs: dict[str, object] = {
1194 "model": model,
1195 "save_path": save_path,
1196 "backend": backend,
1197 }
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
1210
1211 with progress_context(progress_callback):
1212 emit_progress(0, "Initializing compiler")
1213 mxq_compile_V2(**call_kwargs)
1214 emit_progress(100, "Complete")
1215
1216
1217
1219
1220
1221def run_mblt_model(
1222 path_to_mblt: str,
1223 save_all_outputs: bool = True,
1224 inference_output_path: Optional[str] = None,
1225 target_subgraph: Optional[int] = None,
1226):
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
1230
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."
1235 )
1236 if target_subgraph:
1237 raise NotImplementedError(
1238 f"target_subgraph={target_subgraph} is not supported yet."
1239 )
1240 import numpy
1241
1242 if not inference_output_path:
1243 inference_output_path = str(pathlib.Path(path_to_mblt).with_suffix(".infer"))
1244
1245 vd = ValueDict()
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)))
1252
1253 model_inference = ModelInference(
1254 model_dict=md,
1255 weight_dict=wd,
1256 value_dict=vd,
1257 save_all_outputs=save_all_outputs,
1258 inference_all_outputs_write_path=inference_output_path,
1259 )
1260
1261 model_inference.run_inference(use_value_dict_data_for_next_input=False)
Wrapper around the Mobilint compiler to support compilation and inference workflows.
Definition frontend.py:452
__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:473
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:506
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.
Definition frontend.py:1191
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.
Definition frontend.py:945
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.
Definition frontend.py:1104
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.
Definition frontend.py:1149
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.
Definition frontend.py:585
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.
Definition frontend.py:1042