models.py Source File

models.py Source File#

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