From 0c3d735d51c20dda4f1e80531c985c6c1e4dca93 Mon Sep 17 00:00:00 2001 From: Alvaropar Date: Fri, 20 Nov 2026 15:28:39 +0800 Subject: [PATCH] fix(models): default random_state to None in build_model and TabularDataModule build_model() on classifiers, regressors and LSS estimators, and TabularDataModule.__init__ / preprocess_data, defaulted to 101 while the constructors and fit() default to None. build_model() therefore ignored the estimator's own random_state, and an unseeded build_model() was silently seeded with 101. All of them now default to None and resolve it as fit() does: an explicit argument wins, then the estimator's (or the data module's) random_state; with neither, nothing is seeded. A fit that rebuilds (the default) passes the resolved seed explicitly and is unchanged. A fit(rebuild=False) after build_model() keeps the preprocessor that build_model() fitted, now on the constructor seed's partition rather than 101's. build_model() still does not call set_seed(); its docstring now says so. --- deeptab/data/datamodule.py | 21 +-- deeptab/models/_mixins/fit.py | 6 +- deeptab/models/classifier_base.py | 11 +- deeptab/models/lss_base.py | 15 +- deeptab/models/regressor_base.py | 11 +- docs/core_concepts/config_system.md | 2 +- docs/core_concepts/training_and_evaluation.md | 8 + tests/core/test_random_state.py | 152 ++++++++++++++++++ 8 files changed, 206 insertions(+), 20 deletions(-) diff --git a/deeptab/data/datamodule.py b/deeptab/data/datamodule.py index b16a801c..a703cedf 100644 --- a/deeptab/data/datamodule.py +++ b/deeptab/data/datamodule.py @@ -125,11 +125,11 @@ class TabularDataModule(pl.LightningDataModule): val_size : float, default=0.2 Default validation fraction for automatic splits. An explicit :meth:`preprocess_data` argument overrides it. - random_state : int, numpy.integer or None, default=101 - Seed for training-loader ordering and weighted sampling. The split - seed is supplied separately to :meth:`preprocess_data`. ``None`` uses - the generators' unseeded behavior. NumPy integers are accepted; other - types raise ``TypeError``. + random_state : int, numpy.integer or None, default=None + Seed for training-loader ordering and weighted sampling, and the + default seed of the automatic split in :meth:`preprocess_data`. + ``None`` uses the generators' unseeded behavior. NumPy integers are + accepted; other types raise ``TypeError``. stratify : bool, default=True Preserve class proportions in automatic validation splits. Ignored for regression and when explicit validation data are supplied. @@ -162,7 +162,7 @@ def __init__( X_val=None, y_val=None, val_size=0.2, - random_state: int | np.integer | None = 101, + random_state: int | np.integer | None = None, stratify=True, sampler=None, vector_targets=False, @@ -226,7 +226,7 @@ def preprocess_data( embeddings_train=None, embeddings_val=None, val_size=None, - random_state: int | None = 101, + random_state: int | np.integer | None = None, *, fit_preprocessing: bool = True, ): @@ -255,9 +255,11 @@ def preprocess_data( val_size : float or None, default=None Fraction of training rows reserved for automatic validation. ``None`` uses the constructor's ``val_size``. - random_state : int or None, default=101 + random_state : int, numpy.integer or None, default=None Seed for the automatic split and matching sampling-weight split. - This argument does not change the module's loader seed. + ``None`` uses the constructor's ``random_state``; when that is + ``None`` too, the split is unseeded. This argument does not change + the module's loader seed. fit_preprocessing : bool, default=True Fit preprocessing on the training partition. Set to false to retain an already fitted representation while preparing new data. @@ -274,6 +276,7 @@ def preprocess_data( if X_val is None: X_val, y_val = self._initial_X_val, self._initial_y_val val_size = self.val_size if val_size is None else val_size + random_state = self.random_state if random_state is None else random_state if not self.regression: self.num_classes = len(np.unique(y_train)) diff --git a/deeptab/models/_mixins/fit.py b/deeptab/models/_mixins/fit.py index 9f8c76e4..f4f67e6d 100644 --- a/deeptab/models/_mixins/fit.py +++ b/deeptab/models/_mixins/fit.py @@ -127,7 +127,7 @@ def _build_model( embeddings=None, embeddings_val=None, num_classes: int | None = None, - random_state: int | None = 101, + random_state: int | None = None, batch_size: int = 128, shuffle: bool = True, stratify: bool = True, @@ -149,6 +149,10 @@ def _build_model( self._mark_unfitted() if dataloader_kwargs is None: dataloader_kwargs = {} + # Resolve the seed as fit() does: an explicit argument wins over the + # random_state fixed at construction time; both unset stays unseeded. + if random_state is None: + random_state = self.random_state # When trainer_config is active, use its values for lr / weight_decay / scheduler if self.trainer_config is not None: diff --git a/deeptab/models/classifier_base.py b/deeptab/models/classifier_base.py index ce7309f1..3d32912b 100644 --- a/deeptab/models/classifier_base.py +++ b/deeptab/models/classifier_base.py @@ -114,7 +114,7 @@ def build_model( y_val=None, embeddings=None, embeddings_val=None, - random_state: int = 101, + random_state: int | None = None, batch_size: int = 128, shuffle: bool = True, stratify: bool = True, @@ -145,8 +145,13 @@ def build_model( The validation input samples. If provided, `X` and `y` are not split and this data is used for validation. y_val : array-like, shape (n_samples,) or (n_samples, n_targets), optional The validation target values. Required if `X_val` is provided. - random_state : int, default=101 - Controls the shuffling applied to the data before applying the split. + random_state : int or None, default=None + Seed for the automatic validation split, the preprocessor and the + training data loader. ``None`` uses the ``random_state`` fixed at + construction time; when both are ``None``, they are unseeded. Unlike + ``fit()``, this method does not reseed the global random number + generators, so weight initialization follows their current state + (use ``deeptab.set_seed`` to control it). batch_size : int, default=128 Number of samples per gradient update. shuffle : bool, default=True diff --git a/deeptab/models/lss_base.py b/deeptab/models/lss_base.py index 93a9b062..6805dbe1 100644 --- a/deeptab/models/lss_base.py +++ b/deeptab/models/lss_base.py @@ -99,7 +99,7 @@ def build_model( val_size: float = 0.2, X_val=None, y_val=None, - random_state: int | None = 101, + random_state: int | None = None, batch_size: int = 128, shuffle: bool = True, lr: float | None = None, @@ -129,8 +129,13 @@ def build_model( The validation input samples. If provided, `X` and `y` are not split and this data is used for validation. y_val : array-like, shape (n_samples,) or (n_samples, n_targets), optional The validation target values. Required if `X_val` is provided. - random_state : int or None, default=101 - Controls the shuffling applied to the data before applying the split. + random_state : int or None, default=None + Seed for the automatic validation split, the preprocessor and the + training data loader. ``None`` uses the ``random_state`` fixed at + construction time; when both are ``None``, they are unseeded. Unlike + ``fit()``, this method does not reseed the global random number + generators, so weight initialization follows their current state + (use ``deeptab.set_seed`` to control it). batch_size : int, default=128 Number of samples per gradient update. shuffle : bool, default=True @@ -172,6 +177,10 @@ def build_model( self._mark_unfitted() if dataloader_kwargs is None: dataloader_kwargs = {} + # Resolve the seed as fit() does: an explicit argument wins over the + # random_state fixed at construction time; both unset stays unseeded. + if random_state is None: + random_state = self.random_state self._configure_distribution(y, family, distributional_kwargs) # When trainer_config is active, resolve lr / scheduler params from it diff --git a/deeptab/models/regressor_base.py b/deeptab/models/regressor_base.py index 45239ed0..2c9e73ab 100644 --- a/deeptab/models/regressor_base.py +++ b/deeptab/models/regressor_base.py @@ -35,7 +35,7 @@ def build_model( y_val=None, embeddings=None, embeddings_val=None, - random_state: int = 101, + random_state: int | None = None, batch_size: int = 128, shuffle: bool = True, lr: float | None = None, @@ -62,8 +62,13 @@ def build_model( The validation input samples. If provided, `X` and `y` are not split and this data is used for validation. y_val : array-like, shape (n_samples,) or (n_samples, 1), optional The validation target values. Required if `X_val` is provided. - random_state : int, default=101 - Controls the shuffling applied to the data before applying the split. + random_state : int or None, default=None + Seed for the automatic validation split, the preprocessor and the + training data loader. ``None`` uses the ``random_state`` fixed at + construction time; when both are ``None``, they are unseeded. Unlike + ``fit()``, this method does not reseed the global random number + generators, so weight initialization follows their current state + (use ``deeptab.set_seed`` to control it). batch_size : int, default=128 Number of samples per gradient update. shuffle : bool, default=True diff --git a/docs/core_concepts/config_system.md b/docs/core_concepts/config_system.md index eba318d5..43fce7dd 100644 --- a/docs/core_concepts/config_system.md +++ b/docs/core_concepts/config_system.md @@ -421,7 +421,7 @@ trainer_config = TrainerConfig( | `shuffle` | `True` | Shuffle training-loader rows. Does not control the validation split. | | `stratify` | `True` | Stratify the split on `y` so train and validation keep the same class proportions. Ignored for regression. | -The seed for the split comes from the estimator's `random_state` (or the `random_state` you pass to `fit()`), so the same seed always reproduces the same partition. +The seed for the split comes from the estimator's `random_state` (or the `random_state` you pass to `fit()` or `build_model()`), so the same seed always reproduces the same partition. When neither is set, the split is unseeded and differs between calls. ```{important} `stratify` applies to classification only. A continuous regression target cannot be stratified, so the flag is ignored there. With `stratify=True` (the default) a classification split keeps the class balance of the full set; set `stratify=False` to draw a purely random split, which is useful for very small or rare-class datasets where stratification would otherwise fail. diff --git a/docs/core_concepts/training_and_evaluation.md b/docs/core_concepts/training_and_evaluation.md index 1c90902e..1822a7e6 100644 --- a/docs/core_concepts/training_and_evaluation.md +++ b/docs/core_concepts/training_and_evaluation.md @@ -592,6 +592,14 @@ model.fit(X_train, y_train) Running the same script twice produces bit-identical predictions on the same hardware. +`random_state` defaults to `None` everywhere: in the constructor, `fit()`, +`build_model()` and `TabularDataModule`. A call-level `random_state` wins over +the constructor's; when both are `None`, nothing is seeded. `build_model()` +resolves the seed the same way for the validation split, preprocessing, and +training-loader order, but it does not call `set_seed`, so the initial weights +of a built model follow the current global state. Call `set_seed` first when an +untrained, built model must be reproducible. + ### `set_seed`: standalone utility ```python diff --git a/tests/core/test_random_state.py b/tests/core/test_random_state.py index b33e5c1f..90814639 100644 --- a/tests/core/test_random_state.py +++ b/tests/core/test_random_state.py @@ -140,3 +140,155 @@ def test_datamodule_converts_numpy_integer_random_state(): ) assert type(datamodule.random_state) is int assert datamodule.random_state == SEED + + +# --------------------------------------------------------------------------- +# One default: random_state=None, resolved like fit() resolves it +# --------------------------------------------------------------------------- + +_TASKS = ["classifier", "regressor", "lss"] + + +def _seed_problem(task: str): + import pandas as pd + + rng = np.random.default_rng(3) + features = pd.DataFrame( + rng.normal(size=(N_SAMPLES, N_FEATURES)), columns=pd.Index([f"x{i}" for i in range(N_FEATURES)]) + ) + signal = features["x0"].to_numpy() + targets = (signal > 0).astype(int) if task == "classifier" else signal + return features, targets + + +def _seed_estimator(task: str, **options: Any): + from deeptab.configs import MLPConfig, PreprocessingConfig + from deeptab.models import MLPLSS, MLPClassifier, MLPRegressor + + estimator = {"classifier": MLPClassifier, "regressor": MLPRegressor, "lss": MLPLSS}[task] + return estimator( + model_config=MLPConfig(layer_sizes=[8]), + preprocessing_config=PreprocessingConfig(numerical_method="standardization", output_dim=7), + **options, + ) + + +def _validation_rows(model) -> np.ndarray: + return np.sort(model._data_module.X_val.index.to_numpy()) + + +@pytest.mark.parametrize("task", _TASKS) +def test_build_model_random_state_defaults_to_none(task): + import inspect + + model = _seed_estimator(task) + assert inspect.signature(model.build_model).parameters["random_state"].default is None + assert inspect.signature(model.fit).parameters["random_state"].default is None + assert inspect.signature(type(model).__init__).parameters["random_state"].default is None + + +def test_datamodule_random_state_defaults_to_none(): + import inspect + + from deeptab.data import TabularDataModule + + for method in (TabularDataModule.__init__, TabularDataModule.preprocess_data): + assert inspect.signature(method).parameters["random_state"].default is None + + +@pytest.mark.parametrize("task", _TASKS) +def test_build_model_uses_the_constructor_random_state(task): + features, targets = _seed_problem(task) + from_constructor = _seed_estimator(task, random_state=SEED).build_model(features, targets) + explicit = _seed_estimator(task).build_model(features, targets, random_state=SEED) + np.testing.assert_array_equal(_validation_rows(from_constructor), _validation_rows(explicit)) + assert from_constructor._data_module.random_state == SEED + + +@pytest.mark.parametrize("task", _TASKS) +def test_build_model_argument_wins_over_the_constructor_random_state(task): + features, targets = _seed_problem(task) + overridden = _seed_estimator(task, random_state=SEED).build_model(features, targets, random_state=ALT_SEED) + explicit = _seed_estimator(task).build_model(features, targets, random_state=ALT_SEED) + np.testing.assert_array_equal(_validation_rows(overridden), _validation_rows(explicit)) + assert overridden._data_module.random_state == ALT_SEED + + +def _seed_fit_options(task: str) -> dict[str, Any]: + options: dict[str, Any] = { + "accelerator": "cpu", + "logger": False, + "enable_progress_bar": False, + "enable_model_summary": False, + } + if task == "lss": + options["family"] = "normal" + return options + + +def _seed_trainer(tmp_path): + from deeptab.configs import TrainerConfig + + return TrainerConfig(max_epochs=1, batch_size=32, checkpoint_path=str(tmp_path)) + + +@pytest.mark.parametrize("task", _TASKS) +def test_rebuilding_fit_draws_the_same_validation_rows_as_build_model(task, tmp_path): + features, targets = _seed_problem(task) + built = _seed_estimator(task).build_model(features, targets, random_state=SEED) + fitted = _seed_estimator(task, random_state=SEED, trainer_config=_seed_trainer(tmp_path)) + fitted.fit(features, targets, **_seed_fit_options(task)) + np.testing.assert_array_equal(_validation_rows(fitted), _validation_rows(built)) + + +@pytest.mark.parametrize("task", _TASKS) +def test_fit_without_rebuild_keeps_the_preprocessor_fitted_on_the_constructor_seed_partition(task, tmp_path): + features, targets = _seed_problem(task) + reference = _seed_estimator(task).build_model(features, targets, random_state=SEED) + model = _seed_estimator(task, random_state=SEED, trainer_config=_seed_trainer(tmp_path)) + model.build_model(features, targets) + model.fit(features, targets, rebuild=False, **_seed_fit_options(task)) + assert model._data_module.preprocessor.fingerprint_ == reference._data_module.preprocessor.fingerprint_ + + +@pytest.mark.parametrize("task", _TASKS) +def test_build_model_without_any_random_state_leaves_the_split_unseeded(task, monkeypatch): + import deeptab.data.datamodule as datamodule + + seeds: list[Any] = [] + split = datamodule.train_test_split + + def recording_split(*arrays, **options): + seeds.append(options["random_state"]) + return split(*arrays, **options) + + monkeypatch.setattr(datamodule, "train_test_split", recording_split) + features, targets = _seed_problem(task) + model = _seed_estimator(task).build_model(features, targets) + assert seeds == [None] + assert model._data_module.random_state is None + + +@pytest.mark.parametrize( + ("module_seed", "split_seed", "expected"), + [(SEED, None, SEED), (SEED, ALT_SEED, ALT_SEED), (None, ALT_SEED, ALT_SEED), (None, None, None)], + ids=["module", "argument-wins", "argument-only", "unseeded"], +) +def test_preprocess_data_falls_back_to_the_module_random_state(module_seed, split_seed, expected, monkeypatch): + from pretab.preprocessor import Preprocessor + + import deeptab.data.datamodule as datamodule_module + from deeptab.data import TabularDataModule + + seeds: list[Any] = [] + split = datamodule_module.train_test_split + + def recording_split(*arrays, **options): + seeds.append(options["random_state"]) + return split(*arrays, **options) + + monkeypatch.setattr(datamodule_module, "train_test_split", recording_split) + features, targets = _seed_problem("regressor") + datamodule = TabularDataModule(Preprocessor(), 16, False, True, random_state=module_seed) + datamodule.preprocess_data(features, targets, random_state=split_seed) + assert seeds == [expected]