Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions models/unet_segmentation/pipeline.py
Original file line number Diff line number Diff line change
Expand Up @@ -276,6 +276,7 @@ def train_model(
max_grad_norm = hyperparameters.get("max_grad_norm", 1.0)
scheduler_name = hyperparameters.get("scheduler", "cosine")
freeze_encoder = hyperparameters.get("freeze_encoder", True)
early_stop_patience = int(hyperparameters.get("early_stop_patience", 5))
seed = split_info["seed"]

with mlflow_training_context(hyperparameters, model_name, base_model_id, dataset_id):
Expand Down Expand Up @@ -327,6 +328,10 @@ def train_model(

train_losses: list[float] = []
val_losses: list[float] = []
best_val_loss = float("inf")
best_epoch = 0
best_state: dict[str, Any] | None = None
epochs_without_improvement = 0

model.train()
for epoch in range(epochs):
Expand Down Expand Up @@ -358,6 +363,21 @@ def train_model(
msg = f"epoch {epoch + 1}/{epochs} train_loss={avg_train_loss:.4f} val_loss={avg_val_loss:.4f}"
print(msg, flush=True)

if avg_val_loss < best_val_loss:
best_val_loss = avg_val_loss
best_epoch = epoch + 1
best_state = {k: v.detach().cpu().clone() for k, v in model.state_dict().items()}
epochs_without_improvement = 0
else:
epochs_without_improvement += 1
if early_stop_patience > 0 and epochs_without_improvement >= early_stop_patience:
print(f"early stopping at epoch {epoch + 1} (best epoch {best_epoch})", flush=True)
break

if best_state is not None:
model.load_state_dict(best_state)
log_metadata(metadata={"best_epoch": best_epoch, "best_val_loss": best_val_loss})

from fair.zenml.metrics import log_loss_history

log_loss_history(train_losses, val_losses)
Expand Down
15 changes: 12 additions & 3 deletions models/unet_segmentation/stac-item.json
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,8 @@
}
],
"mlm:hyperparameters": {
"training.epochs": 5,
"training.epochs": 30,
"training.early_stop_patience": 5,
"training.batch_size": 4,
"training.learning_rate": 0.0001,
"training.weight_decay": 0.0001,
Expand All @@ -197,10 +198,18 @@
{
"key": "epochs",
"type": "int",
"default": 5,
"default": 30,
"min": 1,
"max": 500,
"description": "Number of training epochs"
"description": "Maximum number of training epochs; early stopping usually ends training sooner"
},
{
"key": "early_stop_patience",
"type": "int",
"default": 5,
"min": 0,
"max": 100,
"description": "Stop training after this many epochs without validation-loss improvement and restore the best epoch's weights; 0 disables early stopping"
},
{
"key": "batch_size",
Expand Down