models.py Source File

models.py Source File#

Mobilint SDK qb Compiler: models.py Source File
Mobilint SDK qb Compiler v1.1
MCS002-KR
models.py
1"""Auto-generated Pydantic models from config_schema.yaml."""
2
3from __future__ import annotations
4from typing import Any, Dict, List, Optional, Union
5from pydantic import BaseModel, Field, ConfigDict
6import yaml
7import json
8from pathlib import Path
9
10SCHEMA_VERSION = "1.0.0"
11
12
13class Uint8InputConfig(BaseModel):
14 """
15 @brief Configuration for uint8 input handling
16
17 @details Defines whether inputs should be treated as uint8 and which specific inputs to apply this to.
18
19 @param apply bool. If true, treat specified inputs as uint8
20 @param inputs List[str]. List of input names to treat as uint8. If empty and apply is true, applies to all inputs
21 @param division_factor float. Division factor for uint8 to float conversion (e.g., 255.0 for [0,1], 127.5 for [0,2])
22 """
23
24 model_config = ConfigDict(
25 populate_by_name=True,
26 extra="forbid",
27 )
28
29 apply: bool = Field(
30 default=False, description="If true, treat specified inputs as uint8"
31 )
32 inputs: List[str] = Field(
33 default=[],
34 description="List of input names to treat as uint8. If empty and apply is true, applies to all inputs",
35 )
36 division_factor: float = Field(
37 default=255.0,
38 alias="divisionFactor",
39 description="Division factor for uint8 to float conversion (e.g., 255.0 for [0,1], 127.5 for [0,2])",
40 )
41
42 def with_updates(self, **kwargs) -> "Uint8InputConfig":
43 """Return a copy with updated fields."""
44 return self.model_copy(update=kwargs)
45
46
47class PreprocessingConfig(BaseModel):
48 """
49 @brief Configuration for input preprocessing pipeline
50
51 @details Defines preprocessing operations to be applied to model inputs,
52 including operations like resize, normalize, color conversion, etc.
53
54 @param apply bool. If true, apply preprocessing pipeline
55 @param auto_convert_format bool. If true, automatically convert input format
56 @param pipeline List[Dict[str, Any]]. List of preprocessing operations to apply globally
57 @param input_configs Dict[str, Any]. Per-input preprocessing configurations. Keys are input names
58 """
59
60 model_config = ConfigDict(
61 populate_by_name=True,
62 extra="forbid",
63 )
64
65 apply: bool = Field(
66 default=False, description="If true, apply preprocessing pipeline"
67 )
68 auto_convert_format: bool = Field(
69 default=False,
70 alias="autoConvertFormat",
71 description="If true, automatically convert input format",
72 )
73 pipeline: Any = Field(
74 default=[], description="List of preprocessing operations to apply globally"
75 )
76 input_configs: Any = Field(
77 default={},
78 alias="inputConfigs",
79 description="Per-input preprocessing configurations. Keys are input names",
80 )
81
82 def with_updates(self, **kwargs) -> "PreprocessingConfig":
83 """Return a copy with updated fields."""
84 return self.model_copy(update=kwargs)
85
86
87class ResourceManagementConfig(BaseModel):
88 """
89 @brief Configuration for resource management during model compilation
90
91 @details Controls GPU and memory management settings during the compilation process.
92
93 @param weight_dtype str. Weight data type for calibration (e.g., 'float32', 'float16')
94 @param use_gpu_only_for_calibration bool. If True, use GPU only during the calibration phase
95 @param weight_memory WeightMemory. Weight memory management configuration
96 """
97
98 model_config = ConfigDict(
99 populate_by_name=True,
100 extra="forbid",
101 )
102
103 weight_dtype: str = Field(
104 default="float32",
105 alias="weightDtype",
106 description="Weight data type for calibration (e.g., 'float32', 'float16')",
107 )
108 use_gpu_only_for_calibration: bool = Field(
109 default=True,
110 alias="useGPUOnlyForCalibration",
111 description="If True, use GPU only during the calibration phase",
112 )
113
114 class WeightMemory(BaseModel):
115 """
116 @brief Weight memory management configuration
117
118 @param method int. Weight memory management method index:<br>
119 0: DeleteFloat - Delete float weights after quantization.<br>
120 1: SaveFloat - Save float weights to disk.<br>
121 2: MoveFloat - Move float weights to CPU.<br>
122 3: KeepFloat - Keep float weights in memory.<br>
123 4: KeepAll - Keep all weights in memory.<br>
124 """
125
126 method_list: List[str] = Field(
127 default=["DeleteFloat", "SaveFloat", "MoveFloat", "KeepFloat", "KeepAll"],
128 alias="methodList",
129 )
130 method: int = Field(default=0, alias="method")
131
132 weight_memory: WeightMemory = Field(
133 default_factory=WeightMemory, alias="weightMemory"
134 )
135
136 def with_updates(self, **kwargs) -> "ResourceManagementConfig":
137 """Return a copy with updated fields."""
138 return self.model_copy(update=kwargs)
139
140
141class CalibrationConfig(BaseModel):
142 """
143 @brief Configuration for calibration during quantization
144
145 @details Defines calibration and quantization parameterization used to derive activation/weight scales
146 and related statistics during quantized compilation.
147
148 @param method int. Calibration method index:<br>
149 0: WChALayer - Weight per-channel, Activation per-layer.<br>
150 1: WChAMulti - Weight per-channel, Activation multi-layer.<br>
151 2: WChALayerZeropoint - Weight per-channel, Activation per-layer with zeropoint.<br>
152 3: WChAMultiZeropoint - Weight per-channel, Activation multi-layer with zeropoint.<br>
153 @param output int. Output quantization type index:<br>
154 0: Layer - Per-layer quantization.<br>
155 1: Ch - Per-channel quantization.<br>
156 2: Sigmoid - Sigmoid-based quantization.<br>
157 @param mode int. Quantization mode index:<br>
158 0: Max - Maximum value calibration.<br>
159 1: MaxPercentile - Maximum percentile calibration.<br>
160 2: Histogram - Histogram-based calibration.<br>
161 @param clustering_methods int. LUT clustering method:<br>
162 0: Scale - Scale-based 1D clustering.<br>
163 1: Scale2D - Scale-based 2D clustering.<br>
164 2: ReparameterizedL2 - Reparameterized L2 distance clustering.<br>
165 3: SubgraphIoU - Subgraph intersection-over-union clustering.<br>
166 4: DomainAwareL2 - Domain-aware L2 distance on common absolute grid.<br>
167 5: OverlapWeightedL2 - L2 weighted by domain overlap (IoU).<br>
168 6: Fast - Minimal search space for fast LUT optimization.<br>
169 @param act_scale_min float. Minimum allowed activation scale (lower bound clamp)
170 @param act16_scale_min float. Minimum 16-bit activation scale (actScaleMin / 256)
171 @param weight_scale_min float. Minimum allowed weight scale (lower bound clamp)
172 @param weight16_scale_min float. Minimum 16-bit weight scale (weightScaleMin / 256)
173 @param min_clip_ratio float. Minimum clip ratio constraint applied during calibration
174 @param max_percentile MaxPercentile. MaxPercentile mode configuration
175 @param fast_dist FastDist. Fast distribution calibration configuration
176 @param histogram Histogram. Histogram-based calibration configuration
177 @param layer_overrides LayerOverrides. Layer-specific override settings for calibration
178 @param statistics Statistics. Statistics save/load configuration with percentile selection
179 """
180
181 model_config = ConfigDict(
182 populate_by_name=True,
183 extra="forbid",
184 )
185
186 method_list: List[str] = Field(
187 default=["WChALayer", "WChAMulti", "WChALayerZeropoint", "WChAMultiZeropoint"],
188 alias="methodList",
189 )
190 method: int = Field(default=1, alias="method")
191 output_list: List[str] = Field(
192 default=["Layer", "Ch", "Sigmoid"], alias="outputList"
193 )
194 output: int = Field(default=0, alias="output")
195 mode_list: List[str] = Field(
196 default=["Max", "MaxPercentile", "Histogram"], alias="modeList"
197 )
198 mode: int = Field(default=1, alias="mode")
199 clustering_methods_list: List[str] = Field(
200 default=[
201 "Scale",
202 "Scale2D",
203 "ReparameterizedL2",
204 "SubgraphIoU",
205 "DomainAwareL2",
206 "OverlapWeightedL2",
207 "Fast",
208 ],
209 alias="clusteringMethodsList",
210 )
211 clustering_methods: List[int] = Field(default=[0], alias="clusteringMethods")
212
213 act_scale_min: float = Field(
214 default=0.0005,
215 alias="actScaleMin",
216 description="Minimum allowed activation scale (lower bound clamp)",
217 ge=0,
218 le=1,
219 )
220 act16_scale_min: float = Field(
221 default=1.953125e-06,
222 alias="act16ScaleMin",
223 description="Minimum 16-bit activation scale (actScaleMin / 256)",
224 )
225 weight_scale_min: float = Field(
226 default=1e-06,
227 alias="weightScaleMin",
228 description="Minimum allowed weight scale (lower bound clamp)",
229 ge=0,
230 le=1,
231 )
232 weight16_scale_min: float = Field(
233 default=3.90625e-09,
234 alias="weight16ScaleMin",
235 description="Minimum 16-bit weight scale (weightScaleMin / 256)",
236 )
237 min_clip_ratio: float = Field(
238 default=-1,
239 alias="minClipRatio",
240 description="Minimum clip ratio constraint applied during calibration",
241 ge=-1,
242 le=1,
243 )
244
245 class MaxPercentile(BaseModel):
246 model_config = ConfigDict(populate_by_name=True)
247
248 """
249 @brief MaxPercentile mode configuration
250
251 @param percentile float. Percentile value for maxPercentile mode
252 @param topk_ratio float. Top-k ratio used in maxPercentile mode
253 @param max_each int. Maximum number of samples processed per iteration
254 @param max_total int. Total maximum number of samples
255 @param per_ch_divisor int. Divisor for per-channel buffer capacity (bufferCap = max(maxTotal / perChDivisor, maxEach))
256 """
257 percentile: float = Field(
258 default=0.9999, description="Percentile value for maxPercentile mode"
259 )
260 topk_ratio: float = Field(
261 default=0.01,
262 alias="topKRatio",
263 description="Top-k ratio used in maxPercentile mode",
264 )
265 max_each: int = Field(
266 default=128,
267 alias="maxEach",
268 description="Maximum number of samples processed per iteration",
269 )
270 max_total: int = Field(
271 default=65536,
272 alias="maxTotal",
273 description="Total maximum number of samples",
274 )
275 per_ch_divisor: int = Field(
276 default=16,
277 alias="perChDivisor",
278 description="Divisor for per-channel buffer capacity (bufferCap = max(maxTotal / perChDivisor, maxEach))",
279 ge=1,
280 )
281
282 max_percentile: MaxPercentile = Field(
283 default_factory=MaxPercentile, alias="maxPercentile"
284 )
285
286 class FastDist(BaseModel):
287 model_config = ConfigDict(populate_by_name=True)
288
289 """
290 @brief Fast distribution calibration configuration
291
292 @param size_cali int.
293 @param kernel_size int.
294 @param stack_size int.
295 """
296 size_cali: int = Field(default=100, alias="sizeCali")
297 kernel_size: int = Field(default=9, alias="kernelSize")
298 stack_size: int = Field(default=32768, alias="stackSize")
299
300 fast_dist: FastDist = Field(default_factory=FastDist, alias="fastDist")
301
302 class Histogram(BaseModel):
303 model_config = ConfigDict(populate_by_name=True)
304
305 """
306 @brief Histogram-based calibration configuration
307
308 @param search_type int. Search type for histogram calibration:<br>
309 0: Percentile.<br>
310 1: MSE.<br>
311 2: KL.<br>
312 @param percentile float. Percentile value for histogram calibration
313 @param use_gpu bool. Use GPU for histogram computation
314 @param num_bins int. Number of bins for histogram
315 @param num_samples int. Number of samples for histogram calibration
316 @param buffer_size int. Buffer size for histogram computation (-1 for auto)
317 @param min_bin_width float. Minimum bin width for histogram
318 @param search_percentile_min float. Minimum search percentile
319 @param search_percentile_max float. Maximum search percentile
320 @param num_search int. Number of search iterations
321 """
322 search_type_list: List[str] = Field(
323 default=["Percentile", "MSE", "KL"], alias="searchTypeList"
324 )
325 search_type: int = Field(default=0, alias="searchType")
326 percentile: float = Field(
327 default=0.9999, description="Percentile value for histogram calibration"
328 )
329 use_gpu: bool = Field(
330 default=True,
331 alias="useGPU",
332 description="Use GPU for histogram computation",
333 )
334 num_bins: int = Field(
335 default=256, alias="numBins", description="Number of bins for histogram"
336 )
337 num_samples: int = Field(
338 default=128,
339 alias="numSamples",
340 description="Number of samples for histogram calibration",
341 )
342 buffer_size: int = Field(
343 default=-1,
344 alias="bufferSize",
345 description="Buffer size for histogram computation (-1 for auto)",
346 )
347 min_bin_width: float = Field(
348 default=1e-06,
349 alias="minBinWidth",
350 description="Minimum bin width for histogram",
351 )
352 search_percentile_min: float = Field(
353 default=0.9999,
354 alias="searchPercentileMin",
355 description="Minimum search percentile",
356 )
357 search_percentile_max: float = Field(
358 default=1.0,
359 alias="searchPercentileMax",
360 description="Maximum search percentile",
361 )
362 num_search: int = Field(
363 default=128, alias="numSearch", description="Number of search iterations"
364 )
365
366 histogram: Histogram = Field(default_factory=Histogram, alias="histogram")
367
368 class LayerOverrides(BaseModel):
369 model_config = ConfigDict(populate_by_name=True)
370
371 """
372 @brief Layer-specific override settings for calibration
373
374 @param act_scale_min dict. Per-layer activation scale minimum overrides. Keys are actScaleMin values (e.g. '0.0005'), values are lists of layer names to apply that override. (e.g. {'0.0005' : ['layer1', 'layer2']})
375 """
376 act_scale_min: Any = Field(
377 default={},
378 alias="actScaleMin",
379 description="Per-layer activation scale minimum overrides. Keys are actScaleMin values (e.g. '0.0005'), values are lists of layer names to apply that override. (e.g. {'0.0005' : ['layer1', 'layer2']})",
380 )
381
382 layer_overrides: LayerOverrides = Field(
383 default_factory=LayerOverrides, alias="layerOverrides"
384 )
385
386 class Statistics(BaseModel):
387 model_config = ConfigDict(populate_by_name=True)
388
389 """
390 @brief Statistics save/load configuration with percentile selection
391
392 @param apply bool. Enable statistics save/load
393 @param save_path str. Path to save statistics. If empty, not saved
394 @param load_path str. Path to load statistics. If empty, not loaded
395 @param percentiles List[float]. List of percentile candidates
396 @param percentile_index int. Index into percentiles list to select active percentile
397 """
398 apply: bool = Field(default=False, description="Enable statistics save/load")
399 save_path: str = Field(
400 default="",
401 alias="savePath",
402 description="Path to save statistics. If empty, not saved",
403 )
404 load_path: str = Field(
405 default="",
406 alias="loadPath",
407 description="Path to load statistics. If empty, not loaded",
408 )
409 percentiles: List[float] = Field(
410 default=[0.9999, 0.999, 0.99, 0.9],
411 description="List of percentile candidates",
412 )
413 percentile_index: int = Field(
414 default=0,
415 alias="percentileIndex",
416 description="Index into percentiles list to select active percentile",
417 )
418
419 statistics: Statistics = Field(default_factory=Statistics, alias="statistics")
420
421 def with_updates(self, **kwargs) -> "CalibrationConfig":
422 """Return a copy with updated fields."""
423 return self.model_copy(update=kwargs)
424
425
426class BitConfig(BaseModel):
427 """
428 @brief Configuration for bit precision
429
430 @details Defines bit-width parameterization for activations and weights used in
431 mixed-precision quantization (e.g., attention and FFN components).
432
433 @param transformer Transformer. Transformer-specific bit-width configuration
434 @param save_info SaveInfo. Bit allocation save/load configuration
435 @param layer_overrides LayerOverrides. Layer-specific bit-width override settings
436 """
437
438 model_config = ConfigDict(
439 populate_by_name=True,
440 extra="forbid",
441 )
442
443 class Transformer(BaseModel):
444 model_config = ConfigDict(populate_by_name=True)
445
446 """
447 @brief Transformer-specific bit-width configuration
448
449 @param activation Activation. Activation bit-widths for transformer components
450 @param weight Weight. Weight bit-widths for transformer components
451 @param mixed_precision MixedPrecision. Mixed precision configuration
452 """
453
454 class Activation(BaseModel):
455 """
456 @brief Activation bit-widths for transformer components
457
458 @param query int. Query activation bit-width
459 @param key int. Key activation bit-width
460 @param value int. Value activation bit-width
461 @param output int. Output activation bit-width
462 @param ffn int. FFN activation bit-width
463 @param head int. Head activation bit-width
464 """
465
466 query: int = Field(default=8, description="Query activation bit-width")
467 key: int = Field(default=8, description="Key activation bit-width")
468 value: int = Field(default=8, description="Value activation bit-width")
469 output: int = Field(default=16, description="Output activation bit-width")
470 ffn: int = Field(default=16, description="FFN activation bit-width")
471 head: int = Field(default=8, description="Head activation bit-width")
472
473 activation: Activation = Field(default_factory=Activation, alias="activation")
474
475 class Weight(BaseModel):
476 """
477 @brief Weight bit-widths for transformer components
478
479 @param query int. Query weight bit-width
480 @param key int. Key weight bit-width
481 @param value int. Value weight bit-width
482 @param output int. Output weight bit-width
483 @param ffn int. FFN weight bit-width
484 @param head int. Head weight bit-width
485 """
486
487 query: int = Field(default=8, description="Query weight bit-width")
488 key: int = Field(default=8, description="Key weight bit-width")
489 value: int = Field(default=8, description="Value weight bit-width")
490 output: int = Field(default=8, description="Output weight bit-width")
491 ffn: int = Field(default=8, description="FFN weight bit-width")
492 head: int = Field(default=8, description="Head weight bit-width")
493
494 weight: Weight = Field(default_factory=Weight, alias="weight")
495
496 class MixedPrecision(BaseModel):
497 model_config = ConfigDict(populate_by_name=True)
498
499 """
500 @brief Mixed precision configuration
501
502 @param apply bool. If true, apply mixed-precision according to the specified bit-widths
503 @param type_wise bool. Apply type-wise mixed precision
504 @param prune float. Pruning ratio
505 @param bit_2 float. Ratio of 2-bit quantization
506 @param bit_4 float. Ratio of 4-bit quantization
507 @param bit_8 float. Ratio of 8-bit quantization
508 @param importance_threshold_low float. Low importance threshold
509 @param importance_threshold_high float. High importance threshold
510 """
511 apply: bool = Field(
512 default=False,
513 description="If true, apply mixed-precision according to the specified bit-widths",
514 )
515 type_wise: bool = Field(
516 default=True,
517 alias="typeWise",
518 description="Apply type-wise mixed precision",
519 )
520 prune: float = Field(default=0, description="Pruning ratio")
521 bit_2: float = Field(
522 default=0, alias="bit2", description="Ratio of 2-bit quantization"
523 )
524 bit_4: float = Field(
525 default=0, alias="bit4", description="Ratio of 4-bit quantization"
526 )
527 bit_8: float = Field(
528 default=1, alias="bit8", description="Ratio of 8-bit quantization"
529 )
530 importance_threshold_low: float = Field(
531 default=-1,
532 alias="importanceThreshold_low",
533 description="Low importance threshold",
534 )
535 importance_threshold_high: float = Field(
536 default=-1,
537 alias="importanceThreshold_high",
538 description="High importance threshold",
539 )
540
541 mixed_precision: MixedPrecision = Field(
542 default_factory=MixedPrecision, alias="mixedPrecision"
543 )
544
545 transformer: Transformer = Field(default_factory=Transformer, alias="transformer")
546
547 class SaveInfo(BaseModel):
548 model_config = ConfigDict(populate_by_name=True)
549
550 """
551 @brief Bit allocation save/load configuration
552
553 @param save_path str. Path to save the bit allocation. If empty, not saved
554 @param load_path str. Path to load the bit allocation. If empty, not loaded
555 """
556 save_path: str = Field(
557 default="",
558 alias="savePath",
559 description="Path to save the bit allocation. If empty, not saved",
560 )
561 load_path: str = Field(
562 default="",
563 alias="loadPath",
564 description="Path to load the bit allocation. If empty, not loaded",
565 )
566
567 save_info: SaveInfo = Field(default_factory=SaveInfo, alias="saveInfo")
568
569 class LayerOverrides(BaseModel):
570 model_config = ConfigDict(populate_by_name=True)
571
572 """
573 @brief Layer-specific bit-width override settings
574
575 @param activation_16bits list[string]. Layer names to force 16-bit activations
576 @param weight_16bits list[string]. Layer names to force 16-bit weights
577 """
578 activation_16bits: List[str] = Field(
579 default=[],
580 alias="activation16Bits",
581 description="Layer names to force 16-bit activations",
582 )
583 weight_16bits: List[str] = Field(
584 default=[],
585 alias="weight16Bits",
586 description="Layer names to force 16-bit weights",
587 )
588
589 layer_overrides: LayerOverrides = Field(
590 default_factory=LayerOverrides, alias="layerOverrides"
591 )
592
593 def with_updates(self, **kwargs) -> "BitConfig":
594 """Return a copy with updated fields."""
595 return self.model_copy(update=kwargs)
596
597
598class OptqConfig(BaseModel):
599 """
600 @brief Configuration for OPTQ algorithm
601
602 @details Defines parameters controlling whether and how OPTQ is applied during quantization,
603 including layer-level inclusion/exclusion lists.
604
605 @param apply bool. If true, apply OPTQ
606 @param attributes Attributes. OPTQ algorithm attributes
607 """
608
609 model_config = ConfigDict(
610 populate_by_name=True,
611 extra="forbid",
612 )
613
614 apply: bool = Field(default=False, description="If true, apply OPTQ")
615
616 class Attributes(BaseModel):
617 model_config = ConfigDict(populate_by_name=True)
618
619 """
620 @brief OPTQ algorithm attributes
621
622 @param act_order bool. If true, use activation order
623 @param block_size int. Block size used for OPTQ
624 @param perc_damp float. Percentage dampening factor
625 @param apply_layers List[str]. Layer names to apply OPTQ. If empty, applies to all eligible layers
626 @param exclude_layers List[str]. Layer names to exclude from OPTQ
627 """
628 act_order: bool = Field(
629 default=True, alias="actOrder", description="If true, use activation order"
630 )
631 block_size: int = Field(
632 default=128, alias="blockSize", description="Block size used for OPTQ"
633 )
634 perc_damp: float = Field(
635 default=0.01, alias="percDamp", description="Percentage dampening factor"
636 )
637 apply_layers: List[str] = Field(
638 default=[],
639 alias="applyLayers",
640 description="Layer names to apply OPTQ. If empty, applies to all eligible layers",
641 )
642 exclude_layers: List[str] = Field(
643 default=[],
644 alias="excludeLayers",
645 description="Layer names to exclude from OPTQ",
646 )
647
648 attributes: Attributes = Field(default_factory=Attributes, alias="attributes")
649
650 def with_updates(self, **kwargs) -> "OptqConfig":
651 """Return a copy with updated fields."""
652 return self.model_copy(update=kwargs)
653
654
655class ModConfig(BaseModel):
656 """
657 @brief Configuration for Minimum Output Difference algorithm
658
659 @details Defines parameters controlling whether and how MOD is applied during quantization,
660 including layer-level inclusion/exclusion lists.
661
662 @param apply bool. If true, apply MOD
663 @param attributes Attributes. MOD algorithm attributes
664 """
665
666 model_config = ConfigDict(
667 populate_by_name=True,
668 extra="forbid",
669 )
670
671 apply: bool = Field(default=False, description="If true, apply MOD")
672
673 class Attributes(BaseModel):
674 model_config = ConfigDict(populate_by_name=True)
675
676 """
677 @brief MOD algorithm attributes
678
679 @param epochs int. Number of training epochs
680 @param warmup_epochs int. Number of warmup epochs
681 @param lr_min_ratio float. Minimum learning rate ratio
682 @param save_dir str. Directory to save MOD results
683 @param seed int. Random seed for MOD
684 @param apply_layers List[str]. Layer names to apply MOD. If empty, applies to all eligible layers
685 @param exclude_layers List[str]. Layer names to exclude from MOD
686 @param mod_after_layer_name str. Apply MOD after this layer
687 @param anchors List. Anchor configurations for detection models. Nested list of anchor box sizes for detection models. Structure: List[List[List[int]]] where outer list is per detection head (e.g. small/medium/large), middle list is anchors per head, inner list is [width, height]. Example: [[[12,16],[19,36],[40,28]], [[36,75],[76,55],[72,146]], [[142,110],[192,243],[459,401]]]
688 @param use_xyxy bool. Use XYXY format for bounding boxes
689 @param learning_rates LearningRates. Learning rate configuration for MOD
690 @param training Training. MOD training configuration
691 @param loss Loss. MOD loss configuration
692 @param post_processing PostProcessing. Post-processing configuration for detection models
693 """
694 epochs: int = Field(default=4, description="Number of training epochs")
695 warmup_epochs: int = Field(
696 default=1, alias="warmupEpochs", description="Number of warmup epochs"
697 )
698 lr_min_ratio: float = Field(
699 default=0.0001,
700 alias="lrMinRatio",
701 description="Minimum learning rate ratio",
702 )
703 save_dir: str = Field(
704 default="", alias="saveDir", description="Directory to save MOD results"
705 )
706 seed: int = Field(default=0, description="Random seed for MOD")
707 apply_layers: List[str] = Field(
708 default=[],
709 alias="applyLayers",
710 description="Layer names to apply MOD. If empty, applies to all eligible layers",
711 )
712 exclude_layers: List[str] = Field(
713 default=[],
714 alias="excludeLayers",
715 description="Layer names to exclude from MOD",
716 )
717 mod_after_layer_name: str = Field(
718 default="",
719 alias="modAfterLayerName",
720 description="Apply MOD after this layer",
721 )
722 anchors: Any = Field(
723 default=[],
724 description="Anchor configurations for detection models. Nested list of anchor box sizes for detection models. Structure: List[List[List[int]]] where outer list is per detection head (e.g. small/medium/large), middle list is anchors per head, inner list is [width, height]. Example: [[[12,16],[19,36],[40,28]], [[36,75],[76,55],[72,146]], [[142,110],[192,243],[459,401]]]",
725 )
726 use_xyxy: bool = Field(
727 default=False,
728 alias="useXYXY",
729 description="Use XYXY format for bounding boxes",
730 )
731
732 class LearningRates(BaseModel):
733 model_config = ConfigDict(populate_by_name=True)
734
735 """
736 @brief Learning rate configuration for MOD
737
738 @param act_scale float. Learning rate for activation scale
739 @param zeropoint float. Learning rate for zeropoint
740 @param weight_scale float. Learning rate for weight scale
741 @param weight float. Learning rate for weight
742 @param bias float. Learning rate for bias
743 """
744 act_scale: float = Field(
745 default=0.0,
746 alias="actScale",
747 description="Learning rate for activation scale",
748 )
749 zeropoint: float = Field(
750 default=0.0, description="Learning rate for zeropoint"
751 )
752 weight_scale: float = Field(
753 default=0.0,
754 alias="weightScale",
755 description="Learning rate for weight scale",
756 )
757 weight: float = Field(default=4e-06, description="Learning rate for weight")
758 bias: float = Field(default=4e-06, description="Learning rate for bias")
759
760 learning_rates: LearningRates = Field(
761 default_factory=LearningRates, alias="learningRates"
762 )
763
764 class Training(BaseModel):
765 model_config = ConfigDict(populate_by_name=True)
766
767 """
768 @brief MOD training configuration
769
770 @param batch_size int. Batch size for MOD training
771 @param q_drop float. Quantization drop probability
772 @param quantize_weight bool. Whether to quantize weights
773 @param weight_scale_init str. Weight scale initialization method
774 @param downresol_mode str. Downresolution mode
775 @param scheduler_type str. LR scheduler type
776 """
777 batch_size: int = Field(
778 default=1, alias="batchSize", description="Batch size for MOD training"
779 )
780 q_drop: float = Field(
781 default=0.0, alias="qDrop", description="Quantization drop probability"
782 )
783 quantize_weight: bool = Field(
784 default=True,
785 alias="quantizeWeight",
786 description="Whether to quantize weights",
787 )
788 weight_scale_init: str = Field(
789 default="MinMax",
790 alias="weightScaleInit",
791 description="Weight scale initialization method",
792 )
793 downresol_mode: str = Field(
794 default="STE", alias="downresolMode", description="Downresolution mode"
795 )
796 scheduler_type: str = Field(
797 default="Cosine", alias="schedulerType", description="LR scheduler type"
798 )
799
800 training: Training = Field(default_factory=Training, alias="training")
801
802 class Loss(BaseModel):
803 model_config = ConfigDict(populate_by_name=True)
804
805 """
806 @brief MOD loss configuration
807
808 @param type str. Loss type (MSE, KL, etc.)
809 @param use_outputs bool. Use model outputs for loss computation
810 @param kl_temperature float. KL divergence temperature
811 @param recon_prob float. Reconstruction probability
812 @param recon_coeff float. Reconstruction coefficient
813 @param lambda_0 float. Loss weight lambda_0
814 @param lambda_1 float. Loss weight lambda_1
815 @param lambda_2 float. Loss weight lambda_2
816 @param lambda_3 float. Loss weight lambda_3
817 @param custom_loss_jit_path str. Path to custom JIT-compiled loss function. Refer to /workspace/quantizer/pyutils/mel.pt
818 """
819 type: str = Field(default="MSE", description="Loss type (MSE, KL, etc.)")
820 use_outputs: bool = Field(
821 default=False,
822 alias="useOutputs",
823 description="Use model outputs for loss computation",
824 )
825 kl_temperature: float = Field(
826 default=1.0,
827 alias="KLTemperature",
828 description="KL divergence temperature",
829 )
830 recon_prob: float = Field(
831 default=1.0, alias="reconProb", description="Reconstruction probability"
832 )
833 recon_coeff: float = Field(
834 default=1.0,
835 alias="reconCoeff",
836 description="Reconstruction coefficient",
837 )
838 lambda_0: float = Field(
839 default=1.0, alias="lambda0", description="Loss weight lambda_0"
840 )
841 lambda_1: float = Field(
842 default=1.0, alias="lambda1", description="Loss weight lambda_1"
843 )
844 lambda_2: float = Field(
845 default=1.0, alias="lambda2", description="Loss weight lambda_2"
846 )
847 lambda_3: float = Field(
848 default=1.0, alias="lambda3", description="Loss weight lambda_3"
849 )
850 custom_loss_jit_path: str = Field(
851 default="",
852 alias="customLossJITPath",
853 description="Path to custom JIT-compiled loss function. Refer to /workspace/quantizer/pyutils/mel.pt",
854 )
855
856 loss: Loss = Field(default_factory=Loss, alias="loss")
857
858 class PostProcessing(BaseModel):
859 model_config = ConfigDict(populate_by_name=True)
860
861 """
862 @brief Post-processing configuration for detection models
863
864 @param post str. Post-processing type
865 @param box_conf_thres float. Box confidence threshold
866 @param box_iou_thres float. Box IoU threshold
867 """
868 post: str = Field(default="", description="Post-processing type")
869 box_conf_thres: float = Field(
870 default=0, alias="boxConfThres", description="Box confidence threshold"
871 )
872 box_iou_thres: float = Field(
873 default=0, alias="boxIoUThres", description="Box IoU threshold"
874 )
875
876 post_processing: PostProcessing = Field(
877 default_factory=PostProcessing, alias="postProcessing"
878 )
879
880 attributes: Attributes = Field(default_factory=Attributes, alias="attributes")
881
882 def with_updates(self, **kwargs) -> "ModConfig":
883 """Return a copy with updated fields."""
884 return self.model_copy(update=kwargs)
885
886
887class LlmConfig(BaseModel):
888 """
889 @brief Configuration for Large Language Model (LLM) compilation
890
891 @details Defines LLM-specific settings including sequence lengths, cache configurations,
892 and runtime parameters for efficient LLM inference.
893
894 @param apply bool. If True, apply LLM-specific configurations
895 @param attributes Attributes. LLM attributes configuration
896 """
897
898 model_config = ConfigDict(
899 populate_by_name=True,
900 extra="forbid",
901 )
902
903 apply: bool = Field(
904 default=False, description="If True, apply LLM-specific configurations"
905 )
906
907 class Attributes(BaseModel):
908 model_config = ConfigDict(populate_by_name=True)
909
910 """
911 @brief LLM attributes configuration
912
913 @param max_data_length int. Maximum data length
914 @param max_sequence_length int. Maximum sequence length
915 @param max_cache_length int. Maximum cache length
916 @param max_core_data_length int. Maximum core data length
917 @param calibration Calibration. LLM calibration settings
918 @param runtime Runtime. LLM runtime settings
919 @param debug Debug. LLM debug settings
920 """
921 max_data_length: int = Field(
922 default=4096, alias="maxDataLength", description="Maximum data length"
923 )
924 max_sequence_length: int = Field(
925 default=4096,
926 alias="maxSequenceLength",
927 description="Maximum sequence length",
928 )
929 max_cache_length: int = Field(
930 default=4096, alias="maxCacheLength", description="Maximum cache length"
931 )
932 max_core_data_length: int = Field(
933 default=128,
934 alias="maxCoreDataLength",
935 description="Maximum core data length",
936 )
937
938 class Calibration(BaseModel):
939 model_config = ConfigDict(populate_by_name=True)
940
941 """
942 @brief LLM calibration settings
943
944 @param random_seq_length int. Random sequence length used for calibration
945 @param use_full_seq_length bool. If True, use the full sequence length for calibration
946 @param use_custom_mask_input bool. Use custom mask input for calibration
947 """
948 random_seq_length: int = Field(
949 default=80,
950 alias="randomSeqLength",
951 description="Random sequence length used for calibration",
952 )
953 use_full_seq_length: bool = Field(
954 default=False,
955 alias="useFullSeqLength",
956 description="If True, use the full sequence length for calibration",
957 )
958 use_custom_mask_input: bool = Field(
959 default=False,
960 alias="useCustomMaskInput",
961 description="Use custom mask input for calibration",
962 )
963
964 calibration: Calibration = Field(
965 default_factory=Calibration, alias="calibration"
966 )
967
968 class Runtime(BaseModel):
969 model_config = ConfigDict(populate_by_name=True)
970
971 """
972 @brief LLM runtime settings
973
974 @param use_global_core bool. If True, use a global core
975 @param batch_size int. Batch size
976 @param npu_core_ids List[int]. List of NPU core IDs
977 @param dynamic_rope bool. If True, enable dynamic RoPE (rotary position embedding)
978 """
979 use_global_core: bool = Field(
980 default=False,
981 alias="useGlobalCore",
982 description="If True, use a global core",
983 )
984 batch_size: int = Field(
985 default=1, alias="batchSize", description="Batch size"
986 )
987 npu_core_ids: List[int] = Field(
988 default=[0], alias="npuCoreIds", description="List of NPU core IDs"
989 )
990 dynamic_rope: bool = Field(
991 default=False,
992 alias="dynamicRope",
993 description="If True, enable dynamic RoPE (rotary position embedding)",
994 )
995
996 runtime: Runtime = Field(default_factory=Runtime, alias="runtime")
997
998 class Debug(BaseModel):
999 model_config = ConfigDict(populate_by_name=True)
1000
1001 """
1002 @brief LLM debug settings
1003
1004 @param apply bool. Enable LLM debug mode
1005 @param batch_debug_bundle_size int. Batch debug bundle size
1006 """
1007 apply: bool = Field(default=False, description="Enable LLM debug mode")
1008 batch_debug_bundle_size: int = Field(
1009 default=0,
1010 alias="batchDebugBundleSize",
1011 description="Batch debug bundle size",
1012 )
1013
1014 debug: Debug = Field(default_factory=Debug, alias="debug")
1015
1016 attributes: Attributes = Field(default_factory=Attributes, alias="attributes")
1017
1018 def with_updates(self, **kwargs) -> "LlmConfig":
1019 """Return a copy with updated fields."""
1020 return self.model_copy(update=kwargs)
1021
1022
1024 """
1025 @brief Configuration for equivalent transformation techniques
1026
1027 @details Defines parameters for various equivalent transformation methods including
1028 NormConv, QK smoothing, and rotation matrices for improved quantization.
1029
1030 @param seed int. Random seed for transformation
1031 @param apply_hadamard_rotation_matrix bool. Apply Hadamard rotation matrix
1032 @param norm_conv NormConv. NormConv equivalent transformation
1033 @param qk Qk. QK smoothing transformation
1034 @param ud Ud. UD transformation
1035 @param vo Vo. VO transformation
1036 @param feed_forward_multi_lut FeedForwardMultiLut. Feed-forward multi-LUT transformation
1037 @param spin_r1 SpinR1. SpinR1 rotation transformation
1038 @param head_out_ch_rotation HeadOutChRotation. Head output channel rotation transformation
1039 @param in_rotation InRotation. Input rotation transformation
1040 @param spin_r2 SpinR2. SpinR2 rotation transformation
1041 @param qk_rotation QkRotation. QK rotation transformation
1042 @param flatten_quant FlattenQuant. Flatten quantization transformation
1043 @param optimize_ffn OptimizeFfn. FFN optimization
1044 """
1045
1046 model_config = ConfigDict(
1047 populate_by_name=True,
1048 extra="forbid",
1049 )
1050
1051 seed: int = Field(default=0, description="Random seed for transformation")
1052 apply_hadamard_rotation_matrix: bool = Field(
1053 default=True,
1054 alias="applyHadamardRotationMatrix",
1055 description="Apply Hadamard rotation matrix",
1056 )
1057
1058 class NormConv(BaseModel):
1059 model_config = ConfigDict(populate_by_name=True)
1060
1061 """
1062 @brief NormConv equivalent transformation
1063
1064 @param apply bool. Apply NormConv transformation
1065 @param learn bool. Learn transformation parameters
1066 @param smoothing_factor float. Smoothing factor
1067 @param min_gamma float. Minimum gamma value
1068 @param max_gamma float. Maximum gamma value
1069 """
1070 apply: bool = Field(default=False, description="Apply NormConv transformation")
1071 learn: bool = Field(
1072 default=False, description="Learn transformation parameters"
1073 )
1074 smoothing_factor: float = Field(
1075 default=0.5, alias="smoothingFactor", description="Smoothing factor"
1076 )
1077 min_gamma: float = Field(
1078 default=0.0001, alias="minGamma", description="Minimum gamma value"
1079 )
1080 max_gamma: float = Field(
1081 default=10000.0, alias="maxGamma", description="Maximum gamma value"
1082 )
1083
1084 norm_conv: NormConv = Field(default_factory=NormConv, alias="NormConv")
1085
1086 class Qk(BaseModel):
1087 model_config = ConfigDict(populate_by_name=True)
1088
1089 """
1090 @brief QK smoothing transformation
1091
1092 @param apply bool. Apply QK transformation
1093 @param smoothing_factor float. Smoothing factor
1094 @param min_gamma float. Minimum gamma value
1095 @param max_gamma float. Maximum gamma value
1096 """
1097 apply: bool = Field(default=False, description="Apply QK transformation")
1098 smoothing_factor: float = Field(
1099 default=0.5, alias="smoothingFactor", description="Smoothing factor"
1100 )
1101 min_gamma: float = Field(
1102 default=0.0001, alias="minGamma", description="Minimum gamma value"
1103 )
1104 max_gamma: float = Field(
1105 default=10000.0, alias="maxGamma", description="Maximum gamma value"
1106 )
1107
1108 qk: Qk = Field(default_factory=Qk, alias="QK")
1109
1110 class Ud(BaseModel):
1111 model_config = ConfigDict(populate_by_name=True)
1112
1113 """
1114 @brief UD transformation
1115
1116 @param apply bool. Apply UD transformation
1117 @param learn bool. Learn transformation parameters
1118 @param smoothing_factor float. Smoothing factor
1119 @param min_gamma float. Minimum gamma value
1120 @param max_gamma float. Maximum gamma value
1121 """
1122 apply: bool = Field(default=False, description="Apply UD transformation")
1123 learn: bool = Field(
1124 default=False, description="Learn transformation parameters"
1125 )
1126 smoothing_factor: float = Field(
1127 default=0.5, alias="smoothingFactor", description="Smoothing factor"
1128 )
1129 min_gamma: float = Field(
1130 default=0.0001, alias="minGamma", description="Minimum gamma value"
1131 )
1132 max_gamma: float = Field(
1133 default=10000.0, alias="maxGamma", description="Maximum gamma value"
1134 )
1135
1136 ud: Ud = Field(default_factory=Ud, alias="UD")
1137
1138 class Vo(BaseModel):
1139 model_config = ConfigDict(populate_by_name=True)
1140
1141 """
1142 @brief VO transformation
1143
1144 @param apply bool. Apply VO transformation
1145 @param smoothing_factor float. Smoothing factor
1146 @param min_gamma float. Minimum gamma value
1147 @param max_gamma float. Maximum gamma value
1148 """
1149 apply: bool = Field(default=False, description="Apply VO transformation")
1150 smoothing_factor: float = Field(
1151 default=0.5, alias="smoothingFactor", description="Smoothing factor"
1152 )
1153 min_gamma: float = Field(
1154 default=0.0001, alias="minGamma", description="Minimum gamma value"
1155 )
1156 max_gamma: float = Field(
1157 default=10000.0, alias="maxGamma", description="Maximum gamma value"
1158 )
1159
1160 vo: Vo = Field(default_factory=Vo, alias="VO")
1161
1162 class FeedForwardMultiLut(BaseModel):
1163 """
1164 @brief Feed-forward multi-LUT transformation
1165
1166 @param apply bool. Apply feed-forward multi-LUT transformation
1167 @param breakpoints List[float]. Breakpoints for multi-LUT
1168 """
1169
1170 apply: bool = Field(
1171 default=False, description="Apply feed-forward multi-LUT transformation"
1172 )
1173 breakpoints: List[float] = Field(
1174 default=[-8.0, -4.0, 0], description="Breakpoints for multi-LUT"
1175 )
1176
1177 feed_forward_multi_lut: FeedForwardMultiLut = Field(
1178 default_factory=FeedForwardMultiLut, alias="FeedForwardMultiLUT"
1179 )
1180
1181 class SpinR1(BaseModel):
1182 model_config = ConfigDict(populate_by_name=True)
1183
1184 """
1185 @brief SpinR1 rotation transformation
1186
1187 @param apply bool. Apply SpinR1 transformation
1188 @param matrix_path str. Path to rotation matrix file
1189 """
1190 apply: bool = Field(default=False, description="Apply SpinR1 transformation")
1191 matrix_path: str = Field(
1192 default="", alias="matrixPath", description="Path to rotation matrix file"
1193 )
1194
1195 spin_r1: SpinR1 = Field(default_factory=SpinR1, alias="SpinR1")
1196
1197 class HeadOutChRotation(BaseModel):
1198 model_config = ConfigDict(populate_by_name=True)
1199
1200 """
1201 @brief Head output channel rotation transformation
1202
1203 @param apply bool. Apply head output channel rotation
1204 @param matrix_path str. Path to rotation matrix file
1205 """
1206 apply: bool = Field(
1207 default=False, description="Apply head output channel rotation"
1208 )
1209 matrix_path: str = Field(
1210 default="", alias="matrixPath", description="Path to rotation matrix file"
1211 )
1212
1213 head_out_ch_rotation: HeadOutChRotation = Field(
1214 default_factory=HeadOutChRotation, alias="HeadOutChRotation"
1215 )
1216
1217 class InRotation(BaseModel):
1218 model_config = ConfigDict(populate_by_name=True)
1219
1220 """
1221 @brief Input rotation transformation
1222
1223 @param apply bool. Apply input rotation
1224 @param matrix_path str. Path to rotation matrix file
1225 @param input_names List[str]. Names of the input layers to rotate
1226 """
1227 apply: bool = Field(default=False, description="Apply input rotation")
1228 matrix_path: str = Field(
1229 default="", alias="matrixPath", description="Path to rotation matrix file"
1230 )
1231 input_names: List[str] = Field(
1232 default=[],
1233 alias="inputNames",
1234 description="Names of the input layers to rotate",
1235 )
1236
1237 in_rotation: InRotation = Field(default_factory=InRotation, alias="InRotation")
1238
1239 class SpinR2(BaseModel):
1240 model_config = ConfigDict(populate_by_name=True)
1241
1242 """
1243 @brief SpinR2 rotation transformation
1244
1245 @param apply bool. Apply SpinR2 transformation
1246 @param learn bool. Learn rotation matrix
1247 @param matrix_path str. Path to rotation matrix file
1248 """
1249 apply: bool = Field(default=False, description="Apply SpinR2 transformation")
1250 learn: bool = Field(default=False, description="Learn rotation matrix")
1251 matrix_path: str = Field(
1252 default="", alias="matrixPath", description="Path to rotation matrix file"
1253 )
1254
1255 spin_r2: SpinR2 = Field(default_factory=SpinR2, alias="SpinR2")
1256
1257 class QkRotation(BaseModel):
1258 model_config = ConfigDict(populate_by_name=True)
1259
1260 """
1261 @brief QK rotation transformation
1262
1263 @param apply bool. Apply QK rotation transformation
1264 @param matrix_path str. Path to rotation matrix file
1265 """
1266 apply: bool = Field(
1267 default=False, description="Apply QK rotation transformation"
1268 )
1269 matrix_path: str = Field(
1270 default="", alias="matrixPath", description="Path to rotation matrix file"
1271 )
1272
1273 qk_rotation: QkRotation = Field(default_factory=QkRotation, alias="QKRotation")
1274
1275 class FlattenQuant(BaseModel):
1276 model_config = ConfigDict(populate_by_name=True)
1277
1278 """
1279 @brief Flatten quantization transformation
1280
1281 @param apply bool. Apply flatten quantization
1282 @param learn bool. Learn flattening parameters
1283 @param apply_threshold float. Threshold for applying flatten quantization
1284 @param max_overhead float. Maximum overhead allowed for flattening
1285 """
1286 apply: bool = Field(default=False, description="Apply flatten quantization")
1287 learn: bool = Field(default=False, description="Learn flattening parameters")
1288 apply_threshold: float = Field(
1289 default=0.33,
1290 alias="applyThreshold",
1291 description="Threshold for applying flatten quantization",
1292 )
1293 max_overhead: float = Field(
1294 default=0.02,
1295 alias="maxOverhead",
1296 description="Maximum overhead allowed for flattening",
1297 )
1298
1299 flatten_quant: FlattenQuant = Field(
1300 default_factory=FlattenQuant, alias="FlattenQuant"
1301 )
1302
1303 class OptimizeFfn(BaseModel):
1304 model_config = ConfigDict(populate_by_name=True)
1305
1306 """
1307 @brief FFN optimization
1308
1309 @param apply bool. Apply FFN optimization
1310 @param ch_per_ffn int. Optimize FFN split (-1 for auto)
1311 """
1312 apply: bool = Field(default=False, description="Apply FFN optimization")
1313 ch_per_ffn: int = Field(
1314 default=-1, alias="chPerFFN", description="Optimize FFN split (-1 for auto)"
1315 )
1316
1317 optimize_ffn: OptimizeFfn = Field(default_factory=OptimizeFfn, alias="OptimizeFFN")
1318
1319 def with_updates(self, **kwargs) -> "EquivalentTransformationConfig":
1320 """Return a copy with updated fields."""
1321 return self.model_copy(update=kwargs)
1322
1323
1325 """
1326 @brief Configuration for weight scale search
1327
1328 @details Defines which transformer components should have their weight scales
1329 searched for optimal quantization.
1330
1331 @param apply bool. If true, apply weight scale search
1332 @param transformer Transformer. Transformer components for weight scale search
1333 """
1334
1335 model_config = ConfigDict(
1336 populate_by_name=True,
1337 extra="forbid",
1338 )
1339
1340 apply: bool = Field(default=False, description="If true, apply weight scale search")
1341
1342 class Transformer(BaseModel):
1343 """
1344 @brief Transformer components for weight scale search
1345
1346 @param query bool. Search weight scale for query
1347 @param key bool. Search weight scale for key
1348 @param value bool. Search weight scale for value
1349 @param out bool. Search weight scale for output
1350 @param ffn bool. Search weight scale for FFN
1351 """
1352
1353 query: bool = Field(default=False, description="Search weight scale for query")
1354 key: bool = Field(default=False, description="Search weight scale for key")
1355 value: bool = Field(default=False, description="Search weight scale for value")
1356 out: bool = Field(default=False, description="Search weight scale for output")
1357 ffn: bool = Field(default=False, description="Search weight scale for FFN")
1358
1359 transformer: Transformer = Field(default_factory=Transformer, alias="transformer")
1360
1361 def with_updates(self, **kwargs) -> "SearchWeightScaleConfig":
1362 """Return a copy with updated fields."""
1363 return self.model_copy(update=kwargs)
1364
1365
1366class RuntimeOptions(BaseModel):
1367 """
1368 @brief Runtime options for compilation
1369
1370 @details Contains runtime-specific settings like version info and cache options.
1371
1372 @param version str. Compiler version string (e.g., 0.0.0)
1373 """
1374
1375 model_config = ConfigDict(
1376 populate_by_name=True,
1377 extra="forbid",
1378 )
1379
1380 version: str = Field(
1381 default="0.0.0", description="Compiler version string (e.g., 0.0.0)"
1382 )
1383
1384 def with_updates(self, **kwargs) -> "RuntimeOptions":
1385 """Return a copy with updated fields."""
1386 return self.model_copy(update=kwargs)
1387
1388
1389class SaveSampleConfig(BaseModel):
1390 """
1391 @brief Sample data generation and saving configuration
1392
1393 @param apply bool. Enable sample data saving
1394 @param mode str. Inference mode: infer (standard) or inferWithCache (LLM cache models)
1395 @param batch_size int. Number of inference batches to generate
1396 @param batch_seq_lens List. Per-batch step-wise sequence lengths for inferWithCache mode. e.g. [[80, 1], [240, 10]]
1397 @param save_folder str. Output folder for sample data
1398 @param dtype str. Data type for saved samples: float or int8
1399 """
1400
1401 model_config = ConfigDict(
1402 populate_by_name=True,
1403 extra="forbid",
1404 )
1405
1406 apply: bool = Field(default=False, description="Enable sample data saving")
1407 mode: str = Field(
1408 default="infer",
1409 description="Inference mode: infer (standard) or inferWithCache (LLM cache models)",
1410 )
1411 batch_size: int = Field(
1412 default=1,
1413 alias="batchSize",
1414 description="Number of inference batches to generate",
1415 )
1416 batch_seq_lens: Any = Field(
1417 default=[],
1418 alias="batchSeqLens",
1419 description="Per-batch step-wise sequence lengths for inferWithCache mode. e.g. [[80, 1], [240, 10]]",
1420 )
1421 save_folder: str = Field(
1422 default="sampleInout",
1423 alias="saveFolder",
1424 description="Output folder for sample data",
1425 )
1426 dtype: str = Field(
1427 default="float", description="Data type for saved samples: float or int8"
1428 )
1429
1430 def with_updates(self, **kwargs) -> "SaveSampleConfig":
1431 """Return a copy with updated fields."""
1432 return self.model_copy(update=kwargs)
1433
1434
1435class CompileConfig(BaseModel):
1436 """Unified compilation configuration for Mobilint MXQ compilation."""
1437
1438 model_config = ConfigDict(
1439 populate_by_name=True,
1440 extra="forbid",
1441 )
1442
1443 model_paths: List[str] = Field(
1444 default=[], alias="modelPaths", description="Paths to model files"
1445 )
1446 calib_data_path: List[str] = Field(
1447 default=[], alias="calibDataPaths", description="Paths to calibration datasets"
1448 )
1449 save_paths: List[str] = Field(
1450 default=["./tmp.mxq"],
1451 alias="savePaths",
1452 description="Output MXQ filename/paths",
1453 )
1454 use_random_calib: bool = Field(
1455 default=False, alias="useRandomCalib", description="Use random calibration"
1456 )
1457 save_msgpack_name: Optional[str] = Field(
1458 default=None,
1459 alias="saveMsgpackName",
1460 description="Name of the msgpack file to save",
1461 )
1462 inference_scheme: str = Field(
1463 default="single", alias="inferenceScheme", description="NPU inference scheme"
1464 )
1465 cpu_offload: bool = Field(
1466 default=False,
1467 alias="cpuOffload",
1468 description="Enable CPU offload for unsupported operators",
1469 )
1470 force_npu_input_reposition: bool = Field(
1471 default=False,
1472 alias="forceNpuInputReposition",
1473 description="Force input reposition operations to run on NPU instead of CPU",
1474 )
1475 force_npu_output_reposition: bool = Field(
1476 default=False,
1477 alias="forceNpuOutputReposition",
1478 description="Force output reposition operations to run on NPU instead of CPU",
1479 )
1480 optimize_option: int = Field(
1481 default=1,
1482 alias="optimizeOption",
1483 description="Compiler optimization selector",
1484 ge=0,
1485 )
1486 buffer_mode: int = Field(
1487 default=1, alias="bufferMode", description="Buffer serialization mode"
1488 )
1489 input_shape_dict: Any = Field(
1490 default={}, alias="inputShapeDict", description="Dictionary of input shapes"
1491 )
1492 device: str = Field(default="gpu", description="Device for computation")
1493 dtype: str = Field(default="float", description="Data type for computation")
1494 debug: bool = Field(default=False, description="Enable debug mode")
1495 trace: bool = Field(default=False, description="Enable trace mode")
1496 image_channels: int = Field(
1497 default=0,
1498 alias="imageChannels",
1499 description="Number of image channels (0 for auto-detect)",
1500 )
1501 config_version: str = Field(
1502 default="1.0.0", alias="configVersion", description="Config schema version"
1503 )
1504 split_blocks: List[int] = Field(
1505 default=[],
1506 alias="splitBlocks",
1507 description="Multi-MXQ split points by transformer block index",
1508 )
1509 split_parts: int = Field(
1510 default=0,
1511 alias="splitParts",
1512 description="Evenly split transformer blocks into N MXQ parts",
1513 )
1514
1515 uint8_input: Uint8InputConfig = Field(
1516 default_factory=Uint8InputConfig, alias="uint8Input"
1517 )
1518 preprocessing: PreprocessingConfig = Field(default_factory=PreprocessingConfig)
1519 resource_management: ResourceManagementConfig = Field(
1520 default_factory=ResourceManagementConfig, alias="resourceManagement"
1521 )
1522 calibration: CalibrationConfig = Field(default_factory=CalibrationConfig)
1523 bit: BitConfig = Field(default_factory=BitConfig)
1524 optq: OptqConfig = Field(default_factory=OptqConfig)
1525 mod: ModConfig = Field(default_factory=ModConfig)
1526 llm: LlmConfig = Field(default_factory=LlmConfig)
1527 equivalent_transformation: EquivalentTransformationConfig = Field(
1528 default_factory=EquivalentTransformationConfig, alias="equivalentTransformation"
1529 )
1530 search_weight_scale: SearchWeightScaleConfig = Field(
1531 default_factory=SearchWeightScaleConfig, alias="searchWeightScale"
1532 )
1533 runtime_options: RuntimeOptions = Field(
1534 default_factory=RuntimeOptions, alias="runtimeOptions"
1535 )
1536 save_sample: SaveSampleConfig = Field(
1537 default_factory=SaveSampleConfig, alias="saveSample"
1538 )
1539
1540 def with_uint8_input(self, **kwargs) -> "CompileConfig":
1541 """Return a copy with uint8_input settings enabled."""
1542 data = {"apply": True, **kwargs}
1543 new_cfg = self.uint8_input.model_copy(update=data)
1544 return self.model_copy(update={"uint8_input": new_cfg})
1545
1546 def with_preprocessing(self, **kwargs) -> "CompileConfig":
1547 """Return a copy with preprocessing settings enabled."""
1548 data = {"apply": True, **kwargs}
1549 new_cfg = self.preprocessing.model_copy(update=data)
1550 return self.model_copy(update={"preprocessing": new_cfg})
1551
1552 def with_optq(self, **kwargs) -> "CompileConfig":
1553 """Return a copy with optq settings enabled."""
1554 data = {"apply": True, **kwargs}
1555 new_cfg = self.optq.model_copy(update=data)
1556 return self.model_copy(update={"optq": new_cfg})
1557
1558 def with_mod(self, **kwargs) -> "CompileConfig":
1559 """Return a copy with mod settings enabled."""
1560 data = {"apply": True, **kwargs}
1561 new_cfg = self.mod.model_copy(update=data)
1562 return self.model_copy(update={"mod": new_cfg})
1563
1564 def with_llm(self, **kwargs) -> "CompileConfig":
1565 """Return a copy with llm settings enabled."""
1566 data = {"apply": True, **kwargs}
1567 new_cfg = self.llm.model_copy(update=data)
1568 return self.model_copy(update={"llm": new_cfg})
1569
1570 def with_search_weight_scale(self, **kwargs) -> "CompileConfig":
1571 """Return a copy with search_weight_scale settings enabled."""
1572 data = {"apply": True, **kwargs}
1573 new_cfg = self.search_weight_scale.model_copy(update=data)
1574 return self.model_copy(update={"search_weight_scale": new_cfg})
1575
1576 def with_save_sample(self, **kwargs) -> "CompileConfig":
1577 """Return a copy with save_sample settings enabled."""
1578 data = {"apply": True, **kwargs}
1579 new_cfg = self.save_sample.model_copy(update=data)
1580 return self.model_copy(update={"save_sample": new_cfg})
1581
1582 @classmethod
1583 def from_file(cls, path: Union[str, Path]) -> "CompileConfig":
1584 """Load config from YAML or JSON file."""
1585 path = Path(path)
1586 with open(path) as f:
1587 if path.suffix in (".yaml", ".yml"):
1588 data = yaml.safe_load(f)
1589 else:
1590 data = json.load(f)
1591 data = cls._flatten_grouped_json(data)
1592 return cls.model_validate(data)
1593
1594 @staticmethod
1595 def _flatten_grouped_json(data: dict) -> dict:
1596 """Flatten grouped JSON keys (e.g. quantization.calibration) to flat structure."""
1597 data = data.copy()
1598 if "quantization" in data:
1599 group = data.pop("quantization")
1600 if "calibration" in group:
1601 data["calibration"] = group["calibration"]
1602 if "bit" in group:
1603 data["bit"] = group["bit"]
1604 if "advancedQuantization" in data:
1605 group = data.pop("advancedQuantization")
1606 if "optq" in group:
1607 data["optq"] = group["optq"]
1608 if "mod" in group:
1609 data["mod"] = group["mod"]
1610 if "EquivalentTransformation" in group:
1611 data["equivalentTransformation"] = group["EquivalentTransformation"]
1612 if "searchWeightScale" in group:
1613 data["searchWeightScale"] = group["searchWeightScale"]
1614 return data
1615
1616 @classmethod
1617 def from_preset(cls, name: str) -> "CompileConfig":
1618 """Load config from a preset."""
1619 from .presets import get_preset
1620
1621 return get_preset(name)
1622
1623 @staticmethod
1624 def _group_to_json(data: dict) -> dict:
1625 """Group flat keys back into nested JSON structure (inverse of _flatten_grouped_json)."""
1626 data = data.copy()
1627 quantization_group = {}
1628 if "calibration" in data:
1629 quantization_group["calibration"] = data.pop("calibration")
1630 if "bit" in data:
1631 quantization_group["bit"] = data.pop("bit")
1632 if quantization_group:
1633 data["quantization"] = quantization_group
1634 advancedQuantization_group = {}
1635 if "optq" in data:
1636 advancedQuantization_group["optq"] = data.pop("optq")
1637 if "mod" in data:
1638 advancedQuantization_group["mod"] = data.pop("mod")
1639 if "equivalentTransformation" in data:
1640 advancedQuantization_group["EquivalentTransformation"] = data.pop(
1641 "equivalentTransformation"
1642 )
1643 if "searchWeightScale" in data:
1644 advancedQuantization_group["searchWeightScale"] = data.pop(
1645 "searchWeightScale"
1646 )
1647 if advancedQuantization_group:
1648 data["advancedQuantization"] = advancedQuantization_group
1649 return data
1650
1651 def to_file(self, path: Union[str, Path]) -> None:
1652 """Save config to YAML or JSON file."""
1653 path = Path(path)
1654 data = self.model_dump(by_alias=True, exclude_none=True)
1655 data = self._group_to_json(data)
1656 with open(path, "w") as f:
1657 if path.suffix in (".yaml", ".yml"):
1658 yaml.dump(data, f, default_flow_style=False)
1659 else:
1660 json.dump(data, f, indent=2)
Activation bit-widths for transformer components.
Definition models.py:454
Weight bit-widths for transformer components.
Definition models.py:475
Configuration for bit precision.
Definition models.py:426
"BitConfig" with_updates(self, **kwargs)
Return a copy with updated fields.
Definition models.py:593
Configuration for calibration during quantization.
Definition models.py:141
"CalibrationConfig" with_updates(self, **kwargs)
Return a copy with updated fields.
Definition models.py:421
Unified compilation configuration for Mobilint MXQ compilation.
Definition models.py:1435
"CompileConfig" with_optq(self, **kwargs)
Return a copy with optq settings enabled.
Definition models.py:1552
"CompileConfig" with_llm(self, **kwargs)
Return a copy with llm settings enabled.
Definition models.py:1564
"CompileConfig" from_preset(cls, str name)
Load config from a preset.
Definition models.py:1617
"CompileConfig" with_search_weight_scale(self, **kwargs)
Return a copy with search_weight_scale settings enabled.
Definition models.py:1570
SearchWeightScaleConfig search_weight_scale
Definition models.py:1530
"CompileConfig" with_preprocessing(self, **kwargs)
Return a copy with preprocessing settings enabled.
Definition models.py:1546
dict _flatten_grouped_json(dict data)
Flatten grouped JSON keys (e.g.
Definition models.py:1595
"CompileConfig" with_mod(self, **kwargs)
Return a copy with mod settings enabled.
Definition models.py:1558
dict _group_to_json(dict data)
Group flat keys back into nested JSON structure (inverse of _flatten_grouped_json).
Definition models.py:1624
"CompileConfig" with_save_sample(self, **kwargs)
Return a copy with save_sample settings enabled.
Definition models.py:1576
"CompileConfig" from_file(cls, Union[str, Path] path)
Load config from YAML or JSON file.
Definition models.py:1583
None to_file(self, Union[str, Path] path)
Save config to YAML or JSON file.
Definition models.py:1651
"CompileConfig" with_uint8_input(self, **kwargs)
Return a copy with uint8_input settings enabled.
Definition models.py:1540
Configuration for equivalent transformation techniques.
Definition models.py:1023
"EquivalentTransformationConfig" with_updates(self, **kwargs)
Return a copy with updated fields.
Definition models.py:1319
Configuration for Large Language Model (LLM) compilation.
Definition models.py:887
"LlmConfig" with_updates(self, **kwargs)
Return a copy with updated fields.
Definition models.py:1018
Configuration for Minimum Output Difference algorithm.
Definition models.py:655
"ModConfig" with_updates(self, **kwargs)
Return a copy with updated fields.
Definition models.py:882
Configuration for OPTQ algorithm.
Definition models.py:598
"OptqConfig" with_updates(self, **kwargs)
Return a copy with updated fields.
Definition models.py:650
Configuration for input preprocessing pipeline.
Definition models.py:47
"PreprocessingConfig" with_updates(self, **kwargs)
Return a copy with updated fields.
Definition models.py:82
Configuration for resource management during model compilation.
Definition models.py:87
"ResourceManagementConfig" with_updates(self, **kwargs)
Return a copy with updated fields.
Definition models.py:136
Runtime options for compilation.
Definition models.py:1366
"RuntimeOptions" with_updates(self, **kwargs)
Return a copy with updated fields.
Definition models.py:1384
Sample data generation and saving configuration.
Definition models.py:1389
"SaveSampleConfig" with_updates(self, **kwargs)
Return a copy with updated fields.
Definition models.py:1430
Transformer components for weight scale search.
Definition models.py:1342
Configuration for weight scale search.
Definition models.py:1324
"SearchWeightScaleConfig" with_updates(self, **kwargs)
Return a copy with updated fields.
Definition models.py:1361
Configuration for uint8 input handling.
Definition models.py:13
"Uint8InputConfig" with_updates(self, **kwargs)
Return a copy with updated fields.
Definition models.py:42