Skip to content

Commit 335bb10

Browse files
committed
Complete folds before budget decisions and repeat small-data CV
Apply scheduling budgets between completed folds, exclude interrupted candidates, preserve run-wide finishing reserves on resume, and defer repeated unaffordable first-fold pilots within each stage. Use three repeats for automatic five-fold validation on small datasets, disable stacking and BoostOnErrors for repeated validation, and preserve explicit validation settings. Validation: 166 targeted scheduler, CV, interruption, shared-boosting, TFM full-context, and CatBoost checks passed together. TFM networks and neural interruptions are simulated in integration tests.
1 parent 8d80c24 commit 335bb10

17 files changed

Lines changed: 540 additions & 318 deletions

‎supervised/algorithms/catboost.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -215,14 +215,14 @@ def fit(
215215
weight=sample_weight_validation,
216216
)
217217

218-
if self.params.get("num_boost_round") is None:
218+
if self.params.get("num_boost_round") is None and max_time is not None:
219219
model_init, new_iterations = self._assess_iterations(
220220
X, y, sample_weight, eval_set, max_time
221221
)
222222
self.model.set_params(iterations=new_iterations)
223223
else:
224224
model_init = None
225-
self.model.set_params(iterations=self.params.get("num_boost_round"))
225+
self.model.set_params(iterations=self.params.get("num_boost_round") or self.rounds)
226226
self.early_stopping_rounds = self.params.get("early_stopping_rounds", 50)
227227

228228
self.model.fit(

‎supervised/automl.py‎

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -99,8 +99,14 @@ def __init__(
9999
If the `results_path` will point to directory with AutoML results (`params.json` must be present),
100100
then all models will be loaded.
101101
102-
total_time_limit (int): The total time limit in seconds for AutoML training.
102+
total_time_limit (int): The scheduling budget in seconds for AutoML training.
103103
It is not used when `model_time_limit` is not `None`.
104+
Started folds finish normally, so elapsed time can exceed this target.
105+
After the first fold, AutoML estimates whether the remaining folds fit.
106+
Candidates with at least 80% of folds complete may use a finishing reserve
107+
of up to 10% of this budget, shared across the run. When ensembling is
108+
enabled, 5% is reserved for ensemble construction. Incomplete candidates
109+
are excluded from model selection and ensembling.
104110
105111
mode (str): Can be {`Explain`, `Perform`, `Compete`, `Optuna`}. This parameter defines the goal of AutoML and how intensive the AutoML search will be.
106112
@@ -132,7 +138,10 @@ def __init__(
132138
133139
model_time_limit (int): The time limit for training a single model, in seconds.
134140
If `model_time_limit` is set, the `total_time_limit` is not respected.
135-
The single model can contain several learners. The time limit for subsequent learners is computed based on `model_time_limit`.
141+
The single model can contain several learners. This is a scheduling
142+
target checked between completed folds, not a cutoff inside a fit.
143+
A started fold finishes normally; elapsed time may exceed the target.
144+
The global finishing reserve does not apply to this explicit per-model limit.
136145
137146
For example, in the case of 10-fold cross-validation, one model will have 10 learners.
138147
The `model_time_limit` is the time for all 10 learners.
@@ -185,6 +194,12 @@ def __init__(
185194
might be needed inside the custom metric.
186195
187196
validation_strategy (dict): Dictionary with validation type. Right now train/test split and cross-validation are supported.
197+
With automatic validation, datasets below 5,000 training rows or
198+
with fewer than 250 samples in the smallest class use 3 repeats
199+
whenever 5-fold CV is selected, with no additional budget threshold.
200+
Stacking and BoostOnErrors are disabled for these repeated folds.
201+
Explicit validation settings are preserved; short budgets may still
202+
select holdout validation.
188203
189204
Example:
190205

‎supervised/base_automl.py‎

Lines changed: 41 additions & 63 deletions
Original file line numberDiff line numberDiff line change
@@ -416,6 +416,11 @@ def _stacking_descriptor(self, params):
416416

417417
def train_model(self, params):
418418
params.pop("candidate_time_limit", None)
419+
if self._time_ctrl.pilots_deferred(params["learner"]["model_type"], self._fit_level):
420+
raise BudgetExceededError(
421+
"Two unaffordable first-fold pilots; deferring this algorithm for this stage.",
422+
phase="pilot_admission", completed_folds=0,
423+
)
419424
policy = self._algorithm_early_stopping
420425
budgeted = (policy is not None and policy.enabled
421426
and self._fit_level not in ("simple_algorithms", "adjust_validation")
@@ -430,15 +435,6 @@ def train_model(self, params):
430435
raise BudgetExceededError("No affordable exploration allowance remains.",
431436
phase="admission", allowance=allowance)
432437
params["candidate_time_limit"] = allowance
433-
if self._fit_level == "stack":
434-
decision = self._time_ctrl.stacking_cost.decision(
435-
self._stacking_descriptor(params), allowance,
436-
)
437-
if decision:
438-
raise BudgetExceededError(
439-
"Previous stacking timings predict this candidate cannot fit its allowance.",
440-
**decision,
441-
)
442438
expected_time = None
443439
if self._fit_level == "feature_discovery":
444440
expected_time = params.get("feature_discovery_expected_time")
@@ -447,15 +443,8 @@ def train_model(self, params):
447443
if not self._time_ctrl.enough_time(
448444
params["learner"]["model_type"], self._fit_level, expected_time=expected_time
449445
):
450-
if budgeted:
451-
raise BudgetExceededError("Estimated candidate cost exceeds the remaining stage budget.",
452-
phase="admission")
453-
if self._fit_level == "feature_discovery":
454-
self.verbose_print(
455-
f"Skip {params['name']}: insufficient time for the estimated training cost."
456-
)
457-
logger.info(f"Cannot train {params['name']} because of the time constraint")
458-
return False
446+
raise BudgetExceededError("Insufficient scheduling budget to start this candidate.",
447+
phase="admission", completed_folds=0)
459448
# let's create directory to log all training artifacts
460449
results_path, model_subpath = self._results_path, params["name"]
461450
model_path = os.path.join(results_path, model_subpath)
@@ -466,30 +455,8 @@ def train_model(self, params):
466455
{"metric": {"name": self._eval_metric}, "log_to_dir": model_path}
467456
)
468457

469-
# disable for now
470-
max_time_for_learner = 3600
471-
if self._total_time_limit is not None:
472-
k_folds = self._validation_strategy.get("k_folds", 1.0)
473-
at_least_algorithms = 10.0
474-
475-
max_time_for_learner = max(
476-
self._total_time_limit / k_folds / at_least_algorithms, 60
477-
)
478-
479-
params["max_time_for_learner"] = max_time_for_learner
480-
if self._model_time_limit is not None:
481-
params["max_time_for_learner"] = self._model_time_limit / self._expected_learners_cnt()
482-
policy = self._algorithm_early_stopping
483-
if policy is not None and policy.enabled and policy.tuning_step(self._fit_level):
484-
allowance = self._time_ctrl.learner_time_limit(
485-
params["learner"]["model_type"], self._fit_level,
486-
self._expected_learners_cnt(),
487-
)
488-
if allowance is not None:
489-
params["max_time_for_learner"] = allowance
490-
491-
if budgeted:
492-
params["max_time_for_learner"] = params["candidate_time_limit"] / self._expected_learners_cnt()
458+
# Routine runtime limits apply between completed folds.
459+
params["max_time_for_learner"] = None
493460

494461
total_time_constraint = TotalTimeConstraint(
495462
{
@@ -506,6 +473,7 @@ def train_model(self, params):
506473
params,
507474
callbacks=[early_stop, total_time_constraint],
508475
data_store=self._training_store,
476+
training_budget=self._time_ctrl.fold_budget(params.get("candidate_time_limit"), self.verbose_print),
509477
)
510478

511479
# start training
@@ -1154,6 +1122,7 @@ def _configure_auto_cv(self, y):
11541122
reasons.append("smallest class has fewer than 250 samples")
11551123
self._auto_cv_policy = {
11561124
"max_folds": 5 if reasons else 10,
1125+
"repeats": 3 if reasons else 1,
11571126
"training_rows": rows,
11581127
"smallest_class_count": smallest_class,
11591128
"reason": "; ".join(reasons) if reasons else "sufficient rows and class counts for 10 folds",
@@ -1163,6 +1132,15 @@ def _configure_auto_cv(self, y):
11631132
f"({self._auto_cv_policy['reason']}); time budget may reduce validation."
11641133
)
11651134

1135+
def _apply_auto_cv_repeats(self, strategy):
1136+
if (self.validation_strategy == "auto"
1137+
and self._auto_cv_policy is not None
1138+
and self._auto_cv_policy["max_folds"] == 5
1139+
and strategy.get("validation_type") == "kfold"
1140+
and strategy.get("k_folds") == 5):
1141+
strategy["repeats"] = 3
1142+
strategy.setdefault("random_seed", 1906)
1143+
11661144
def _set_adjusted_validation(self):
11671145
if self._validation_strategy["validation_type"] != "split":
11681146
return
@@ -1185,16 +1163,10 @@ def _set_adjusted_validation(self):
11851163
if self._auto_cv_policy is not None:
11861164
self._auto_cv_policy["time_budget_folds"] = k_folds
11871165
k_folds = min(k_folds, self._auto_cv_policy["max_folds"])
1188-
# too small dataset for stacking
1189-
if self.n_rows_in_ < 500:
1190-
self._stack_models = False
1191-
self.verbose_print(
1192-
"*** Disable stacking for small dataset (nrows < 500)"
1193-
)
1194-
11951166
self._validation_strategy["validation_type"] = "kfold"
11961167
del self._validation_strategy["train_ratio"]
11971168
self._validation_strategy["k_folds"] = k_folds
1169+
self._apply_auto_cv_repeats(self._validation_strategy)
11981170
self.tuner._validation_strategy = self._validation_strategy
11991171
shutil.rmtree(
12001172
os.path.join(self._results_path, self._model_subpaths[0]),
@@ -1209,15 +1181,17 @@ def _set_adjusted_validation(self):
12091181
cv += ["Shuffle"]
12101182
if self._validation_strategy.get("stratify", False):
12111183
cv += ["Stratify"]
1212-
self.select_and_save_best() # save validation strategy
1184+
self._apply_constraints_stack_models()
1185+
self.select_and_save_best() # save validation strategy and its constraints
12131186

1214-
self.verbose_print(f"Validation strategy: {k_folds}-fold CV {','.join(cv)}")
1187+
repeats = self._validation_strategy.get("repeats", 1)
1188+
self.verbose_print(f"Validation strategy: {k_folds}-fold CV, {repeats} repeat(s), {','.join(cv)}")
12151189
else:
12161190
# cant stack models for train/test split
12171191
self._stack_models = False
12181192
self.verbose_print("Disable stacking for split validation")
12191193

1220-
self._apply_constraints_stack_models()
1194+
self._apply_constraints_stack_models()
12211195

12221196
def _apply_class_balance_stacking_constraint(self, y):
12231197
"""Avoid stacking when a classification target has a class below 15%."""
@@ -1244,7 +1218,11 @@ def _apply_constraints_stack_models(self):
12441218
self._stack_models = False
12451219
self._boost_on_errors = False
12461220
if "repeats" in self._validation_strategy:
1247-
if self._stack_models:
1221+
if (self.validation_strategy == "auto" and self._auto_cv_policy is not None
1222+
and self._auto_cv_policy["max_folds"] == 5
1223+
and self._validation_strategy.get("repeats") == 3):
1224+
self.verbose_print("Small dataset: stacking disabled; using 5-fold CV with 3 repeats.")
1225+
elif self._stack_models:
12481226
self.verbose_print("Disable stacking for repeated validation")
12491227
self._stack_models = False
12501228
self._boost_on_errors = False
@@ -1535,15 +1513,15 @@ def _fit_with_store(
15351513
self.verbose_print(f"Skip {step} because of the time limit.")
15361514
continue
15371515
else:
1538-
pending_count = sum(p.get("status") not in ("trained", "skipped", "error")
1516+
pending_count = sum(p.get("status") not in ("trained", "skipped", "error", "not_trained", "not_started")
15391517
for p in generated_params)
15401518
model_str = "models" if pending_count != 1 else "model"
15411519
self.verbose_print(
15421520
f"* Step {step} will try to check up to {pending_count} {model_str}"
15431521
)
15441522

15451523
for params in generated_params:
1546-
if params.get("status", "") in ["trained", "skipped", "error"]:
1524+
if params.get("status", "") in ["trained", "skipped", "error", "not_trained", "not_started"]:
15471525
if "algorithm_early_stopping" not in params:
15481526
self.verbose_print(f"{params['name']}: {params['status']}.")
15491527
continue
@@ -1561,7 +1539,7 @@ def _fit_with_store(
15611539
if policy.enabled and policy.tuning_step(step):
15621540
self._time_ctrl.set_active_algorithms(step, {
15631541
p["learner"]["model_type"] for p in generated_params
1564-
if p.get("status") not in ("trained", "skipped", "error")
1542+
if p.get("status") not in ("trained", "skipped", "error", "not_trained", "not_started")
15651543
and policy.decision(step, p) is None
15661544
})
15671545

@@ -1593,17 +1571,15 @@ def _fit_with_store(
15931571

15941572
except BudgetExceededError as e:
15951573
outcome = "budget_exhausted"
1596-
params.update(status="skipped", final_loss=None, train_time=None)
1574+
started = e.details.get("phase") not in (
1575+
"admission", "pilot_admission", "stacking_admission")
1576+
params.update(status="not_trained" if started else "not_started",
1577+
final_loss=None, train_time=None)
15971578
params["budget_skip"] = {
15981579
"reason": str(e), "elapsed": time.monotonic() - attempt_start,
15991580
"allowance": params.get("candidate_time_limit"), **e.details,
16001581
}
1601-
if step == "stack" and e.details.get("completed_folds", 0) > 0:
1602-
self._time_ctrl.stacking_cost.observe(
1603-
params["name"], self._stacking_descriptor(params),
1604-
e.details["elapsed"], e.details["completed_folds"],
1605-
e.details["expected_folds"], e.details.get("dimensions"),
1606-
)
1582+
self.verbose_print(f"Skip {params.get('name')}: {e}")
16071583
except CandidateValidationError as e:
16081584
params.update(status="skipped", final_loss=None, train_time=None)
16091585
params["candidate_skip"] = dict(
@@ -1639,6 +1615,7 @@ def _fit_with_store(
16391615
self._time_ctrl.record_attempt(
16401616
params["name"], params["learner"]["model_type"], step,
16411617
time.monotonic() - attempt_start, outcome, configuration,
1618+
params.get("budget_skip"),
16421619
)
16431620

16441621
self.save_progress(step, generated_params)
@@ -2360,6 +2337,7 @@ def _get_validation_strategy(self):
23602337
}
23612338
if strat.get("validation_type") == "kfold" and self._auto_cv_policy is not None:
23622339
strat["k_folds"] = min(strat["k_folds"], self._auto_cv_policy["max_folds"])
2340+
self._apply_auto_cv_repeats(strat)
23632341
if self._get_ml_task() == REGRESSION:
23642342
if "stratify" in strat:
23652343
# it's better to always check
Lines changed: 4 additions & 67 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,10 @@
1-
import logging
2-
import time
1+
"""Legacy callback metadata; scheduling is enforced at fold boundaries.
32
4-
import numpy as np
3+
ModelFramework and FoldBudget own the stopping decisions, including finishing
4+
reserve and candidate completion tracking. This callback never truncates a fit.
5+
"""
56

67
from supervised.callbacks.callback import Callback
7-
from supervised.exceptions import BudgetExceededError
8-
from supervised.utils.config import LOG_LEVEL
9-
10-
log = logging.getLogger(__name__)
11-
log.setLevel(LOG_LEVEL)
128

139

1410
class TotalTimeConstraint(Callback):
@@ -18,62 +14,3 @@ def __init__(self, params={}):
1814
self.total_time_limit = params.get("total_time_limit")
1915
self.total_time_start = params.get("total_time_start")
2016
self.expected_learners_cnt = params.get("expected_learners_cnt", 1)
21-
22-
def on_learner_train_start(self, logs):
23-
self.train_start_time = time.time()
24-
25-
def on_learner_train_end(self, logs):
26-
if (
27-
self.total_time_limit is not None
28-
and len(self.learners) == 1
29-
and self.expected_learners_cnt > 1
30-
# just check for the first learner
31-
# need to have more than 1 learner
32-
# otherwise it is a finish of the training
33-
):
34-
one_fold_time = time.time() - self.train_start_time
35-
estimate_all_folds = one_fold_time * self.expected_learners_cnt
36-
37-
total_elapsed_time = np.round(time.time() - self.total_time_start, 2)
38-
39-
# we need to add time for the rest of learners (assuming that all folds training time is the same)
40-
estimate_elapsed_time = total_elapsed_time + one_fold_time * (
41-
self.expected_learners_cnt - 1
42-
)
43-
44-
if estimate_elapsed_time >= self.total_time_limit:
45-
raise BudgetExceededError(
46-
"Stop training after the first fold. "
47-
f"Time needed to train on the first fold {np.round(one_fold_time)} seconds. "
48-
"The time estimate for training on all folds is larger than total_time_limit."
49-
)
50-
if (
51-
self.total_time_limit is not None
52-
and len(self.learners) < self.expected_learners_cnt
53-
# dont stop for last learner, we are finishing anyway
54-
):
55-
total_elapsed_time = np.round(time.time() - self.total_time_start, 2)
56-
57-
if total_elapsed_time > self.total_time_limit + 600:
58-
# add 10 minutes of margin
59-
# margin is added because of unexpected time changes
60-
# if training on each fold will be the same
61-
# then the training will be stopped after first fold (above condition)
62-
raise BudgetExceededError(
63-
"Force to stop the training. "
64-
"Total time for AutoML training already exceeded."
65-
)
66-
67-
def on_iteration_end(self, logs, predictions):
68-
total_elapsed_time = np.round(time.time() - self.total_time_start, 2)
69-
70-
if self.total_time_limit is not None:
71-
log.debug(
72-
f"Total elapsed time {total_elapsed_time} seconds. "
73-
+ f"Time left {np.round(self.total_time_limit - total_elapsed_time, 2)} seconds."
74-
)
75-
# not time left, stop now
76-
if total_elapsed_time >= self.total_time_limit:
77-
self.learner.stop_training = True
78-
else:
79-
log.debug(f"Total elapsed time {total_elapsed_time} seconds")

0 commit comments

Comments
 (0)