Property training wrapper
Bases: Module
Train a task model to satisfy general input-output specifications.
Each PropertySpec associates an affine/Boolean output formula with closed input boxes. Lower satisfaction margins extend the classification-margin formulation used for local robustness to these general properties. The verification graph shares the task network's parameters and may append fixed operations, such as known state-transition dynamics.
Training minimises task loss plus the selected weighted property loss.
Bound methods penalize lower margins; adversarial and hybrid methods use
pointwise or combined surrogates. A low training loss does not establish a
certificate: use certify_properties to check every covering cell afresh.
Both training and verification use evaluation-mode model behaviour, with
gradients enabled during training and caller modes restored afterwards.
Epoch checks use the training bound method, GLS's configured training bound,
or sound full-box IBP for other methods; no separate selector is required.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
Module
|
Task model to optimise and return from training. |
required |
input_shape
|
tuple[int, ...]
|
Task input shape, excluding the batch axis. |
required |
properties
|
Iterable[PropertySpec]
|
Nonempty specifications with unique names. Copied at construction to isolate them from caller mutation. |
required |
task_loss
|
Callable
|
Loss called as |
required |
num_epochs
|
int
|
Total trajectory length, also the default training end. |
required |
training_method
|
str
|
IBP, CROWN-IBP, CROWN, MTL-IBP, CC-IBP, EXP-IBP, SABR, PGD, IBP-R or GLS. Defaults to CROWN-IBP. Hybrid, adversarial, regularized and smoothed property methods are experimental adaptations, not established paper reproductions. |
'CROWN-IBP'
|
verification_model
|
Module | None
|
Graph whose outputs the
formulas reference. Defaults to |
None
|
verification_input_shape
|
tuple[int, ...] | None
|
Verification input
shape without the batch axis; defaults to |
None
|
device
|
str | device
|
Model and training device; defaults to CPU. |
'cpu'
|
lr
|
float
|
Positive optimiser learning rate. |
0.001
|
optimizer_func
|
Callable
|
Optimizer constructor accepting model
parameters and |
Adam
|
lr_scheduler_func
|
Callable | None
|
Optional scheduler constructor. The trainer steps it once after each epoch. |
None
|
lr_scheduler_kwargs
|
dict | None
|
Scheduler constructor arguments. |
None
|
property_weight
|
float
|
Nonnegative multiplier of the property loss. |
1.0
|
margin
|
float
|
Positive target lower margin for the hinge penalty. Logical certification instead requires a lower margin above zero. |
0.001
|
weight_ramp_epochs
|
int
|
Epochs after warm-up for linearly increasing
the property weight from zero to |
0
|
property_batch_size
|
int
|
Number of covering cells sampled with replacement per task batch; also the bound-evaluation batch size. |
32
|
refinement
|
bool
|
Split uncertified cells after each epoch, then reevaluate the refined cover. Defaults to False. |
False
|
split_count
|
int
|
Maximum number of cells split per epoch. Each split adds one cell and divides the parent's sampling weight equally. |
8
|
max_cells
|
int
|
Refinement cell limit per original input box, not a limit on the total cover across all specifications. |
1024
|
max_depth
|
int
|
Maximum number of splits along a cell's lineage. |
12
|
population_bn
|
bool
|
Recalibrate task-model BatchNorm statistics on training inputs after each epoch, before selection. Otherwise running statistics stay fixed during training. |
False
|
checkpoint_save_path
|
str | Path | None
|
Optional directory for resumable epoch checkpoints. Existing files are not overwritten. |
None
|
checkpoint_save_interval
|
int
|
Save every this many completed epochs and at the end of each training call. |
10
|
bound_opts
|
dict | None
|
auto_LiRPA options. |
None
|
training_options
|
dict | None
|
Parameters of the selected method, copied and validated before conversion. Supports loss='hinge' or 'cross_entropy' and optional gradient_clip for all methods. Hybrids support PGD controls and ReLU retention; expressive methods add alpha, CROWN-IBP adds beta, SABR adds subselection_ratio, IBP-R adds rho/masking, and GLS adds estimator, samples, sigma, sigma_lr and scale decay. See the property guide for defaults and the support table. |
None
|
property_dataset
|
Sequence[Box] | None
|
Optional finite, indexable box
pool generated on demand for a single property formula. Must expose
|
None
|
warm_up_epochs
|
int
|
Initial epochs optimizing only the task loss.
No property regions, bounds or attacks are computed in this phase.
Defaults to zero. Included in |
0
|
match_property_batch_size
|
bool
|
Sample as many property boxes as
actual task examples in each update, including the final partial
batch. |
False
|
Attributes:
| Name | Type | Description |
|---|---|---|
original_model |
Module
|
Task model sharing verification weights. |
partition |
list[dict]
|
Covering cells with lineage and sampling weights.
Every original box starts with equal weight; overlapping boxes are
still separate sampling regions. Empty when |
epoch |
int
|
Number of completed trajectory epochs. |
history |
list[dict]
|
Per-epoch task/property losses, validation loss, whole-cover certification flag, cell count and minimum lower bound. |
configuration |
dict
|
Serializable property and training configuration used to reject incompatible checkpoints. |
inference_selected |
bool
|
True after restoring validation-selected weights. Reload an epoch checkpoint before resuming the trajectory. |
Source code in CTRAIN/model_wrappers/certified/property_model_wrapper.py
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 | |
best_score
property
writable
Best validation-selection score retained by the training state.
best_weights
property
writable
Inference weights associated with the best validation-selection score.
epoch
property
writable
Number of completed epochs in the property-training trajectory.
history
property
writable
Per-epoch task losses, property losses and whole-cover diagnostics.
inference_selected
property
writable
Whether validation-selected inference weights have replaced trajectory weights.
loader_rng
property
writable
Pending loader-generator state to restore on the next training call.
partition
property
writable
Current covering cells and their split lineages and sampling weights.
certify_properties(**kwargs)
Compute fresh bounds on every obligation in the declared domain cover.
Keyword arguments are forwarded to
CTRAIN.eval.properties.certify_properties. Useful options are method
(defaults to CROWN, independently of the training method), refine
(defaults to True), and max_cells/max_depth.
properties=[...] evaluates separate specifications, starting from their
original boxes with fresh bound graphs and the same bound options. This
leaves the training properties and partition unchanged.
method='ALPHA-CROWN' optimises slopes; set its iteration budget through
bound_opts={'optimize_bound_args': {'iteration': 100}} at construction.
This method is available for certification, not training. complete=True enables
alpha-beta-CROWN fallback and requires results_path; timeout is the
solver time limit per unresolved cell. Evaluation refinement does not
replace the stored training partition.
For a lazy property_dataset, the default evaluates every dataset box
and returns aggregate counts and margins. Refinement and complete
verification require explicit properties=[...]. Checkpoints retain
the dataset descriptor rather than its materialized boxes.
Returns:
| Type | Description |
|---|---|
dict
|
Whole-cover |
Source code in CTRAIN/model_wrappers/certified/property_model_wrapper.py
353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 | |
forward(inputs)
Return task-model predictions, without appending property margins.
Source code in CTRAIN/model_wrappers/certified/property_model_wrapper.py
304 305 306 | |
load_checkpoint(path)
Restore a trusted epoch checkpoint and return this wrapper.
Reconstruct the same model, verification graph and task loss before loading. Property/training configuration must match. This restores the trajectory, optimiser/scheduler, validated cover, history and RNG state; loader generator restoration is deferred until the next training call. It also clears the inference-selection guard and synchronizes bound graph buffers. Arbitrary multi-worker/CUDA determinism is not guaranteed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Trusted local checkpoint. Loading uses Python deserialization because the checkpoint includes RNG state. |
required |
Returns:
| Type | Description |
|---|---|
PropertyModelWrapper
|
This wrapper, ready to resume training. |
Raises:
| Type | Description |
|---|---|
ValueError
|
Configuration differs or the saved partition fails to cover the declared input boxes. |
Source code in CTRAIN/model_wrappers/certified/property_model_wrapper.py
408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 | |
save_checkpoint(path, train_loader=None)
Save the current training trajectory to a new file.
Includes model, optimiser/scheduler, partition, epoch, selection history and Python/NumPy/PyTorch RNG states. When supplied, the loader's explicit generator state is saved too. Automatic epoch saves occur before validation-selected inference weights are restored.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
New checkpoint filename. |
required |
train_loader
|
DataLoader | None
|
Optional loader whose explicit generator should be included for resumption. |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
Validation-selected weights have replaced trajectory weights. Load an epoch checkpoint before saving a trajectory. |
FileExistsError
|
The destination already exists. |
Source code in CTRAIN/model_wrappers/certified/property_model_wrapper.py
387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 | |
train_model(train_loader, val_loader=None, start_epoch=None, end_epoch=None, *, epoch_metrics=None)
Train the wrapped model using the configured method and schedule.
The wrapper forwards its configuration to the corresponding library trainer. start_epoch and end_epoch select a segment of the full schedule, retaining its original warm-up, ramp-up and learning-rate milestones.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
train_loader
|
DataLoader
|
Nonempty loader of
|
required |
val_loader
|
DataLoader | None
|
Optional task-loss validation loader. Enables model selection: certification first, then validation loss; before certification, minimum lower bound first and validation loss as a tie-breaker. |
None
|
start_epoch
|
int | None
|
Zero-based starting epoch. Defaults to the
completed |
None
|
end_epoch
|
int | None
|
Exclusive ending epoch; defaults to
|
None
|
epoch_metrics
|
callable | None
|
Optional function of the task model
returning a JSON-serializable metrics dict after each epoch.
These diagnostics do not participate in model selection.
History is logged to |
None
|
Returns:
| Type | Description |
|---|---|
Module
|
Validation-selected task model when a validation loader is supplied; otherwise the final trajectory model. Its caller mode is restored. Optimizer state is not rewound on selection. |
Source code in CTRAIN/model_wrappers/certified/property_model_wrapper.py
308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 | |