API Reference: Engine Components¶
Core processing engines coordinating model training loops and inference predictions.
CoreTrainer¶
corecv.engine.trainer.CoreTrainer(model, optimizer, loss_fn, train_dataloader, val_dataloader=None, device=None, gradient_accumulation_steps=1, max_grad_norm=1.0, use_amp=None, amp_dtype=torch.float16, ema_decay=0.9999, ema_start_epoch=0, scheduler=None, scheduler_interval='epoch', log_interval=50, output_dir='./checkpoints', train_metrics=None, val_metrics=None, model_config=None)
¶
Unified training engine for CoreCV models.
Coordinates the complete training loop with support for:
- Automatic Mixed Precision (AMP) via
torch.amp.autocast - Gradient accumulation
- Gradient clipping
- Exponential Moving Average (EMA) of model weights
- Checkpoint save/load with optimizer, scheduler, epoch state
- Metrics integration with
corecv.metricsobjects
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
Module
|
The CoreCV model to train ( |
required |
optimizer
|
Optimizer
|
PyTorch optimizer. |
required |
loss_fn
|
object
|
Loss function (callable taking |
required |
train_dataloader
|
DataLoader
|
Training :class: |
required |
val_dataloader
|
DataLoader | None
|
Optional validation :class: |
None
|
device
|
device | None
|
:class: |
None
|
gradient_accumulation_steps
|
int
|
Number of steps to accumulate
gradients before each optimizer update. Default |
1
|
max_grad_norm
|
float | None
|
Max norm for gradient clipping. |
1.0
|
use_amp
|
bool | None
|
Enable Automatic Mixed Precision. Defaults to |
None
|
amp_dtype
|
dtype
|
AMP computation dtype. Default |
float16
|
ema_decay
|
float | None
|
EMA decay factor. |
0.9999
|
ema_start_epoch
|
int
|
Epoch at which to start updating EMA weights
(allows EMA to begin after a warmup period). Default |
0
|
scheduler
|
object | None
|
Optional LR scheduler. |
None
|
scheduler_interval
|
str
|
When to step the scheduler. One of |
'epoch'
|
log_interval
|
int
|
Log training metrics every |
50
|
output_dir
|
str
|
Directory for checkpoints. Default |
'./checkpoints'
|
train_metrics
|
Module | None
|
Optional metrics object (from |
None
|
val_metrics
|
Module | None
|
Optional metrics object (from |
None
|
model_config
|
dict[str, Any] | None
|
Optional dictionary containing the model configuration
(e.g. architecture hyperparameters). Stored in checkpoints
under the |
None
|
Example::
>>> trainer = CoreTrainer(
... model=model,
... optimizer=optimizer,
... loss_fn=nn.CrossEntropyLoss(),
... train_dataloader=train_loader,
... val_dataloader=val_loader,
... device=torch.device("cuda"),
... )
>>> history = trainer.fit(num_epochs=100)
>>> with trainer.model_ema:
... output = trainer.model(test_inputs)
Initialise the CoreTrainer with model, optimizer, and training configuration.
Source code in src/corecv/engine/trainer.py
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 | |
model_ema
property
¶
Get a context manager that temporarily applies EMA weights.
Use this for inference with EMA-averaged weights::
with trainer.model_ema:
output = trainer.model(input)
The EMA weights are applied to the model upon entering the
with block and automatically restored upon exit.
Returns:
| Name | Type | Description |
|---|---|---|
An |
EMAContext
|
class: |
fit(num_epochs)
¶
Run the complete training loop for a given number of epochs.
For each epoch:
- Calls :meth:
train_one_epoch - Calls :meth:
validate(ifval_dataloaderis available) - Steps the epoch-based scheduler (if configured with
scheduler_interval='epoch') - Saves a checkpoint
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
num_epochs
|
int
|
Number of epochs to train. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, list]
|
History dictionary with keys |
dict[str, list]
|
containing a list of per-epoch metric dictionaries. |
Source code in src/corecv/engine/trainer.py
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 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 | |
load_checkpoint(path, load_optimizer=True, load_scheduler=True, load_ema=True)
¶
Load a training checkpoint from disk.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
File path of the checkpoint. |
required |
load_optimizer
|
bool
|
If |
True
|
load_scheduler
|
bool
|
If |
True
|
load_ema
|
bool
|
If |
True
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
The full checkpoint dictionary (contains at least |
dict[str, Any]
|
|
dict[str, Any]
|
|
dict[str, Any]
|
that was initialised with a |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If the checkpoint file does not exist. |
RuntimeError
|
If the checkpoint is missing a required key. |
Source code in src/corecv/engine/trainer.py
save_checkpoint(path, epoch, metrics)
¶
Save a training checkpoint to disk.
The checkpoint dictionary contains the following keys:
epoch— Current epoch number.model_state_dict— Model parameters.optimizer_state_dict— Optimizer state.scheduler_state_dict— Scheduler state (Noneif not set).ema_state_dict— EMA shadow parameters.scaler_state_dict— AMP gradient scaler state.metrics— User-supplied metrics dictionary.model_config— Model configuration dictionary (Noneif not provided at initialisation).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
File path for the checkpoint. |
required |
epoch
|
int
|
Current epoch number. |
required |
metrics
|
dict[str, Any]
|
Dictionary of metrics to store in the checkpoint (e.g. loss, accuracy, etc.). |
required |
Source code in src/corecv/engine/trainer.py
train_one_epoch(epoch)
¶
Run one training epoch.
Iterates over train_dataloader, computes forward / backward,
accumulates gradients, applies gradient clipping, updates weights,
and optionally updates EMA and scheduler (if
scheduler_interval == 'step').
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
epoch
|
int
|
Current epoch number (1-indexed, used for logging and EMA start condition). |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary of training metrics for the epoch, including at |
dict[str, Any]
|
minimum |
dict[str, Any]
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in src/corecv/engine/trainer.py
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 | |
validate(epoch, use_ema=False)
¶
Run validation on val_dataloader.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
epoch
|
int
|
Current epoch number (used for logging). |
required |
use_ema
|
bool
|
If |
False
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary of validation metrics, including at least |
dict[str, Any]
|
|
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If |
Source code in src/corecv/engine/trainer.py
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 | |
CorePredictor¶
corecv.engine.predictor.CorePredictor(model, task='detection', input_size=(640, 640), mean=_MEAN_DEFAULT, std=_STD_DEFAULT, conf_threshold=0.25, iou_threshold=0.45, topk=5, half_precision=False, compile_model=False, batch_size=8, num_classes=None)
¶
Accelerated inference engine for CoreCV models.
Wraps a CoreCV model and provides a clean predict() / predict_batch()
API with optimised preprocessing, GPU-native post-processing, and
configurable acceleration features.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
Module
|
A CoreCV model ( |
required |
task
|
Literal['classification', 'segmentation', 'detection']
|
The task type. One of |
'detection'
|
input_size
|
tuple[int, int]
|
Target |
(640, 640)
|
mean
|
tuple[float, float, float]
|
Per-channel normalisation mean. Default ImageNet mean. |
_MEAN_DEFAULT
|
std
|
tuple[float, float, float]
|
Per-channel normalisation standard deviation. Default ImageNet std. |
_STD_DEFAULT
|
conf_threshold
|
float
|
Minimum confidence score for detection predictions.
Default |
0.25
|
iou_threshold
|
float
|
IoU threshold for detection NMS. Default |
0.45
|
topk
|
int
|
Number of top predictions for classification. Default |
5
|
half_precision
|
bool
|
Enable FP16 inference via |
False
|
compile_model
|
bool
|
Enable |
False
|
batch_size
|
int
|
Maximum batch size for list/folder inference. Default
|
8
|
num_classes
|
int | None
|
Number of classes for detection heads. If |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Example
predictor = CorePredictor( ... model=my_model, ... task="detection", ... input_size=(640, 640), ... half_precision=True, ... ) results = predictor.predict("photo.jpg") results[0].detection.boxes.shape[1] 4
Initialise the CorePredictor with model and inference configuration.
Source code in src/corecv/engine/predictor.py
predict(source)
¶
Run inference on one or more images.
Accepts a wide variety of input types:
strorPath: interpreted as a single image file path.np.ndarray: a single HWC or CHW image (uint8 or float32).Tensor: a single CHW image tensor.list: a list of any of the above; also supports a list ofTensorobjects for pre-batched input.
When a directory path is given, all images with known extensions inside it are loaded and processed in batches.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
str | Path | ndarray | Tensor | list[str | Path | ndarray | Tensor]
|
Image source(s) as described above. |
required |
Returns:
| Type | Description |
|---|---|
list[Prediction]
|
A list of :class: |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If a file path does not exist. |
TypeError
|
If the input type is unsupported. |
Source code in src/corecv/engine/predictor.py
predict_batch(images)
¶
Run inference on a list of pre-loaded tensors.
Each tensor should be in (C, H, W) format with float values
in [0, 1] or [0, 255]. Tensors are automatically
normalised and batched.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
images
|
list[Tensor]
|
List of image tensors. |
required |
Returns:
| Type | Description |
|---|---|
list[Prediction]
|
A list of :class: |
Source code in src/corecv/engine/predictor.py
register_normalization(mean, std)
¶
Register normalisation constants as module buffers.
The tensors are stored on CPU and broadcast to the input device during preprocessing to avoid repeated allocations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mean
|
tuple[float, float, float]
|
Per-channel mean (RGB). |
required |
std
|
tuple[float, float, float]
|
Per-channel standard deviation (RGB). |
required |
Source code in src/corecv/engine/predictor.py
set_class_labels(labels)
¶
Set human-readable class labels for predictions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
labels
|
list[str]
|
List of label strings, one per class index. |
required |