Перейти к содержанию

Trainer

Trainer trains one or more models for a single pipeline step. It iterates over ModelCandidate entries (or ready nn.Module instances), manages checkpoints, logs progress, and produces a StepTrainResult.

Before training starts, Trainer reads the step's action type and selects the matching implementation from hyppopipe.train.tasks — classification, segmentation, and localization differ in dataloaders and loss computation.

TrainingConfig

Immutable dataclass with hyperparameters:

  • epochs, batch_size, val_batch_size, lr, device
  • optimizer_name / optimizer_kwargs or custom optimizer_factory
  • loss and monitor (see hyppopipe.train.objectives)
  • early_stopping (EarlyStoppingConfig)

Use copy_with(epochs=50) to derive a per-step config from a shared default.

ModelCandidate

Wraps a torchvision model factory and one or more WeightsEnum values so you can compare architectures and pretrained weights in a single train() call without duplicating notebooks.

Export

TrainResult.export(path) writes manifest.json, weights (.pth), and a reports/ folder with training_history.json, loss_curves.png, and monitor_curves.png.

from torchvision.models.detection import (
    FasterRCNN_MobileNet_V3_Large_FPN_Weights,
    fasterrcnn_mobilenet_v3_large_fpn,
)

from hyppopipe.data.dataset import YAMLDataset
from hyppopipe.pipeline import Pipeline, Step
from hyppopipe.pipeline.image.localization import ImageLocalizer
from hyppopipe.train import ModelCandidate, Trainer, TrainingConfig

ds = YAMLDataset("data/brain_tumor/data.yaml")
splits = ds.as_split_data()

pipeline = Pipeline({"localize": Step(ImageLocalizer())})

result = pipeline.train(
    step_config={
        "localize": Trainer(
            data=splits,
            config=TrainingConfig(epochs=15, batch_size=4, lr=5e-4),
            model_candidates=[
                ModelCandidate(
                    fasterrcnn_mobilenet_v3_large_fpn,
                    FasterRCNN_MobileNet_V3_Large_FPN_Weights.DEFAULT,
                ),
            ],
        ),
    },
)

Documentation

Trains one or more models for a pipeline step action.

Example

Train a classification step on a split dataset::

trainer = Trainer([resnet50], data=splits, config=TrainingConfig(epochs=5))
step_result = trainer.train(step=classify_step, step_name="classify")

__init__(model_candidates, data=None, *, config=None, transforms=None, loss=None, monitor=None, ignore_fails=False)

Configure models and defaults for :meth:train.

Parameters:

Name Type Description Default
model_candidates Sequence[Module | ModelCandidate]

Ready modules and/or :class:ModelCandidate factories.

required
data SplitData | None

Optional default :class:~hyppopipe.data.dataset.splits.SplitData.

None
config TrainingConfig | None

Training hyperparameters; defaults to a new :class:TrainingConfig.

None
transforms Any | None

Task-specific train/val data transforms (see hyppopipe.train.transforms).

None
loss LossFactory | None

Loss override; falls back to config.loss, then the task default.

None
monitor MonitorSpec | None

Validation monitor for early stopping; falls back to config.monitor, then validation loss (minimize).

None
ignore_fails bool

If True, log and skip failed candidates instead of raising.

False

train(*, step, step_name, config=None, log_to=None)

Train all model candidates for one pipeline step.

Parameters:

Name Type Description Default
step Step

Step whose action selects the :class:~hyppopipe.train.tasks.base.TrainingTask.

required
step_name str

Key used in logs and result artifacts.

required
config TrainingConfig | None

Optional override of self.config for this call.

None
log_to Path | str | LogConfig | None

Per-run logging configuration.

None

Returns:

Name Type Description
One StepTrainResult

class:~hyppopipe.train.result.ModelRunResult per successful candidate.

Raises:

Type Description
ValueError

If no training data is available.