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
21 changes: 12 additions & 9 deletions deeptab/data/datamodule.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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,
):
Expand Down Expand Up @@ -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.
Expand All @@ -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))

Expand Down
6 changes: 5 additions & 1 deletion deeptab/models/_mixins/fit.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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:
Expand Down
11 changes: 8 additions & 3 deletions deeptab/models/classifier_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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
Expand Down
15 changes: 12 additions & 3 deletions deeptab/models/lss_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
11 changes: 8 additions & 3 deletions deeptab/models/regressor_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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
Expand Down
2 changes: 1 addition & 1 deletion docs/core_concepts/config_system.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
8 changes: 8 additions & 0 deletions docs/core_concepts/training_and_evaluation.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
152 changes: 152 additions & 0 deletions tests/core/test_random_state.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]