stagereg.core¶
Every symbol exported from stagereg.core, the backend-neutral contracts and utilities,
grouped by the module that defines it.
stagereg.core.checkpoints¶
Checkpoint
dataclass
¶
Checkpoint(
state: TrainingState,
epoch: int,
parameters: Any | None = None,
optimizer_state: Any | None = None,
rng_state: Any | None = None,
early_stopping_state: Any | None = None,
metadata: Mapping[str, Any] = dict(),
)
The complete state necessary to resume staged training.
Attributes:
| Name | Type | Description |
|---|---|---|
state |
TrainingState
|
Snapshot of the |
epoch |
int
|
Epoch of the active stage at which the checkpoint was saved. |
parameters |
Any | None
|
Snapshot of the model's parameters, in the backend's own
format. Defaults to |
optimizer_state |
Any | None
|
Snapshot of the optimizer's state, in the backend's own
format. Defaults to |
rng_state |
Any | None
|
Random key to resume training with. It mirrors the
|
early_stopping_state |
Any | None
|
State of the early stopper, such as an
|
metadata |
Mapping[str, Any]
|
Information about the checkpoint, such as the stage that saved it. Defaults to an empty mapping. |
CheckpointStore ¶
Bases: Protocol
Persists checkpoints under opaque keys.
InMemoryCheckpointStore ¶
A CheckpointStore kept in process memory.
Checkpoints live only for the lifetime of the store, which makes it the natural choice for examples, tests, and short runs that only need the best checkpoint of the current process restored at the end. Saving under an existing key replaces the checkpoint held there.
Source code in src/stagereg/core/checkpoints.py
save ¶
Store a checkpoint under a key, replacing any checkpoint there.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
The opaque key to store the checkpoint under. |
required |
checkpoint
|
Checkpoint
|
The checkpoint to store. |
required |
Returns:
| Type | Description |
|---|---|
None
|
None. |
Source code in src/stagereg/core/checkpoints.py
load ¶
Return the checkpoint stored under a key.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
The key the checkpoint was saved under. |
required |
Returns:
| Type | Description |
|---|---|
Checkpoint
|
The stored checkpoint. |
Raises:
| Type | Description |
|---|---|
KeyError
|
If no checkpoint has been saved under |
Source code in src/stagereg/core/checkpoints.py
exists ¶
Report whether a checkpoint is stored under a key.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
The key to look up. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
|
stagereg.core.distributions¶
PredictiveDistribution ¶
Bases: Protocol
A probability distribution produced by a regression model.
This protocol is the backend-neutral model/loss boundary. Epoch metrics use backend adapters to materialize host arrays rather than retaining distribution objects, which intentionally have no concatenation or indexing contract.
DistributionHead ¶
Bases: Protocol
Produces a predictive distribution from model features.
Likelihood ¶
Bases: Protocol
Evaluates a target under a predictive distribution.
DistributionLoss ¶
Bases: Protocol
Computes an unreduced loss from a predictive distribution.
PredictionLoss ¶
Bases: Protocol
Computes an unreduced loss from deterministic array predictions.
stagereg.core.early_stopping¶
OptimizationMode ¶
Bases: StrEnum
The direction in which a monitored metric is considered improved.
EarlyStoppingState
dataclass
¶
EarlyStoppingState(
metric: str,
mode: OptimizationMode,
min_delta: float,
patience: int,
source: Split = Split.VALIDATION,
best_score: float | None = None,
best_epoch: int | None = None,
non_improving_epochs: int = 0,
stopped: bool = False,
)
Checkpointable state for a configured early-stopping policy.
Attributes:
| Name | Type | Description |
|---|---|---|
metric |
str
|
Name of the monitored metric. |
mode |
OptimizationMode
|
Direction in which the metric is considered improved. |
min_delta |
float
|
Minimum change required to qualify as an improvement. |
patience |
int
|
Number of consecutive non-improving epochs tolerated before stopping. |
source |
Split
|
Split the monitored metric is measured on. |
best_score |
float | None
|
Best value observed so far, or |
best_epoch |
int | None
|
Epoch at which |
non_improving_epochs |
int
|
Number of consecutive epochs without an improvement. |
stopped |
bool
|
Whether patience has been exhausted and training should stop. |
EarlyStoppingDecision
dataclass
¶
The result of observing one monitored metric value.
Attributes:
| Name | Type | Description |
|---|---|---|
state |
EarlyStoppingState
|
Updated early-stopping state after the observation. |
improved |
bool
|
Whether the observed value improved on the best score. |
EarlyStopper ¶
EarlyStopper(
*,
metric: str,
mode: OptimizationMode | str,
patience: int,
min_delta: float = 0.0,
source: Split | str = Split.VALIDATION,
state: EarlyStoppingState | None = None,
)
Tracks a scalar metric and decides when training should stop.
Initialize an early stopper.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
metric
|
str
|
Name of the metric to monitor. |
required |
mode
|
OptimizationMode | str
|
Direction in which the metric is considered improved,
either |
required |
patience
|
int
|
Number of consecutive non-improving epochs tolerated before stopping. |
required |
min_delta
|
float
|
Minimum change required to qualify as an
improvement. Defaults to |
0.0
|
source
|
Split | str
|
Split the monitored metric is measured on, either
|
VALIDATION
|
state
|
EarlyStoppingState | None
|
Previously checkpointed state to resume from. Must match the configuration passed to this constructor. |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in src/stagereg/core/early_stopping.py
expects_validation ¶
Whether the monitored metric must come from validation.
Returns:
| Type | Description |
|---|---|
bool
|
|
bool
|
measured on the validation split (i.e. requires a |
bool
|
|
bool
|
supplied to the training loop), |
bool
|
on the training split. |
Source code in src/stagereg/core/early_stopping.py
monitored_metric_name ¶
Return the name of the metric this stopper monitors.
Returns:
| Type | Description |
|---|---|
str
|
The metric name passed to the constructor, used by callers |
str
|
to look up the corresponding value in per-epoch metrics. |
Source code in src/stagereg/core/early_stopping.py
observe ¶
Record a metric observed after epoch and return its decision.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
float
|
The monitored metric value observed for this epoch. |
required |
epoch
|
int
|
The epoch at which |
required |
Returns:
| Type | Description |
|---|---|
EarlyStoppingDecision
|
|
EarlyStoppingDecision
|
with the updated state and whether |
EarlyStoppingDecision
|
score so far. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
RuntimeError
|
If early stopping has already been triggered. |
Source code in src/stagereg/core/early_stopping.py
stagereg.core.losses¶
NegativeLogLikelihoodLoss
dataclass
¶
NegativeLogLikelihoodLoss(
beta: float = 0.0,
stop_gradient: Callable[[Array], Array] = _identity,
target_transform: Callable[[Array], Array] = _identity,
)
Configurable negative log-likelihood for predictive distributions.
Attributes:
| Name | Type | Description |
|---|---|---|
beta |
float
|
Variance-reweighting exponent in |
stop_gradient |
Callable[[Array], Array]
|
Callable excluding the variance weight from gradient
propagation. Defaults to the identity, which lets gradients flow
through the weight. With JAX and |
target_transform |
Callable[[Array], Array]
|
Callable applied to targets before evaluating the predictive distribution. Defaults to the identity transform. |
per_example ¶
Compute the optionally transformed and beta-weighted NLL.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prediction
|
PredictiveDistribution
|
The predictive distribution produced for |
required |
batch
|
Batch
|
Batch whose targets are scored under |
required |
Returns:
| Type | Description |
|---|---|
Array
|
An array of per-example negative log-likelihood values. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in src/stagereg/core/losses.py
SquaredErrorLoss
dataclass
¶
Per-example squared error for deterministic predictions.
per_example ¶
Compute squared prediction errors.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prediction
|
Array
|
Deterministic model predictions. |
required |
batch
|
Batch
|
Batch containing regression targets. |
required |
Returns:
| Type | Description |
|---|---|
Array
|
Elementwise squared prediction errors. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in src/stagereg/core/losses.py
add_epsilon ¶
Create a target transform that adds a positive stabilization offset.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
epsilon
|
float
|
Positive finite offset added to each target. |
1e-12
|
Returns:
| Type | Description |
|---|---|
Callable[[Array], Array]
|
A callable adding |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in src/stagereg/core/losses.py
GaussianNLLLoss
module-attribute
¶
Alias of NegativeLogLikelihoodLoss.
Kept for compatibility with the pre-consolidation name; prefer the canonical name.
BetaNLLLoss
module-attribute
¶
Alias of NegativeLogLikelihoodLoss.
Kept for compatibility with the pre-consolidation name; prefer the canonical name. The
beta-NLL weighting is the beta argument of
NegativeLogLikelihoodLoss.
stagereg.core.metric_registry¶
EvaluationGrid
dataclass
¶
A shared scalar CRPS integration grid.
Attributes:
| Name | Type | Description |
|---|---|---|
values |
FloatArray
|
Finite, strictly increasing integration coordinates. |
PredictionInterval
dataclass
¶
Host-resident bounds labelled by their central confidence level.
Attributes:
| Name | Type | Description |
|---|---|---|
level |
float
|
Central confidence level of the interval, strictly between 0 and 1. |
lower |
FloatArray
|
Lower bounds, one per scoring unit. |
upper |
FloatArray
|
Upper bounds, one per scoring unit, each no smaller than its lower bound. |
EpochPredictionData
dataclass
¶
EpochPredictionData(
targets: FloatArray,
mean: FloatArray,
variance: FloatArray | None = None,
predictive_samples: FloatArray | None = None,
reference_samples: FloatArray | None = None,
intervals: tuple[PredictionInterval, ...] = (),
coordinate: FloatArray | None = None,
evaluation_grid: EvaluationGrid | None = None,
log_likelihood: FloatArray | None = None,
)
Typed, host-materialized scalar predictions for one batch or epoch.
Rows are independent scalar scoring units. Sample matrices use rows for scoring units and columns for samples; non-scalar distribution events are intentionally not represented by this contract.
Attributes:
| Name | Type | Description |
|---|---|---|
targets |
FloatArray
|
Observed target, one per scoring unit. |
mean |
FloatArray
|
Predictive mean, one per scoring unit. |
variance |
FloatArray | None
|
Non-negative predictive variance, one per scoring unit. Defaults
to |
predictive_samples |
FloatArray | None
|
Samples from the predictive distribution, one row per
scoring unit and one column per sample. Defaults to |
reference_samples |
FloatArray | None
|
Samples from each scoring unit's reference distribution,
the empirical distribution the predictive samples are scored against,
one row per scoring unit and one column per sample. Defaults to |
intervals |
tuple[PredictionInterval, ...]
|
Prediction intervals, each a
|
coordinate |
FloatArray | None
|
Numeric coordinate of each scoring unit, such as time or
remaining useful life, that a metric orders or weights scoring units
by. Defaults to |
evaluation_grid |
EvaluationGrid | None
|
Shared |
log_likelihood |
FloatArray | None
|
Log-density of each scoring unit's target under the
predictive distribution. Defaults to |
interval ¶
Return the prediction interval registered at exactly level.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
level
|
float
|
Required central confidence level. |
required |
Returns:
| Type | Description |
|---|---|
PredictionInterval
|
The matching labelled interval. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no interval at |
Source code in src/stagereg/core/metric_registry.py
MetricRequirements
dataclass
¶
MetricRequirements(
variance: bool = False,
predictive_samples: bool = False,
reference_samples: bool = False,
interval_levels: frozenset[float] = frozenset(),
coordinate: bool = False,
evaluation_grid: bool = False,
log_likelihood: bool = False,
)
Materialized fields required by one or more epoch metrics.
Targets and predictive means are always materialized; each attribute asks for one
more field of EpochPredictionData.
Attributes:
| Name | Type | Description |
|---|---|---|
variance |
bool
|
Whether the predictive variance is required. Defaults to
|
predictive_samples |
bool
|
Whether samples from the predictive distribution are
required. Defaults to |
reference_samples |
bool
|
Whether samples from each scoring unit's reference
distribution are required. Defaults to |
interval_levels |
frozenset[float]
|
Confidence levels, each in |
coordinate |
bool
|
Whether each scoring unit's numeric coordinate is required.
Defaults to |
evaluation_grid |
bool
|
Whether the shared evaluation grid is required. Defaults
to |
log_likelihood |
bool
|
Whether each target's predictive log-density is
required. Defaults to |
union ¶
Combine this requirement set with another.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
MetricRequirements
|
Additional requirements. |
required |
Returns:
| Type | Description |
|---|---|
MetricRequirements
|
A requirement set containing the union of both inputs. |
Source code in src/stagereg/core/metric_registry.py
EpochMetric ¶
Bases: Protocol
A host-side scalar metric over typed epoch prediction data.
requirements
property
¶
Return fields that must be materialized for this metric.
RootMeanSquaredError
dataclass
¶
Epoch adapter for root mean squared error.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
Bare metric name the value is reported under. Defaults to |
__call__ ¶
NegativeLogLikelihood
dataclass
¶
Mean negative log-density of the targets under the predictive distribution.
The predictor computes each target's exact log-density, so a non-Gaussian predictive (such as a mixture over draws) is scored without a Gaussian approximation.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
Bare metric name the value is reported under. Defaults to |
IntervalCoverage
dataclass
¶
Observed coverage of an explicitly labelled prediction interval.
Attributes:
| Name | Type | Description |
|---|---|---|
level |
float
|
Confidence level of the labelled interval, in |
name |
str
|
Bare metric name the value is reported under. Defaults to |
WeightedSpread
dataclass
¶
Weighted spread for an interval and explicit numeric coordinate.
Attributes:
| Name | Type | Description |
|---|---|---|
level |
float
|
Confidence level of the labelled interval, in |
name |
str
|
Bare metric name the value is reported under. Defaults to |
__call__ ¶
Compute normalized weighted interval spread.
Raises:
| Type | Description |
|---|---|
ValueError
|
If the required coordinate is absent. |
Source code in src/stagereg/core/metric_registry.py
PointContinuousRankedProbabilityScore
dataclass
¶
Mean point-CRPS across independent scalar scoring units.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
Bare metric name the value is reported under. Defaults to |
requirements
property
¶
Require predictive samples and the shared evaluation grid.
__call__ ¶
Compute one point-CRPS per unit, then average units equally.
Raises:
| Type | Description |
|---|---|
ValueError
|
If predictive samples or the grid are absent. |
Source code in src/stagereg/core/metric_registry.py
SampleContinuousRankedProbabilityScore
dataclass
¶
Mean exact CRPS of predictive samples across scalar scoring units.
Each unit's predictive samples are scored against its target with
sample_crps, the energy form of the CRPS,
so unlike PointContinuousRankedProbabilityScore
it needs no evaluation grid.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
Bare metric name the value is reported under. Defaults to
|
__call__ ¶
Compute one CRPS per unit, then average units equally.
Raises:
| Type | Description |
|---|---|
ValueError
|
If predictive samples are absent. |
Source code in src/stagereg/core/metric_registry.py
ContinuousRankedProbabilityScore
dataclass
¶
Mean expected CRPS under per-unit empirical reference distributions.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
Bare metric name the value is reported under. Defaults to |
requirements
property
¶
Require predictive/reference samples and the shared grid.
__call__ ¶
Compute expected empirical-reference CRPS and average scoring units.
Raises:
| Type | Description |
|---|---|
ValueError
|
If either sample matrix or the grid is absent. |
Source code in src/stagereg/core/metric_registry.py
stagereg.core.metrics¶
cdf ¶
Return the empirical cumulative distribution at x.
Source code in src/stagereg/core/metrics.py
crps ¶
Approximate expected CRPS under a scalar empirical reference distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
samples_true
|
ArrayLike
|
Samples from the reference scalar distribution. |
required |
samples_pred
|
ArrayLike
|
Samples from the predictive scalar distribution. |
required |
x_grid
|
ArrayLike
|
Finite, strictly increasing integration coordinates. |
required |
Returns:
| Type | Description |
|---|---|
float
|
The predictive CRPS averaged over the empirical reference distribution. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If samples or the grid are empty, non-finite, or malformed. |
Source code in src/stagereg/core/metrics.py
point_crps ¶
Approximate CRPS between a scalar target and empirical predictions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y_true
|
float
|
Scalar reference target. |
required |
samples_pred
|
ArrayLike
|
Samples from the predictive scalar distribution. |
required |
x_grid
|
ArrayLike
|
Finite, strictly increasing integration coordinates. |
required |
Returns:
| Type | Description |
|---|---|
float
|
The grid-integrated squared distance between the point and empirical CDFs. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If inputs are empty, non-finite, or malformed. |
Source code in src/stagereg/core/metrics.py
sample_crps ¶
Return the exact CRPS between a scalar target and empirical predictions.
It uses the energy form E|X - y| - E|X - X'| / 2 of the CRPS, with X
and X' drawn from the empirical distribution of samples_pred, so
no evaluation grid is needed. It equals the integral of the squared
distance between the empirical and the target's CDFs over the whole line.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y_true
|
float
|
Scalar reference target. |
required |
samples_pred
|
ArrayLike
|
Samples from the predictive scalar distribution. |
required |
Returns:
| Type | Description |
|---|---|
float
|
The CRPS of the empirical predictive distribution at |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the target is not finite, or the samples are empty, non-finite, or not one-dimensional. |
Source code in src/stagereg/core/metrics.py
rmse ¶
Return the root mean squared error.
coverage ¶
Return the fraction of targets within inclusive prediction intervals.
Source code in src/stagereg/core/metrics.py
wsu ¶
Return the normalized weighted spread of uncertainty intervals.
The calculation preserves QMoDeM's established WSU definition while using a generic, strictly increasing coordinate rather than battery-specific time.
Source code in src/stagereg/core/metrics.py
stagereg.core.naming¶
Split ¶
Bases: StrEnum
The partition of data a metric was measured on.
MetricTag ¶
Bases: NamedTuple
The parts of a metric tag.
Attributes:
| Name | Type | Description |
|---|---|---|
stage |
str
|
Name of the stage that produced the metric. |
split |
Split
|
Split the metric was measured on. |
metric |
str
|
Bare name of the metric. |
metric_tag ¶
Build the metric tag for a metric measured in a stage on a split.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
stage
|
str
|
Name of the stage that produced the metric. |
required |
split
|
Split
|
Split the metric was measured on. |
required |
metric
|
str
|
Bare name of the metric. |
required |
Returns:
| Type | Description |
|---|---|
str
|
The tag |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in src/stagereg/core/naming.py
parse_metric_tag ¶
Split a metric tag back into its stage, split and metric name.
This is the exact inverse of metric_tag.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tag
|
str
|
A tag of the form |
required |
Returns:
| Type | Description |
|---|---|
MetricTag
|
The stage, split and metric name the tag was built from. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in src/stagereg/core/naming.py
flatten_parameters ¶
Flatten a nested parameter mapping into parameter paths.
Every non-mapping value, and every empty mapping, is a leaf and is kept unchanged under its key path joined with the separator. Because no key may be empty or contain the separator, two distinct key paths never map onto one parameter path.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
parameters
|
Mapping[str, Any]
|
The parameters to flatten, possibly nested. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
One entry per leaf, keyed by its parameter path. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If any key, at any depth, is empty or contains the separator. |
Source code in src/stagereg/core/naming.py
stagereg.core.protocols¶
Dataset ¶
Bases: Protocol
An indexable collection of raw examples.
LoaderFactory ¶
Bases: Protocol
Builds a batch loader for a split and epoch.
Optimizer ¶
Bases: Protocol
A functional optimizer with explicit, checkpointable state.
Step ¶
Bases: Protocol
Executes one training or evaluation step.
ValidationStrategy ¶
Bases: Protocol
Evaluates a trained state according to a caller-defined policy.
stagereg.core.stages¶
validate_transition ¶
Raise ValueError unless next_state directly follows current.
Source code in src/stagereg/core/stages.py
TrainingStage ¶
Bases: Protocol
A named unit of training with declared prerequisites and outputs.
stagereg.core.tracking¶
Decision
dataclass
¶
The measurement a decision event judged.
Attributes:
| Name | Type | Description |
|---|---|---|
metric |
str
|
Bare name of the monitored metric. |
value |
float
|
The metric's value at the step the decision was made. |
TrainingEvent
dataclass
¶
TrainingEvent(
name: str,
stage: str,
split: Split,
iteration: int,
step: int,
metrics: Mapping[str, float],
state: TrainingState,
decision: Decision | None = None,
)
A structured event emitted during staged training.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
The point in the stage's lifecycle the event marks, such as
|
stage |
str
|
Name of the stage that emitted the event. |
split |
Split
|
Split the event concerns: the split its metrics were measured on, or, for a decision event, the split of the metric the decision was made on. |
iteration |
int
|
Outer iteration of the staged workflow. |
step |
int
|
Step of the stage the event belongs to. |
metrics |
Mapping[str, float]
|
Metrics measured at this point, keyed by bare metric name. Empty for a decision event. |
state |
TrainingState
|
The live training state. |
decision |
Decision | None
|
The measurement a decision event judged, or |
EventSink ¶
Bases: Protocol
Consumes training events.
ExperimentTracker ¶
Bases: Protocol
Records parameters, metrics, and artifacts for an experiment.
log_params ¶
Record a run's hyperparameters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
values
|
Mapping[str, Any]
|
A nested mapping whose leaf keys are bare
|
required |
Returns:
| Type | Description |
|---|---|
None
|
None. |
Source code in src/stagereg/core/tracking.py
log_metrics ¶
Record metric values at a step.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
values
|
Mapping[str, float]
|
Metric values keyed by the tag to record them under. |
required |
step
|
int
|
The step the metrics belong to. |
required |
Returns:
| Type | Description |
|---|---|
None
|
None. |
Source code in src/stagereg/core/tracking.py
log_artifact ¶
Record an artifact under a name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The name to record the artifact under. |
required |
value
|
Any
|
The artifact to record. |
required |
Returns:
| Type | Description |
|---|---|
None
|
None. |
TrackerEventSink
dataclass
¶
An EventSink forwarding event metrics to a tracker.
Each metric is logged under its metric tag, built from the event's stage, the event's split and the metric name, with the event's own step. A decision event carries no metrics, so it adds no series.
The sink calls only
ExperimentTracker.log_metrics.
Hyperparameters and artifacts stay caller-driven, since neither arrives on
a training event.
Attributes:
| Name | Type | Description |
|---|---|---|
tracker |
ExperimentTracker
|
The experiment tracker that receives the metrics. |
on_event ¶
Log an event's metrics to the tracker under their metric tags.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
event
|
TrainingEvent
|
The training event whose metrics to forward. |
required |
Returns:
| Type | Description |
|---|---|
None
|
None. |
Source code in src/stagereg/core/tracking.py
stagereg.core.types¶
Array
module-attribute
¶
An array of the active backend, such as a jax.Array.
Typed as Any because stagereg.core imports no backend.
PyTree
module-attribute
¶
A nested container of arrays of the active backend, such as model parameters.
Typed as Any because stagereg.core imports no backend.
ParameterRole ¶
Bases: StrEnum
The responsibility of a trainable model component.
StageState ¶
Bases: StrEnum
The ordered lifecycle of a staged probabilistic-regression workflow.
Batch
dataclass
¶
Batch(
inputs: PyTree,
targets: PyTree | None = None,
sample_weight: Array | None = None,
metadata: Mapping[str, Any] = dict(),
)
A batch of model inputs, optional targets, weights, and metadata.
Attributes:
| Name | Type | Description |
|---|---|---|
inputs |
PyTree
|
Model inputs, an array or nested container of arrays with a leading batch dimension. |
targets |
PyTree | None
|
Regression targets aligned with |
sample_weight |
Array | None
|
Weights with a leading batch dimension, one per row, scaling
each row's contribution to the loss. Defaults to |
metadata |
Mapping[str, Any]
|
Caller-supplied information about the batch, carried along unchanged. Defaults to an empty mapping. |
CheckpointRef
dataclass
¶
An opaque reference to a persisted checkpoint.
Attributes:
| Name | Type | Description |
|---|---|---|
key |
str
|
Key the checkpoint is stored under in a
|
metadata |
Mapping[str, Any]
|
Information about the checkpoint, such as the stage that saved it. Defaults to an empty mapping. |
TrainingState
dataclass
¶
TrainingState(
model_components: dict[str, Any] = dict(),
parameter_roles: dict[str, ParameterRole] = dict(),
frozen_components: frozenset[str] = frozenset(),
optimizer_states: dict[str, Any] = dict(),
posterior_state: Any | None = None,
rng_state: Any | None = None,
lifecycle_state: StageState = StageState.NEW,
stage: str | None = None,
outer_iteration: int = 0,
data_fingerprint: str | None = None,
checkpoint_registry: dict[str, CheckpointRef] = dict(),
metric_history: dict[str, list[float]] = dict(),
)
State shared across one or more explicit training stages.
Attributes:
| Name | Type | Description |
|---|---|---|
model_components |
dict[str, Any]
|
Model objects keyed by component name, as registered
with |
parameter_roles |
dict[str, ParameterRole]
|
The |
frozen_components |
frozenset[str]
|
Names of components that are no longer trained, such as a fitted mean model while a later stage trains the variance. Defaults to an empty set. |
optimizer_states |
dict[str, Any]
|
Optimizer states keyed by name, as registered with
|
posterior_state |
Any | None
|
State of the posterior-approximation stage, set once
|
rng_state |
Any | None
|
Random key threaded through training; seed it to make a run
reproducible. Defaults to |
lifecycle_state |
StageState
|
Position of the workflow in the ordered
|
stage |
str | None
|
Label of the active stage, the value behind the
|
outer_iteration |
int
|
Zero-based outer iteration: the count of passes through
the run's sequence of stages. Defaults to |
data_fingerprint |
str | None
|
Identifier of the dataset the state was trained on,
meant to detect resuming against different data. Set by the user and
not interpreted by the library. Defaults to |
checkpoint_registry |
dict[str, CheckpointRef]
|
Named references to checkpoints a stage registered, such as its best checkpoint. Defaults to an empty mapping. |
metric_history |
dict[str, list[float]]
|
Recorded values of each metric in order, keyed by metric
tag ( |
active_stage
property
writable
¶
Return the explicit active training-stage label.
Returns:
| Type | Description |
|---|---|
str | None
|
The active training-stage label, or |
register_component ¶
Register a model component under name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The key under which |
required |
component
|
Any
|
The model component to register. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in src/stagereg/core/types.py
register_optimizer ¶
Register an optimizer state under name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The key under which |
required |
optimizer
|
Any
|
The optimizer state to register. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in src/stagereg/core/types.py
record_metric ¶
Append value to the metric history recorded under name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The metric name whose history is appended to. |
required |
value
|
float
|
The observed metric value to append. |
required |
Source code in src/stagereg/core/types.py
StageResult
dataclass
¶
StageResult(
state: TrainingState,
metrics: Mapping[str, float] = dict(),
loss: float | None = None,
)
The outcome of executing a training stage.
Attributes:
| Name | Type | Description |
|---|---|---|
state |
TrainingState
|
Training state the stage left behind. |
metrics |
Mapping[str, float]
|
Final metric values of the stage, keyed by metric name. Defaults to an empty mapping. |
loss |
float | None
|
Loss of the stage's last epoch on the |
ValidationResult
dataclass
¶
ValidationResult(
passed: bool,
metrics: Mapping[str, float] = dict(),
message: str | None = None,
)
The outcome of validating a training stage.
Attributes:
| Name | Type | Description |
|---|---|---|
passed |
bool
|
Whether the stage's invariants hold. |
metrics |
Mapping[str, float]
|
Metric values measured during validation, keyed by metric name. Defaults to an empty mapping. |
message |
str | None
|
Explanation of the outcome, typically of a failure. Defaults to
|