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

Trainer

Trainer обучает одну или несколько моделей для отдельного шага пайплайна. Перебирает записи ModelCandidate (или готовые экземпляры nn.Module), управляет контрольными точками, журналирует прогресс и формирует StepTrainResult.

Перед началом обучения Trainer определяет тип action шага и выбирает реализацию из hyppopipe.train.tasks — для классификации, сегментации и локализации отличаются загрузчики данных и расчёт loss.

TrainingConfig

Неизменяемый dataclass с гиперпараметрами:

  • epochs, batch_size, val_batch_size, lr, device
  • optimizer_name / optimizer_kwargs или пользовательский optimizer_factory
  • loss и monitor (см. hyppopipe.train.objectives)
  • early_stopping (EarlyStoppingConfig)

Метод copy_with(epochs=50) создаёт конфигурацию для отдельного шага на основе общего шаблона.

ModelCandidate

Оборачивает фабрику модели torchvision и один или несколько WeightsEnum, чтобы сравнивать архитектуры и предобученные веса в одном вызове train() без дублирования ноутбуков.

Экспорт

TrainResult.export(path) записывает manifest.json, веса (.pth) и папку reports/ с training_history.json, loss_curves.png и 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,
                ),
            ],
        ),
    },
)

Документация

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.