Source code for phlower.settings._predictor_setting
from __future__ import annotations
from typing import Self
import pydantic
from phlower.settings._time_series_sliding_setting import (
SlidingWindow,
SlidingWindowForStage,
SlidingWindowParameters,
)
from phlower.utils.enums import ModelSelectionType
[docs]
class RolloutVariableSetting(pydantic.BaseModel):
state_variable: str
"""
Name of the input variable which is updated at every step.
"""
increment_variable: str
"""
Name of the output variable which is added to the state.
"""
model_config = pydantic.ConfigDict(frozen=True, extra="forbid")
[docs]
class RolloutSetting(pydantic.BaseModel):
"""Predict a time series by applying the model step by step.
At every step, the increment predicted by the model is added to
the state in the unit of the data before scaling, and the new state
is the input of the next step. The model sees one time step of the
inputs at a time, so it must be a one-step model. A model with
`time_series_length: -1` runs once at every step.
"""
variables: list[RolloutVariableSetting] = pydantic.Field(min_length=1)
"""
Pairs of state and increment, all updated at every step.
"""
n_steps: int | None = pydantic.Field(None, gt=0)
"""
Number of steps. Defaults to None, which means the time length
of the states.
"""
model_config = pydantic.ConfigDict(frozen=True, extra="forbid")
@pydantic.model_validator(mode="after")
def check_variables(self) -> Self:
states = [v.state_variable for v in self.variables]
increments = [v.increment_variable for v in self.variables]
if len(set(states)) != len(states):
raise ValueError(f"Duplicate state_variable found: {states}")
if len(set(increments)) != len(increments):
raise ValueError(
f"Duplicate increment_variable found: {increments}"
)
return self
[docs]
class PhlowerPredictorSetting(pydantic.BaseModel):
selection_mode: str
"""
Define method to select checkpoint file.
Choose from "best", "latest", "train_best", "specified"
"""
device: str = "cpu"
"""
device name. Defaults to cpu
"""
log_file_name: str = "log"
"""
name of log file. Defaults to "log"
"""
saved_setting_filename: str = "model"
"""
file name of pretrained model setting. Defaults to "model"
"""
batch_size: int = 1
"""
batch size. Defaults to 1
"""
num_workers: int = 0
"""
the number of cores. Defaults to 0
"""
non_blocking: bool = False
"""
If True, the data transfer is non-blocking. Defaults to False.
"""
pin_memory: bool = False
"""
If True, the data loader uses pin_memory. Defaults to False.
"""
random_seed: int = 0
"""
random seed. Defaults to 0
"""
target_epoch: int | None = None
"""
target_epoch specifies the number of snapshot. Defaults to None.
"""
output_to_scaler_name: dict[str, str] = pydantic.Field(default_factory=dict)
"""
output_to_scaler_name is a dictionary to define the scaler
for each output variable. The key is the name of the output variable
and the value is the name of variable which has the scaler to use.
Defaults to empty dictionary, relationship between output variable
and scaler is assumed to be the same as that of label variables.
"""
use_inference_mode: bool = True
"""
If True, use torch.inference_mode() for prediction. Defaults to True.
"""
time_series_sliding: SlidingWindowForStage = pydantic.Field(
default_factory=lambda: SlidingWindowForStage(
is_active=False,
inputs=SlidingWindowParameters(
root=SlidingWindow(offset=0, size=1, stride=1)
),
labels=SlidingWindowParameters(
root=SlidingWindow(offset=0, size=1, stride=1)
),
)
)
"""
Setting for sliding window for time series data.
Defaults to inactive.
"""
rollout: RolloutSetting | None = None
"""
Setting for rollout, which needs the scaling setting.
Defaults to None, no rollout.
"""
# special keyward to forbid extra fields in pydantic
model_config = pydantic.ConfigDict(frozen=True, extra="forbid")
@pydantic.model_validator(mode="after")
def check_rollout_without_sliding(self) -> Self:
if self.rollout is not None and self.time_series_sliding.is_active:
raise ValueError("rollout cannot be used with time_series_sliding.")
return self
@pydantic.field_validator("selection_mode")
@classmethod
def check_valid_selection_mode(cls, name: str) -> str:
names = [v.value for v in ModelSelectionType]
if name not in names:
raise ValueError(f"{name} selection mode does not exist.")
return name
@pydantic.field_validator("time_series_sliding")
@classmethod
def check_not_treat_as_samples(
cls, value: SlidingWindowForStage
) -> SlidingWindowForStage:
if value.windows_as_samples():
raise ValueError(
"treat_as_samples is only for training. Set it false."
)
return value
@pydantic.model_validator(mode="after")
def check_valid_target_epoch(self) -> Self:
if self.selection_mode != "specified":
if self.target_epoch is not None:
raise ValueError(
"target_epoch should be None "
"if selection_mode is not `specified` "
f"but {self.target_epoch}"
)
return self
if (self.target_epoch is None) or (self.target_epoch < 0):
raise ValueError(
"target_epoch should be non-negative value "
f"when selection_mode = {self.selection_mode}, "
f"but {self.target_epoch}"
)
return self