mod_config.py Source File

mod_config.py Source File#

Mobilint SDK qb Compiler: mod_config.py Source File
Mobilint SDK qb Compiler v1.0
MCS002-EN
mod_config.py
1import numbers
2from typing import List, Optional
3from typeguard import typechecked
4from . import ConfigABC
5
6
12
13
14class ModConfig(ConfigABC):
15 """
16 @brief Configuration for Minimum Output Difference algorithm.
17
18 @details Defines parameters controlling whether and how Mod is applied during quantization, including layer-level inclusion/exclusion lists.
19 """
20
21 optional = True
22 DEFAULTS = {
23 "apply": False,
24 "epochs": 4,
25 "warmup_epochs": 1,
26 "lr_act_scale": 0.0,
27 "lr_zeropoint": 0.0,
28 "lr_weight_scale": 0.0,
29 "lr_weight": 4e-6,
30 "lr_bias": 4e-6,
31 "lr_min_ratio": 1e-4,
32 "batch_size": 1,
33 "q_drop": 0.0,
34 "post_processing": "",
35 "box_conf_thres": 0,
36 "box_iou_thres": 0,
37 "loss_type": "MSE",
38 "use_outputs": False,
39 "kl_temperature": 1.0,
40 "recon_prob": 1.0,
41 "recon_coeff": 1.0,
42 "lambda_0": 1.0,
43 "lambda_1": 1.0,
44 "lambda_2": 1.0,
45 "anchors": [
46 [[12, 16], [19, 36], [40, 28]],
47 [[36, 75], [76, 55], [72, 146]],
48 [[142, 110], [192, 243], [459, 401]],
49 ],
50 "use_xyxy": False,
51 "save_dir": "",
52 "seed": 0,
53 "apply_layers": [],
54 "exclude_layers": [],
55 "custom_loss_jit_path": "",
56 "mod_after_layer_name": "",
57 }
58
59 py_to_cpp_name = {
60 "apply": "apply",
61 "epochs": "epochs",
62 "warmup_epochs": "warmupEpochs",
63 "lr_min_ratio": "lrMinRatio",
64 "lr_act_scale": "actScaleLR",
65 "lr_zeropoint": "zeropointLR",
66 "lr_weight_scale": "weightScaleLR",
67 "lr_weight": "weightLR",
68 "lr_bias": "biasLR",
69 "batch_size": "batchSize",
70 "q_drop": "qDrop",
71 "post_processing": "post",
72 "box_conf_thres": "boxConfThres",
73 "box_iou_thres": "boxIoUThres",
74 "loss_type": "lossType",
75 "use_outputs": "useOutputs",
76 "kl_temperature": "KLTemperature",
77 "recon_prob": "reconProb",
78 "recon_coeff": "reconCoeff",
79 "lambda_0": "lambda_0",
80 "lambda_1": "lambda_1",
81 "lambda_2": "lambda_2",
82 "use_xyxy": "useXYXY",
83 "save_dir": "saveDir",
84 "seed": "seed",
85 "custom_loss_jit_path": "customLossJITPath",
86 "mod_after_layer_name": "modAfterLayerName",
87 }
88
89 min_max_check = {
90 "epochs": [0, None],
91 "warmup_epochs": [0, None],
92 "lr_min_ratio": [0, None],
93 "lr_act_scale": [0, None],
94 "lr_zeropoint": [0, None],
95 "lr_weight_scale": [0, None],
96 "lr_weight": [0, None],
97 "lr_bias": [0, None],
98 "batch_size": [0, None],
99 "q_drop": [0, 1],
100 "box_conf_thres": [0, None],
101 "box_iou_thres": [0, None],
102 "kl_temperature": [0, None],
103 "recon_prob": [0, 1],
104 "recon_coeff": [0, None],
105 "lambda_0": [0, None],
106 "lambda_1": [0, None],
107 "lambda_2": [0, None],
108 "seed": [0, None],
109 }
110
111 @typechecked
113 self,
114 apply: bool,
115 epochs: int,
116 warmup_epochs: int,
117 lr_act_scale: numbers.Number,
118 lr_zeropoint: numbers.Number,
119 lr_weight_scale: numbers.Number,
120 lr_weight: numbers.Number,
121 lr_bias: numbers.Number,
122 lr_min_ratio: numbers.Number,
123 batch_size: int,
124 q_drop: numbers.Number,
125 post_processing: str,
126 box_conf_thres: numbers.Number,
127 box_iou_thres: numbers.Number,
128 loss_type: str,
129 use_outputs: bool,
130 kl_temperature: numbers.Number,
131 recon_prob: numbers.Number,
132 recon_coeff: numbers.Number,
133 lambda_0: numbers.Number,
134 lambda_1: numbers.Number,
135 lambda_2: numbers.Number,
136 anchors: List,
137 use_xyxy: bool,
138 save_dir: str,
139 seed: int,
140 apply_layers: List[str],
141 exclude_layers: List[str],
142 custom_loss_jit_path: str,
143 mod_after_layer_name: str,
144 optional: bool = optional,
145 ):
146 """
147 @brief Initialize the ModConfig.
148 @param apply bool. Whether to apply MOD.
149 @param epochs int. Number of training epochs.
150 @param warmup_epochs int. Number of warmup epochs.
151 @param lr_act_scale float. Learning rate for activation scale.
152 @param lr_zeropoint float. Learning rate for zeropoint.
153 @param lr_weight_scale float. Learning rate for weight scale.
154 @param lr_weight float. Learning rate for weight.
155 @param lr_bias float. Learning rate for bias.
156 @param lr_min_ratio float. Minimum learning rate ratio for scheduler.
157 @param batch_size int. Batch size for training.
158 @param q_drop float. QDrop ratio.
159 @param post_processing str. Post-processing function.
160 @param box_conf_thres float. Box confidence threshold for NMS.
161 @param box_iou_thres float. Box IoU threshold for NMS.
162 @param loss_type str. Loss function type.
163 @param use_outputs bool. Compare only intermediate layers.
164 @param kl_temperature float. Temperature for KL divergence loss.
165 @param recon_prob float. Sampling probability for intermediate layers.
166 @param recon_coeff float. Coefficient for intermediate layer loss.
167 @param lambda_0 float. First coefficient for AnchorlessDetection loss.
168 @param lambda_1 float. Second coefficient for AnchorlessDetection loss.
169 @param lambda_2 float. Third coefficient for AnchorlessDetection loss.
170 @param anchors List. Anchor boxes configuration.
171 @param use_xyxy bool. Use XYXY format.
172 @param save_dir str. Directory to save results.
173 @param seed int. Random seed.
174 @param apply_layers List[str]. Layers to apply MOD.
175 @param exclude_layers List[str]. Layers to exclude from MOD.
176 @param custom_loss_jit_path str. Path to custom loss JIT file.
177 @param mod_after_layer_name str. Layer name to apply MOD after.
178 @param optional bool. Indicates whether this config is optional. Use the default value defined as a class variable.
179 """
180 super().__init__(optional)
181 self.apply = apply
182 self.epochs = epochs
183 self.warmup_epochs = warmup_epochs
184 self.lr_act_scale = lr_act_scale
185 self.lr_zeropoint = lr_zeropoint
186 self.lr_weight_scale = lr_weight_scale
187 self.lr_weight = lr_weight
188 self.lr_bias = lr_bias
189 self.lr_min_ratio = lr_min_ratio
190 self.batch_size = batch_size
191 self.q_drop = q_drop
192 self.post_processing = post_processing
193 self.box_conf_thres = box_conf_thres
194 self.box_iou_thres = box_iou_thres
195 self.loss_type = loss_type
196 self.use_outputs = use_outputs
197 self.kl_temperature = kl_temperature
198 self.recon_prob = recon_prob
199 self.recon_coeff = recon_coeff
200 self.lambda_0 = lambda_0
201 self.lambda_1 = lambda_1
202 self.lambda_2 = lambda_2
203 self.anchors = anchors
204 self.use_xyxy = use_xyxy
205 self.save_dir = save_dir
206 self.seed = seed
207 self.apply_layers = apply_layers
208 self.exclude_layers = exclude_layers
209 self.custom_loss_jit_path = custom_loss_jit_path
210 self.mod_after_layer_name = mod_after_layer_name
211 self.check_valid(
212 except_list=["optional", "anchors", "apply_layers", "exclude_layers"]
213 )
214
215 @classmethod
216 def default_config(cls):
217 return cls(**cls.DEFAULTS, optional=cls.optional)
218
219 @classmethod
220 def from_dict(cls, config_dict: dict):
221 """Create ModConfig from dictionary (JSON structure)"""
222 params = cls.DEFAULTS.copy()
223
224 if "apply" in config_dict:
225 params["apply"] = config_dict["apply"]
226
227 if "attributes" in config_dict:
228 attributes = config_dict["attributes"]
229
230 if "epochs" in attributes:
231 params["epochs"] = attributes["epochs"]
232 if "warmupEpochs" in attributes:
233 params["warmup_epochs"] = attributes["warmupEpochs"]
234 if "lrMinRatio" in attributes:
235 params["lr_min_ratio"] = attributes["lrMinRatio"]
236 if "anchors" in attributes:
237 params["anchors"] = attributes["anchors"]
238 if "useXYXY" in attributes:
239 params["use_xyxy"] = attributes["useXYXY"]
240 if "saveDir" in attributes:
241 params["save_dir"] = attributes["saveDir"]
242 if "seed" in attributes:
243 params["seed"] = attributes["seed"]
244 if "applyLayers" in attributes:
245 params["apply_layers"] = attributes["applyLayers"]
246 if "excludeLayers" in attributes:
247 params["exclude_layers"] = attributes["excludeLayers"]
248 if "modAfterLayerName" in attributes:
249 params["mod_after_layer_name"] = attributes["modAfterLayerName"]
250
251 if "learningRates" in attributes:
252 learning_rates = attributes["learningRates"]
253 if "actScale" in learning_rates:
254 params["lr_act_scale"] = learning_rates["actScale"]
255 if "zeropoint" in learning_rates:
256 params["lr_zeropoint"] = learning_rates["zeropoint"]
257 if "weightScale" in learning_rates:
258 params["lr_weight_scale"] = learning_rates["weightScale"]
259 if "weight" in learning_rates:
260 params["lr_weight"] = learning_rates["weight"]
261 if "bias" in learning_rates:
262 params["lr_bias"] = learning_rates["bias"]
263
264 if "training" in attributes:
265 training = attributes["training"]
266 if "batchSize" in training:
267 params["batch_size"] = training["batchSize"]
268 if "qDrop" in training:
269 params["q_drop"] = training["qDrop"]
270
271 if "postProcessing" in attributes:
272 post_processing = attributes["postProcessing"]
273 if "post" in post_processing:
274 params["post_processing"] = post_processing["post"]
275 if "boxConfThres" in post_processing:
276 params["box_conf_thres"] = post_processing["boxConfThres"]
277 if "boxIoUThres" in post_processing:
278 params["box_iou_thres"] = post_processing["boxIoUThres"]
279
280 if "loss" in attributes:
281 loss = attributes["loss"]
282 if "type" in loss:
283 params["loss_type"] = loss["type"]
284 if "useOutputs" in loss:
285 params["use_outputs"] = loss["useOutputs"]
286 if "KLTemperature" in loss:
287 params["kl_temperature"] = loss["KLTemperature"]
288 if "reconProb" in loss:
289 params["recon_prob"] = loss["reconProb"]
290 if "reconCoeff" in loss:
291 params["recon_coeff"] = loss["reconCoeff"]
292 if "lambda_0" in loss:
293 params["lambda_0"] = loss["lambda_0"]
294 if "lambda_1" in loss:
295 params["lambda_1"] = loss["lambda_1"]
296 if "lambda_2" in loss:
297 params["lambda_2"] = loss["lambda_2"]
298 # Read customLossJITPath from loss object
299 if "customLossJITPath" in loss:
300 params["custom_loss_jit_path"] = loss["customLossJITPath"]
301
302 return cls(**params)
303
304 def to_dict(self):
305 return {
306 "apply": self.apply,
307 "attributes": {
308 "epochs": self.epochs,
309 "warmupEpochs": self.warmup_epochs,
310 "learningRates": {
311 "actScale": self.lr_act_scale,
312 "zeropoint": self.lr_zeropoint,
313 "weightScale": self.lr_weight_scale,
314 "weight": self.lr_weight,
315 "bias": self.lr_bias,
316 },
317 "lrMinRatio": self.lr_min_ratio,
318 "training": {
319 "batchSize": self.batch_size,
320 "qDrop": self.q_drop,
321 },
322 "postProcessing": {
323 "post": self.post_processing,
324 "boxConfThres": self.box_conf_thres,
325 "boxIoUThres": self.box_iou_thres,
326 },
327 "loss": {
328 "type": self.loss_type,
329 "useOutputs": self.use_outputs,
330 "KLTemperature": self.kl_temperature,
331 "reconProb": self.recon_prob,
332 "reconCoeff": self.recon_coeff,
333 "lambda_0": self.lambda_0,
334 "lambda_1": self.lambda_1,
335 "lambda_2": self.lambda_2,
336 "customLossJITPath": self.custom_loss_jit_path,
337 },
338 "anchors": self.anchors,
339 "useXYXY": self.use_xyxy,
340 "saveDir": self.save_dir,
341 "seed": self.seed,
342 "applyLayers": self.apply_layers,
343 "excludeLayers": self.exclude_layers,
344 "modAfterLayerName": self.mod_after_layer_name,
345 },
346 }
347
348
349def get_mod_config(**kwargs) -> ModConfig:
350 """
351 @brief Create ModConfig with partial parameters merged with defaults.
352 """
353 params = ModConfig.DEFAULTS.copy()
354 params.update(kwargs)
355 return ModConfig(**params, optional=ModConfig.optional)
356
357
358# @}
Configuration for Minimum Output Difference algorithm.
Definition mod_config.py:14
ModConfig get_mod_config(**kwargs)
Create ModConfig with partial parameters merged with defaults.
from_dict(cls, dict config_dict)
Create ModConfig from dictionary (JSON structure)
__init__(self, bool apply, int epochs, int warmup_epochs, numbers.Number lr_act_scale, numbers.Number lr_zeropoint, numbers.Number lr_weight_scale, numbers.Number lr_weight, numbers.Number lr_bias, numbers.Number lr_min_ratio, int batch_size, numbers.Number q_drop, str post_processing, numbers.Number box_conf_thres, numbers.Number box_iou_thres, str loss_type, bool use_outputs, numbers.Number kl_temperature, numbers.Number recon_prob, numbers.Number recon_coeff, numbers.Number lambda_0, numbers.Number lambda_1, numbers.Number lambda_2, List anchors, bool use_xyxy, str save_dir, int seed, List[str] apply_layers, List[str] exclude_layers, str custom_loss_jit_path, str mod_after_layer_name, bool optional=optional)
Initialize the ModConfig.