API Reference: CoreModel¶
High-level unified interface for CoreCV models. Wraps model initialization, training loops, inference pipelines, and model export formats under a single facade.
CoreModel¶
corecv.api.model.CoreModel(model, task=None, input_size=_DEFAULT_INPUT_SIZE, device=None, num_classes=None, pretrained=True, neck=None, head=None, **kwargs)
¶
High-level unified API facade for CoreCV models.
Wraps any CoreCV model (classification, segmentation, or detection) and exposes a single entry point for training, inference, and export through delegation to specialised engines.
Engines are created lazily — no heavyweight initialisation happens until the corresponding method is called.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
Module | str | Path | dict[str, Any]
|
One of:
|
required |
task
|
Literal['classification', 'segmentation', 'detection'] | None
|
Task type. One of |
None
|
input_size
|
tuple[int, int]
|
Input image dimensions |
_DEFAULT_INPUT_SIZE
|
device
|
device | None
|
Target :class: |
None
|
num_classes
|
int | None
|
Number of output classes. If |
None
|
Example
import torch from corecv.api import CoreModel from corecv.models import CoreObjectDetector
detector = CoreObjectDetector(...) model = CoreModel(detector, task="detection", input_size=(640, 640))
Fluent configuration¶
(model ... .set_loss_fn(torch.nn.CrossEntropyLoss()) ... .set_train_dataloader(train_loader) ... .set_val_dataloader(val_loader))
Train¶
history = model.train(epochs=50, lr=0.001, batch_size=16)
Predict¶
results = model.predict("test.jpg", conf_threshold=0.5)
Export¶
paths = model.export(format="onnx", target_hardware="edge")
Initialise the CoreModel facade.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
Module | str | Path | dict[str, Any]
|
A CoreCV model ( |
required |
task
|
Literal['classification', 'segmentation', 'detection'] | None
|
Task type discriminant. If |
None
|
input_size
|
tuple[int, int]
|
Input |
_DEFAULT_INPUT_SIZE
|
device
|
device | None
|
Target device (auto-detected if |
None
|
num_classes
|
int | None
|
Number of output classes (inferred if |
None
|
pretrained
|
bool
|
Whether to load pretrained backbone weights. |
True
|
neck
|
str | None
|
Registered neck name (e.g. |
None
|
head
|
str | None
|
Registered head name (e.g. |
None
|
**kwargs
|
Any
|
Additional configuration entries forwarded to component constructors and stored for training execution. |
{}
|
Source code in src/corecv/api/model.py
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 | |
device
property
¶
Return the target :class:torch.device.
input_size
property
¶
Return the input (height, width) used for preprocessing.
model
property
¶
Return the wrapped CoreCV model.
num_classes
property
¶
Return the number of output classes, or None if unknown.
predictor
property
¶
Return the internal :class:CorePredictor instance.
None until :meth:predict is called.
task
property
¶
Return the task type.
One of "classification", "segmentation", or "detection".
trainer
property
¶
Return the internal :class:CoreTrainer instance.
None until :meth:train is called.
export(format='onnx', target_hardware='server', opset=_DEFAULT_OPSET, optimize=True, output_path=None, input_shape=None, dynamic_axes=None, weights=None)
¶
Export the model to ONNX and/or ExecuTorch format.
Delegates to :class:CoreExporter which internally uses
:class:TargetRewriter (for edge-hardware graph rewrites)
and :class:MetaProber (for zero-VRAM shape validation).
The export pipeline is:
- Rewrite — When
target_hardware='edge', applies activation replacements (GELU -> ReLU, SiLU -> Hardswish) and collapses redundant layout permutations. - Validate — Runs shape propagation on
device='meta'and audits the graph for dynamic operations. - Export — Serialises to
.onnxand/or.pte.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
format
|
str
|
Export target. One of |
'onnx'
|
target_hardware
|
str
|
Hardware profile. |
'server'
|
opset
|
int
|
ONNX opset version ( |
_DEFAULT_OPSET
|
optimize
|
bool
|
When |
True
|
output_path
|
str | None
|
Explicit output file path. For |
None
|
input_shape
|
tuple[int, ...] | None
|
Input tensor shape |
None
|
dynamic_axes
|
dict[str, dict[int, str]] | None
|
ONNX-style dynamic axes dictionary.
|
None
|
weights
|
str | Path | None
|
Optional path to a |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, str]
|
A dictionary mapping format names to file paths, e.g. |
dict[str, str]
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If any parameter is invalid. |
RuntimeError
|
If validation or export fails. |
Example::
>>> # ONNX for server
>>> paths = model.export(format="onnx", target_hardware="server")
>>> paths["onnx"]
'.../model_20260723_021130.onnx'
>>> # ExecuTorch for edge with rewrites
>>> paths = model.export(
... format="executorch",
... target_hardware="edge",
... opset=18,
... )
>>> paths["executorch"]
'.../model_20260723_021131.pte'
>>> # Both formats
>>> paths = model.export(format="both")
>>> list(paths.keys())
['onnx', 'executorch']
>>> # Load weights before export
>>> paths = model.export(format="onnx", weights="best.pt")
Source code in src/corecv/api/model.py
906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 | |
from_pretrained(path, device=None)
classmethod
¶
Load a pretrained model from a checkpoint file.
The checkpoint must contain a model_config key (a dictionary
describing the architecture) and a model_state_dict key
containing the trained weights. The architecture is rebuilt from
model_config, the weights are loaded, and a fully-configured
:class:CoreModel instance is returned.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Path to a |
required |
device
|
device | None
|
Target device. If |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
A |
CoreModel
|
class: |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If the checkpoint file does not exist. |
KeyError
|
If the checkpoint is missing |
RuntimeError
|
If the checkpoint cannot be loaded. |
Source code in src/corecv/api/model.py
508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 | |
predict(source, conf_threshold=None, iou_threshold=None, topk=None, half_precision=False, compile_model=False, batch_size=8, weights=None)
¶
Run inference on one or more images.
Delegates to :class:CorePredictor which handles preprocessing,
GPU-native post-processing, and batching.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
str | Path | Tensor | list[str | Path | Tensor]
|
Input source — a single image path, a list of paths,
a |
required |
conf_threshold
|
float | None
|
Minimum confidence score for detection
predictions. |
None
|
iou_threshold
|
float | None
|
IoU threshold for NMS in detection.
|
None
|
topk
|
int | None
|
Number of top predictions for classification.
|
None
|
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
|
weights
|
str | Path | None
|
Optional path to a |
None
|
Returns:
| Type | Description |
|---|---|
list[Prediction]
|
A list of :class: |
Example::
>>> # Single image
>>> preds = model.predict("photo.jpg", topk=5)
>>> print(preds[0].classification.class_ids)
>>> # Batch of tensors
>>> batch = torch.randn(4, 3, 224, 224)
>>> preds = model.predict(list(batch))
>>> # Load weights before prediction
>>> preds = model.predict("photo.jpg", weights="best.pt")
Source code in src/corecv/api/model.py
823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 | |
set_loss_fn(loss_fn)
¶
Set the loss function for training.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
loss_fn
|
object
|
A callable |
required |
Returns:
| Type | Description |
|---|---|
CoreModel
|
|
Source code in src/corecv/api/model.py
set_train_dataloader(loader)
¶
Set the training :class:DataLoader.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
loader
|
DataLoader
|
Training data loader. |
required |
Returns:
| Type | Description |
|---|---|
CoreModel
|
|
set_val_dataloader(loader)
¶
Set the validation :class:DataLoader.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
loader
|
DataLoader
|
Validation data loader. |
required |
Returns:
| Type | Description |
|---|---|
CoreModel
|
|
train(config=None, *, target_hardware='server', **kwargs)
¶
train(
config: dict[str, Any],
*,
target_hardware: str = "server",
**kwargs: object,
) -> dict[str, list]
Train the model with the given configuration.
Accepts a polymorphic config argument:
str— Path to a.yamlconfiguration file.dict— Configuration dictionary.- :class:
TrainingConfig— A validated dataclass instance. None— All parameters are provided via**kwargs.
In all cases, keyword arguments take precedence over values in
config (when both are present).
Required pre-conditions (must be set before calling train):
- A train :class:
DataLoadervia :meth:set_train_dataloaderor passed viaconfig. - A loss function via :meth:
set_loss_fn.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
str | dict[str, Any] | TrainingConfig | None
|
Path to a |
None
|
target_hardware
|
str
|
Hardware profile. |
'server'
|
**kwargs
|
object
|
Additional or overriding training hyperparameters.
See :class: |
{}
|
Returns:
| Type | Description |
|---|---|
dict[str, list]
|
A history dictionary with keys |
dict[str, list]
|
each containing a list of per-epoch metric dictionaries. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If configuration validation fails or required components are missing. |
RuntimeError
|
If the training engine encounters an error. |
Example::
>>> # Keyword arguments
>>> history = model.train(epochs=10, lr=0.001, batch_size=64)
>>> # Dictionary
>>> history = model.train({"epochs": 10, "lr": 0.001})
>>> # YAML file
>>> history = model.train("configs/train.yaml")
>>> # Dataclass
>>> cfg = TrainingConfig(epochs=10, lr=0.001)
>>> history = model.train(cfg)
>>> # Mixed (kwargs override dict)
>>> history = model.train({"epochs": 10}, batch_size=128)
Source code in src/corecv/api/model.py
669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 | |
TrainingConfig¶
corecv.api.model.TrainingConfig(*, epochs=_DEFAULT_EPOCHS, lr=_DEFAULT_LR, batch_size=_DEFAULT_BATCH_SIZE, optimizer=_DEFAULT_OPTIMIZER, scheduler=None, amp=True, grad_accum=1, clip_grad=1.0, ema=True, ema_decay=0.9999, device=None, output_dir='./checkpoints', target_hardware='server')
dataclass
¶
Validated training hyperparameter configuration.
All fields are validated in __post_init__.
Attributes:
| Name | Type | Description |
|---|---|---|
epochs |
int
|
Number of training epochs. Must be |
lr |
float
|
Learning rate. Must be |
batch_size |
int
|
Batch size per device. Must be |
optimizer |
str
|
Optimizer name. One of |
scheduler |
str | None
|
Scheduler name. One of |
amp |
bool
|
Enable automatic mixed precision. Default |
grad_accum |
int
|
Gradient accumulation steps. Must be |
clip_grad |
float | None
|
Max gradient norm for clipping. |
ema |
bool
|
Enable exponential moving average. Default |
ema_decay |
float
|
EMA decay factor. Must be in |
device |
str | None
|
Target device string (e.g. |
output_dir |
str
|
Directory for checkpoints and logs. |
target_hardware |
str
|
Hardware profile. |
__post_init__()
¶
Validate training configuration fields.
Source code in src/corecv/api/model.py
ExportConfig¶
corecv.api.model.ExportConfig(*, format='onnx', target_hardware='server', opset=_DEFAULT_OPSET, optimize=True, output_path=None, input_shape=(1, 3, *_DEFAULT_INPUT_SIZE), dynamic_axes=None)
dataclass
¶
Validated export configuration.
All fields are validated in __post_init__.
Attributes:
| Name | Type | Description |
|---|---|---|
format |
str
|
Export format. One of |
target_hardware |
str
|
Target hardware profile. |
opset |
int
|
ONNX opset version. Must be |
optimize |
bool
|
Apply additional graph optimisations (rewrites,
layout folding, delegate passes). Default |
output_path |
str | None
|
Explicit output file path. If |
input_shape |
tuple[int, ...]
|
Input tensor shape |
dynamic_axes |
dict[str, dict[int, str]] | None
|
ONNX-style dynamic axes dictionary, e.g.
|
__post_init__()
¶
Validate export configuration fields.