stagereg.jax¶
Every symbol exported from stagereg.jax, the JAX/Flax NNX training backend, grouped by the
module that defines it. Using it needs the jax extra.
stagereg.jax.bayes_by_backprop¶
BayesByBackprop
dataclass
¶
BayesByBackprop(
optimizer: GradientTransformation = _default_optimizer(),
initial_std: float = 0.001,
)
Mean-field Gaussian variational inference by Bayes by Backprop.
Every update takes one reparameterized parameter sample and steps the
variational parameters along the gradient of the negative minibatch
ELBO: the KL divergence from the prior minus the problem's
log-likelihood, which is already scaled by N / B. The KL is in closed
form for an IsotropicGaussianPrior
and a one-sample Monte Carlo estimate, log q(w) - log p(w), for any
other prior. Standard deviations are parameterized as the softplus of an
unconstrained rho.
The variational means are warm-started from the problem's initial
parameters, the trained mean network, and every standard deviation from
initial_std. Its default of 1e-3 keeps the first draws close to
the trained mean, so inference starts from a good fit and widens the
posterior from there; raise it when the parameters' posterior spread is
expected to be far larger, since a softplus scale grows only about
linearly in rho.
It supports early stopping. Its best checkpoint holds the variational parameters and optimizer state; its finalized checkpoint holds the variational means and standard deviations alone.
Attributes:
| Name | Type | Description |
|---|---|---|
optimizer |
GradientTransformation
|
The Optax transformation stepping the variational
parameters. Defaults to Adam with a learning rate of |
initial_std |
float
|
The standard deviation every parameter starts with,
positive and finite. Defaults to |
supports_early_stopping
property
¶
Always True: the variational parameters can stop anywhere.
init ¶
Warm-start the variational parameters from problem.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
problem
|
PosteriorProblem
|
The posterior problem. |
required |
Source code in src/stagereg/jax/bayes_by_backprop.py
update ¶
Step the variational parameters on one training batch.
Only the batch's inputs, targets and sample_weight reach
the log-likelihood; its metadata does not.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
batch
|
Batch
|
The training batch. |
required |
key
|
Array
|
A fresh PRNG key for this batch's parameter sample. |
required |
Returns:
| Type | Description |
|---|---|
Mapping[str, Any]
|
|
Mapping[str, Any]
|
negative ELBO. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the method has not been initialized. |
Source code in src/stagereg/jax/bayes_by_backprop.py
posterior ¶
Return the current variational posterior.
Returns:
| Type | Description |
|---|---|
MeanFieldGaussianPosterior
|
A posterior independent of later updates. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the method has not been initialized. |
Source code in src/stagereg/jax/bayes_by_backprop.py
state ¶
Return the variational parameters and the optimizer state.
Returns:
| Type | Description |
|---|---|
PyTree
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If the method has not been initialized. |
Source code in src/stagereg/jax/bayes_by_backprop.py
load_state ¶
Resume inference from a state returned by state().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state
|
PyTree
|
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the method has not been initialized. |
Source code in src/stagereg/jax/bayes_by_backprop.py
posterior_state ¶
Return the variational means and standard deviations.
Returns:
| Type | Description |
|---|---|
PyTree
|
|
PyTree
|
tree. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the method has not been initialized. |
Source code in src/stagereg/jax/bayes_by_backprop.py
load_posterior ¶
Rebuild the posterior from a state returned by posterior_state().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state
|
PyTree
|
A state previously returned by
|
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the method has not been initialized. |
Source code in src/stagereg/jax/bayes_by_backprop.py
MeanFieldGaussianPosterior
dataclass
¶
MeanFieldGaussianPosterior(
mean_function: Callable[[PyTree, PyTree], Array],
means: PyTree,
stds: PyTree,
)
An independent Gaussian on every parameter of the posterior network.
Draw s under key samples its parameters from
jax.random.fold_in(key, s), so it is the same mean function at every
input, in every call, and whatever the number of draws asked for.
Attributes:
| Name | Type | Description |
|---|---|---|
mean_function |
Callable[[PyTree, PyTree], Array]
|
Maps |
means |
PyTree
|
The variational means, in the posterior network's parameter tree. |
stds |
PyTree
|
The variational standard deviations, positive, in the same tree. |
num_draws
property
¶
Always None: a variational posterior has unlimited draws.
sample_means ¶
Draw mean predictions at inputs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
inputs
|
PyTree
|
Model inputs with a leading batch dimension. |
required |
key
|
Array
|
The PRNG key selecting the draws. |
required |
num_samples
|
int | None
|
The number of draws |
None
|
Returns:
| Type | Description |
|---|---|
Array
|
The draws' mean predictions, shaped |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in src/stagereg/jax/bayes_by_backprop.py
stagereg.jax.distributions¶
Gaussian
dataclass
¶
A JAX-backed Gaussian predictive distribution parametrized by scale.
Attributes:
| Name | Type | Description |
|---|---|---|
loc |
Array
|
The distribution mean, shaped like the model's output. |
scale |
Array
|
The distribution's positive standard deviation, broadcastable
against |
batch_shape
property
¶
The broadcast shape of independent Gaussian components.
event_shape
property
¶
The shape of a single Gaussian event, always scalar.
log_prob ¶
Compute the elementwise Gaussian log-density of targets.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
targets
|
Array
|
Target values broadcastable against |
required |
Returns:
| Type | Description |
|---|---|
Array
|
The elementwise log-density, shaped like the broadcast of |
Array
|
|
Source code in src/stagereg/jax/distributions.py
sample ¶
Draw reparametrized samples from this distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
Array
|
A JAX PRNG key. |
required |
sample_shape
|
tuple[int, ...]
|
Leading sample dimensions prepended to
|
()
|
Returns:
| Type | Description |
|---|---|
Array
|
Samples shaped |
Source code in src/stagereg/jax/distributions.py
mean ¶
Gamma
dataclass
¶
A JAX-backed Gamma distribution parametrized by shape and rate.
Attributes:
| Name | Type | Description |
|---|---|---|
concentration |
Array
|
Positive Gamma shape parameter. |
rate |
Array
|
Positive Gamma rate parameter, i.e. the inverse scale. |
batch_shape
property
¶
Return the broadcast shape of independent Gamma components.
event_shape
property
¶
Return the shape of a single Gamma event, always scalar.
log_prob ¶
Compute the elementwise Gamma log-density of targets.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
targets
|
Array
|
Positive target values broadcastable against the concentration and rate. |
required |
Returns:
| Type | Description |
|---|---|
Array
|
Elementwise log-density values. |
Source code in src/stagereg/jax/distributions.py
sample ¶
Draw keyed samples from the Gamma distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
Array
|
A JAX PRNG key. |
required |
sample_shape
|
tuple[int, ...]
|
Leading sample dimensions prepended to
|
()
|
Returns:
| Type | Description |
|---|---|
Array
|
Samples shaped |
Source code in src/stagereg/jax/distributions.py
mean ¶
variance ¶
PosteriorPredictive
dataclass
¶
The posterior predictive: an equally weighted mixture of Gaussians over draws.
Each component is a Gaussian centred on one draw's mean with the aleatoric
variance, so the mixture is exact for the draws taken and may be skewed or
multimodal. Its single-Gaussian summary is
moment_matched.
Attributes:
| Name | Type | Description |
|---|---|---|
draws |
Array
|
The mean of each draw at the predicted inputs, shaped
|
aleatoric_variance |
Array
|
The positive aleatoric variance, broadcastable
against |
batch_shape
property
¶
The broadcast shape of the draws' means and the aleatoric variance.
event_shape
property
¶
The shape of a single predictive sample, always scalar.
log_prob ¶
Compute the exact elementwise mixture log-density of targets.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
targets
|
Array
|
Target values broadcastable against |
required |
Returns:
| Type | Description |
|---|---|
Array
|
|
Array
|
|
Source code in src/stagereg/jax/distributions.py
sample ¶
Draw predictive samples, each from a uniformly chosen draw's Gaussian.
The Gaussian noise uses key exactly as
Gaussian.sample does, so with one draw
the samples equal that Gaussian's.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
Array
|
A JAX PRNG key. |
required |
sample_shape
|
tuple[int, ...]
|
Leading sample dimensions prepended to
|
()
|
Returns:
| Type | Description |
|---|---|
Array
|
Predictive samples shaped |
Source code in src/stagereg/jax/distributions.py
mean ¶
variance ¶
cdf ¶
Compute the elementwise mixture cumulative distribution of targets.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
targets
|
Array
|
Target values broadcastable against |
required |
Returns:
| Type | Description |
|---|---|
Array
|
The average over draws of the component Gaussian CDFs. |
Source code in src/stagereg/jax/distributions.py
quantile ¶
Compute the elementwise mixture quantile at probability.
The mixture CDF has no closed-form inverse, so the quantile is found by bisection between the smallest and the largest of the draws' Gaussian quantiles, which bracket it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
probability
|
float
|
The cumulative probability, strictly between 0 and 1. |
required |
Returns:
| Type | Description |
|---|---|
Array
|
The quantile, shaped like |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in src/stagereg/jax/distributions.py
moment_matched ¶
Summarize the mixture by the Gaussian with its mean and variance.
By the law of total variance, the mixture variance is the aleatoric variance plus the epistemic variance of the draws' means.
Returns:
| Type | Description |
|---|---|
MomentMatchedPredictive
|
|
MomentMatchedPredictive
|
with both variance parts broadcast to |
Source code in src/stagereg/jax/distributions.py
MomentMatchedPredictive
dataclass
¶
The Gaussian with a posterior predictive's mean and variance.
A named summary of a PosteriorPredictive,
not a substitute for it: its variance is split into the aleatoric and the
epistemic part. Obtain one from
PosteriorPredictive.moment_matched.
Attributes:
| Name | Type | Description |
|---|---|---|
loc |
Array
|
The predictive mean, the average of the draws' means. |
aleatoric_variance |
Array
|
The aleatoric variance shared by every draw. |
epistemic_variance |
Array
|
The variance of the draws' means around |
batch_shape
property
¶
The broadcast shape of the mean and both variance parts.
event_shape
property
¶
The shape of a single predictive sample, always scalar.
log_prob ¶
Compute the elementwise Gaussian log-density of targets.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
targets
|
Array
|
Target values broadcastable against |
required |
Returns:
| Type | Description |
|---|---|
Array
|
The elementwise log-density under the moment-matched Gaussian. |
Source code in src/stagereg/jax/distributions.py
sample ¶
Draw predictive samples from the moment-matched Gaussian.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
Array
|
A JAX PRNG key. |
required |
sample_shape
|
tuple[int, ...]
|
Leading sample dimensions prepended to
|
()
|
Returns:
| Type | Description |
|---|---|
Array
|
Predictive samples shaped |
Source code in src/stagereg/jax/distributions.py
mean ¶
GaussianHead ¶
Bases: Module
An NNX head producing a Gaussian from model features.
A single linear layer maps in_features to 2 * out_features
outputs, split into an unconstrained location and an unconstrained scale
that is passed through softplus (plus eps) to guarantee a
strictly positive standard deviation.
Initialize the head's linear layer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
in_features
|
int
|
Number of input feature dimensions. |
required |
out_features
|
int
|
Number of predicted target dimensions. |
required |
rngs
|
Rngs
|
NNX RNG collection used to initialize parameters. |
required |
eps
|
float
|
A small positive constant added to the |
1e-06
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in src/stagereg/jax/distributions.py
__call__ ¶
Produce a Gaussian prediction from features.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
features
|
Array
|
Model features, shaped |
required |
Returns:
| Type | Description |
|---|---|
Gaussian
|
A |
Gaussian
|
|
Source code in src/stagereg/jax/distributions.py
GammaHead ¶
Bases: Module
An NNX head producing a shape/rate Gamma distribution.
Initialize the Gamma parameter projection.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
in_features
|
int
|
Number of input feature dimensions. |
required |
out_features
|
int
|
Number of predicted target dimensions. |
required |
rngs
|
Rngs
|
NNX RNG collection used to initialize parameters. |
required |
eps
|
float
|
Positive finite offset added after |
1e-06
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in src/stagereg/jax/distributions.py
__call__ ¶
Produce a Gamma prediction from model features.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
features
|
Array
|
Model features shaped |
required |
Returns:
| Type | Description |
|---|---|
Gamma
|
A Gamma distribution with positive concentration and rate shaped |
Gamma
|
|
Source code in src/stagereg/jax/distributions.py
stagereg.jax.evaluation¶
SupervisedLoss ¶
Bases: Protocol
A callable computing a supervised loss for an NNX model.
Implementations compute a scalar loss from a model, a batch of inputs/targets/sample weights, a PRNG key (e.g. for stochastic layers such as dropout), and a flag indicating whether the call happens during training (as opposed to evaluation).
__call__ ¶
__call__(
model: Module,
inputs: PyTree,
targets: Array,
sample_weight: Array | None,
key: Array,
training: bool,
) -> jax.Array
Compute the scalar supervised loss for a batch.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
Module
|
The NNX module to evaluate. |
required |
inputs
|
PyTree
|
The batch inputs. |
required |
targets
|
Array
|
The batch targets. |
required |
sample_weight
|
Array | None
|
Per-sample weights for the batch. |
required |
key
|
Array
|
A JAX PRNG key, e.g. for stochastic layers. |
required |
training
|
bool
|
Whether the loss is being computed during training (as opposed to evaluation). |
required |
Returns:
| Type | Description |
|---|---|
Array
|
The scalar loss value. |
Source code in src/stagereg/jax/evaluation.py
make_evaluation_step ¶
make_evaluation_step(
loss: SupervisedLoss,
*,
metrics: Sequence[BatchMetricSpec] = (),
) -> Callable[..., Mapping[str, jax.Array]]
Create a JIT-compiled NNX supervised evaluation step.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
loss
|
SupervisedLoss
|
A callable computing the supervised loss given a model,
inputs, targets, sample weights, a PRNG key, and a
|
required |
metrics
|
Sequence[BatchMetricSpec]
|
Registered JAX-native batch metrics. |
()
|
Returns:
| Type | Description |
|---|---|
Callable[..., Mapping[str, Array]]
|
A JIT-compiled function ``evaluate_step(model, inputs, targets, |
Callable[..., Mapping[str, Array]]
|
sample_weight, key) |
Callable[..., Mapping[str, Array]]
|
plus one scalar value per registered batch metric. |
Source code in src/stagereg/jax/evaluation.py
evaluate_loader ¶
evaluate_loader(
model: Module,
loader: Iterable[Batch],
*,
key: Array,
metrics: MetricSuite | None = None,
loss: SupervisedLoss | None = None,
) -> tuple[dict[str, float], jax.Array]
Evaluate a loader and return reduced metrics and the advanced random key.
The evaluation step is built here from metrics and loss, so a
caller that only wants to score a loader against metrics need not
invent a loss to do it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
Module
|
The NNX module to evaluate. |
required |
loader
|
Iterable[Batch]
|
An iterable of batches to evaluate. |
required |
key
|
Array
|
The JAX PRNG key to use, advanced once per batch. |
required |
metrics
|
MetricSuite | None
|
Optional registered batch/epoch metrics for evaluation. When omitted, no metrics are collected. |
None
|
loss
|
SupervisedLoss | None
|
Optional supervised loss to average across batches. When
omitted, the returned mapping has no |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, float]
|
A tuple |
Array
|
registered metrics plus |
tuple[dict[str, float], Array]
|
|
Source code in src/stagereg/jax/evaluation.py
stagereg.jax.losses¶
make_supervised_loss ¶
make_supervised_loss(
objective: DistributionLoss | PredictionLoss,
*,
reduction: Callable[[Array], Array] = jnp.mean,
) -> SupervisedLoss
Adapt a per-example objective to the JAX supervised-runner contract.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
objective
|
DistributionLoss | PredictionLoss
|
Backend-neutral objective computing unreduced loss values from model predictions and a batch. |
required |
reduction
|
Callable[[Array], Array]
|
Callable reducing optionally weighted loss values to a
scalar. Defaults to |
mean
|
Returns:
| Type | Description |
|---|---|
SupervisedLoss
|
A supervised loss that invokes the model, applies the objective and |
SupervisedLoss
|
optional sample weights, then reduces to a scalar. Training calls use |
SupervisedLoss
|
the live model in training mode. Evaluation calls use an isolated |
SupervisedLoss
|
inference-mode clone so validation cannot mutate the live model. |
Source code in src/stagereg/jax/losses.py
stagereg.jax.metrics¶
BatchMetric ¶
Bases: Protocol
A JAX-native metric computed per batch.
__call__ ¶
__call__(
model: Module,
inputs: PyTree,
targets: Array,
sample_weight: Array | None,
key: Array,
training: bool,
) -> jax.Array
Return a scalar batch metric value.
BatchMetricSpec
dataclass
¶
BatchMetricSpec(
name: str,
metric: BatchMetric,
reduce: Callable[
[Sequence[float]], float
] = _metric_mean,
)
A named batch metric with a host-side reduction policy.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
Bare metric name the reduced value is reported under. Must not be empty. |
metric |
BatchMetric
|
The |
reduce |
Callable[[Sequence[float]], float]
|
Host-side reduction of the per-batch values to one epoch value. Defaults to the arithmetic mean. |
PredictionRequirements
dataclass
¶
PredictionRequirements(
fields: MetricRequirements,
predictive_sample_count: int | None = None,
evaluation_grid: EvaluationGrid | None = None,
)
Combined metric requirements plus explicit materialization configuration.
Attributes:
| Name | Type | Description |
|---|---|---|
fields |
MetricRequirements
|
Union of the prediction fields the registered epoch metrics read. |
predictive_sample_count |
int | None
|
Number of predictive samples per scoring unit.
Required, and positive, when |
evaluation_grid |
EvaluationGrid | None
|
Grid the CRPS metrics integrate over. Required when
|
CoordinateExtractor ¶
Bases: Protocol
Extract a numeric scoring-unit coordinate from a domain batch.
ReferenceSamplesExtractor ¶
Bases: Protocol
Materialize reference samples at the JAX/domain boundary.
Predictor ¶
Bases: Protocol
Materialize typed host predictions from a JAX model and batch.
__call__ ¶
__call__(
model: Module,
batch: Batch,
requirements: PredictionRequirements,
key: Array,
) -> EpochPredictionData
Produce host-resident prediction data for batch.
GaussianPredictor
dataclass
¶
GaussianPredictor(
coordinate_extractor: CoordinateExtractor | None = None,
reference_samples_extractor: ReferenceSamplesExtractor
| None = None,
)
Materialize scalar epoch data from a model returning Gaussian.
Attributes:
| Name | Type | Description |
|---|---|---|
coordinate_extractor |
CoordinateExtractor | None
|
Optional explicit adapter for coordinate metadata. |
reference_samples_extractor |
ReferenceSamplesExtractor | None
|
Optional explicit adapter for conditional CRPS
reference samples. It must return |
__call__ ¶
__call__(
model: Module,
batch: Batch,
requirements: PredictionRequirements,
key: Array,
) -> EpochPredictionData
Materialize only fields requested by registered epoch metrics.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
Module
|
Model mapping batch inputs to a scalar-event Gaussian. |
required |
batch
|
Batch
|
Domain batch containing targets. |
required |
requirements
|
PredictionRequirements
|
Combined fields and explicit sample/grid configuration. |
required |
key
|
Array
|
Dedicated metric PRNG key. |
required |
Returns:
| Type | Description |
|---|---|
EpochPredictionData
|
Validated host-resident prediction data. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If the model does not return a Gaussian. |
ValueError
|
If targets, event shape, extractors, or shapes are invalid. |
Source code in src/stagereg/jax/metrics.py
PosteriorPredictivePredictor
dataclass
¶
PosteriorPredictivePredictor(
coordinate_extractor: CoordinateExtractor | None = None,
reference_samples_extractor: ReferenceSamplesExtractor
| None = None,
)
Materialize scalar epoch data from a model returning PosteriorPredictive.
Scores the exact mixture rather than its moment-matched Gaussian: the log-likelihood is the mixture log-density, predictive samples are drawn from the mixture, and prediction intervals are central mixture quantiles.
Attributes:
| Name | Type | Description |
|---|---|---|
coordinate_extractor |
CoordinateExtractor | None
|
Optional explicit adapter for coordinate metadata. |
reference_samples_extractor |
ReferenceSamplesExtractor | None
|
Optional explicit adapter for conditional CRPS
reference samples. It must return |
__call__ ¶
__call__(
model: Module,
batch: Batch,
requirements: PredictionRequirements,
key: Array,
) -> EpochPredictionData
Materialize only fields requested by registered epoch metrics.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
Module
|
Model mapping batch inputs to a
|
required |
batch
|
Batch
|
Domain batch containing targets. |
required |
requirements
|
PredictionRequirements
|
Combined fields and explicit sample/grid configuration. |
required |
key
|
Array
|
Dedicated metric PRNG key. |
required |
Returns:
| Type | Description |
|---|---|
EpochPredictionData
|
Validated host-resident prediction data. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If the model does not return a posterior predictive. |
ValueError
|
If targets, extractors, or shapes are invalid. |
Source code in src/stagereg/jax/metrics.py
MetricSuite
dataclass
¶
MetricSuite(
batch: tuple[BatchMetricSpec, ...] = (),
epoch: tuple[EpochMetric, ...] = (),
predictor: Predictor | None = None,
predictive_sample_count: int | None = None,
evaluation_grid: EvaluationGrid | None = None,
)
Complete metric registration and materialization configuration.
Attributes:
| Name | Type | Description |
|---|---|---|
batch |
tuple[BatchMetricSpec, ...]
|
Batch metrics evaluated on every batch. |
epoch |
tuple[EpochMetric, ...]
|
|
predictor |
Predictor | None
|
The |
predictive_sample_count |
int | None
|
Number of predictive samples per scoring unit. Required by sample-based epoch metrics. |
evaluation_grid |
EvaluationGrid | None
|
Grid the CRPS metrics integrate over. Required by CRPS epoch metrics. |
merge_epoch_prediction_data ¶
Merge batches according to each typed field's scoring axes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
parts
|
Sequence[EpochPredictionData]
|
Per-batch host-materialized prediction data. |
required |
Returns:
| Type | Description |
|---|---|
EpochPredictionData
|
One validated epoch prediction object. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If parts are empty or optional fields/configuration conflict. |
Source code in src/stagereg/jax/metrics.py
stagereg.jax.posterior¶
PosteriorProblem
dataclass
¶
PosteriorProblem(
initial_parameters: PyTree,
mean_function: Callable[[PyTree, PyTree], Array],
log_likelihood: Callable[[PyTree, Batch], Array],
prior: Prior,
train_loader: LoaderFactory,
dataset_size: int,
)
Everything a posterior stage hands its inference method.
Attributes:
| Name | Type | Description |
|---|---|---|
initial_parameters |
PyTree
|
The warm start: a copy of the trained mean network's parameters, in the posterior network's parameter tree. |
mean_function |
Callable[[PyTree, PyTree], Array]
|
Maps |
log_likelihood |
Callable[[PyTree, Batch], Array]
|
Maps |
prior |
Prior
|
The prior over the parameter tree. |
train_loader |
LoaderFactory
|
Factory producing the training batches of each epoch. |
dataset_size |
int
|
The number of training examples |
Prior ¶
Bases: Protocol
A log-density over the parameter tree of the posterior network.
IsotropicGaussianPrior
dataclass
¶
An independent zero-mean Gaussian on every parameter.
The default precision of 1 is VeBNN's κ = 1.
Attributes:
| Name | Type | Description |
|---|---|---|
precision |
float
|
The inverse variance of every parameter, positive and
finite. Defaults to |
log_prob ¶
Return the normalized log-density of a parameter tree.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
parameters
|
PyTree
|
A tree of parameter arrays. |
required |
Returns:
| Type | Description |
|---|---|
Array
|
The scalar sum, over every parameter, of its Gaussian log-density. |
Source code in src/stagereg/jax/posterior.py
InferenceMethod ¶
Bases: Protocol
How a posterior stage turns a posterior problem into a posterior.
The stage owns the epoch loop: it calls
init once, then
update once per training batch,
and reads the current posterior
to validate each epoch that ends with
has_posterior true. Every
method honors the problem's prior.
supports_early_stopping
property
¶
Whether stopping on a validation improvement is meaningful.
False for SG-MCMC, whose chain an early stopper would truncate.
has_posterior
property
¶
Whether posterior can be read.
False before init and, for SG-MCMC, until the first sample is
retained. The posterior stage skips validation for an epoch that ends
without a posterior, so a method that supports early stopping must
have one after every epoch.
init ¶
Start inference from problem, discarding any previous state.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
problem
|
PosteriorProblem
|
The posterior problem. |
required |
update ¶
Advance inference by one training batch.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
batch
|
Batch
|
The training batch. |
required |
key
|
Array
|
A fresh PRNG key for this batch. |
required |
Returns:
| Type | Description |
|---|---|
Mapping[str, Any]
|
A mapping holding the scalar |
Source code in src/stagereg/jax/posterior.py
posterior ¶
Return the current posterior, independent of later updates.
Returns:
| Type | Description |
|---|---|
Posterior
|
The posterior inferred so far. |
state ¶
Return the method's full state, independent of later updates.
This is what a best checkpoint stores, so that inference can resume from it, e.g. variational parameters plus optimizer state.
Returns:
| Type | Description |
|---|---|
PyTree
|
A tree of arrays. |
Source code in src/stagereg/jax/posterior.py
load_state ¶
posterior_state ¶
Return the current posterior alone, independent of later updates.
This is what a finalized checkpoint stores: only what
load_posterior needs
to rebuild the posterior, e.g. the variational parameters of a
variational method or the retained samples of an SG-MCMC method, but
no optimizer state.
Returns:
| Type | Description |
|---|---|
PyTree
|
A tree of arrays. |
Source code in src/stagereg/jax/posterior.py
load_posterior ¶
Rebuild a finalized posterior after
init.
Afterwards posterior
returns the posterior that state describes. The method need not be
able to resume inference from it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state
|
PyTree
|
A state previously returned by
|
required |
Source code in src/stagereg/jax/posterior.py
Posterior ¶
Bases: Protocol
An approximate posterior over mean functions, consumed through draws.
A draw is a whole mean function: under the same key, draw s is the
same function at every input and in every batch. A finite posterior
(retained samples, ensemble members) has a fixed set of draws and always
uses all of them; an unlimited one (a variational distribution,
MC-Dropout) takes the number of draws from its caller.
num_draws
property
¶
The number of draws of a finite posterior, or None if unlimited.
sample_means ¶
Draw mean predictions at inputs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
inputs
|
PyTree
|
Model inputs with a leading batch dimension. |
required |
key
|
Array
|
The PRNG key selecting the draws. A finite posterior may ignore it. |
required |
num_samples
|
int | None
|
The number of draws |
None
|
Returns:
| Type | Description |
|---|---|
Array
|
The draws' mean predictions, shaped |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in src/stagereg/jax/posterior.py
stagereg.jax.posterior_stage¶
PosteriorStageOptions
dataclass
¶
PosteriorStageOptions(
epochs: int,
num_draws: int = 32,
validation_loader: LoaderFactory | None = None,
validation_metrics: MetricSuite = _default_validation_metrics(),
early_stopper: EarlyStopper | None = None,
event_sinks: Sequence[EventSink] = (),
checkpoint_store: CheckpointStore | None = None,
checkpoint_key: str | None = None,
)
Epoch-loop and prediction options of a posterior stage.
Attributes:
| Name | Type | Description |
|---|---|---|
epochs |
int
|
Maximum number of training epochs. |
num_draws |
int
|
The number of draws |
validation_loader |
LoaderFactory | None
|
Factory producing the |
validation_metrics |
MetricSuite
|
The epoch metrics the posterior predictive is
scored with, reported under their usual names ( |
early_stopper |
EarlyStopper | None
|
Optional early-stopping policy. Refused for an inference method that does not support early stopping. |
event_sinks |
Sequence[EventSink]
|
Event consumers notified of |
checkpoint_store |
CheckpointStore | None
|
Optional store for the best checkpoint, which holds the inference method's full state, and for the finalized checkpoint that replaces it at the end of training and holds the posterior alone. |
checkpoint_key |
str | None
|
The key of the best and finalized checkpoints.
Defaults to |
PosteriorStage
dataclass
¶
PosteriorStage(
inference_method: InferenceMethod,
train_loader: LoaderFactory,
dataset_size: int,
options: PosteriorStageOptions,
prior: Prior = IsotropicGaussianPrior(),
model: Module | None = None,
mean_model_name: str = "mean_model",
variance_model_name: str = "variance_model",
model_name: str = "posterior",
)
Optional Step 3 stage inferring a posterior over mean functions.
It follows the variance stage. The posterior network has the mean
network's parameter tree and is warm-started from a copy of the trained
mean weights; the mean and variance models stay frozen, and the aleatoric
variance is computed on the fly as the mean of the variance model's
prediction. The stage hands its inference method a
PosteriorProblem, drives the epoch loop
with the method's update, and validates every epoch on the current
posterior predictive, skipping epochs that end before the method
has_posterior.
Attributes:
| Name | Type | Description |
|---|---|---|
inference_method |
InferenceMethod
|
The |
train_loader |
LoaderFactory
|
Factory producing the original regression batches. |
dataset_size |
int
|
The number of training examples |
options |
PosteriorStageOptions
|
Epoch-loop and prediction options. |
prior |
Prior
|
The prior over the posterior network's parameters. Defaults to
|
model |
Module | None
|
The posterior network. A copy of it is warm-started, so its own
parameters never change. Its parameter tree must equal the mean
network's, but its module may differ. Defaults to |
mean_model_name |
str
|
Registry name of the trained mean model. |
variance_model_name |
str
|
Registry name of the trained variance model. |
model_name |
str
|
Registry name the posterior is registered under. |
prepare ¶
Warm-start the posterior network and initialize the inference method.
Every check runs before state changes. Afterwards the mean and
variance models are frozen components.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state
|
TrainingState
|
Shared state whose mean and variance stages are ready. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the lifecycle state is not |
TypeError
|
If the mean or variance model is not an NNX module, or
|
Source code in src/stagereg/jax/posterior_stage.py
train ¶
Infer the posterior, register it and transition to POSTERIOR_READY.
With an early stopper and a checkpoint store, every improvement saves a
best checkpoint whose parameters hold the inference method's full
state. After the last epoch the
method resumes from the best checkpoint, if one was saved, and
state returns to the best epoch. The method's
posterior_state is
then stored as state.posterior_state, and, with a checkpoint store,
saved as the finalized checkpoint under the checkpoint key: lifecycle
state POSTERIOR_READY, metadata {"stage": "posterior",
"stage_complete": True}, and no parameters, so neither the mean and
variance weights nor the method's optimizer state are duplicated.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state
|
TrainingState
|
State the stage has been prepared on. |
required |
Returns:
| Type | Description |
|---|---|
StageResult
|
The epoch loop's result: the training metrics of the best epoch |
StageResult
|
when a best checkpoint was restored, otherwise of the last epoch. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the stage was not prepared or training produced a non-finite final loss. |
Source code in src/stagereg/jax/posterior_stage.py
restore ¶
Restore the posterior stage's finalized checkpoint into state.
Call it after the mean stage's
restore and the variance stage's
restore. The inference
method is initialized on the posterior problem of the registered mean
and variance models, then rebuilds the saved posterior with
load_posterior; the
posterior is registered under model_name. Every model component
and optimizer registered before, such as the mean and variance models,
stays registered. Afterwards the state passes
validate.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state
|
TrainingState
|
Training state the mean and variance stages have been restored into. |
required |
checkpoint
|
Checkpoint
|
The posterior stage's finalized checkpoint. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
TypeError
|
If the mean or variance model is not an NNX module, or the checkpoint holds no JAX random key. |
Source code in src/stagereg/jax/posterior_stage.py
validate ¶
Validate posterior-stage lifecycle, ownership and freezing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state
|
TrainingState
|
Shared staged training state. |
required |
Returns:
| Type | Description |
|---|---|
ValidationResult
|
A validation result describing whether Step 3 is ready. |
Source code in src/stagereg/jax/posterior_stage.py
select_checkpoint ¶
Return a reference to the posterior stage's best checkpoint.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state
|
TrainingState
|
Shared staged training state. |
required |
Returns:
| Type | Description |
|---|---|
CheckpointRef
|
Reference to the configured |
CheckpointRef
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If no checkpoint exists under that key. |
Source code in src/stagereg/jax/posterior_stage.py
stagereg.jax.psgld¶
PreconditionedSGLD
dataclass
¶
PreconditionedSGLD(
step_size: float,
burn_in: int = 0,
thinning: int = 1,
decay: float = 0.99,
stability: float = 1e-05,
)
RMSprop-preconditioned stochastic-gradient Langevin dynamics.
Each update takes one step on
the batch's estimate U of the negative log posterior, the problem's
log-likelihood (already scaled to the full data set) plus its prior.
With gradient g = ∇U, the preconditioner tracks
V ← decay · V + (1 − decay) · g² and G = 1 / (stability + √V),
and the parameters move by −(step_size / 2) · G · g plus Gaussian
noise of variance step_size · G. The preconditioner's own drift
correction is neglected, as is usual.
The step is compiled once per init;
the log-likelihood sees each batch's inputs, targets and sample weights but
not its metadata.
Burn-in and thinning count update steps, i.e. training batches, not
epochs. Steps are numbered from 1; the position after step t is
retained when t = burn_in + k · thinning for some k ≥ 1. Until
the first position is retained,
has_posterior is
False and posterior
refuses, so a posterior stage skips validation for the epochs of a
burn-in.
SG-MCMC declares no early-stopping support, so a
PosteriorStage refuses an early stopper
for it and writes only a finalized checkpoint, holding the stacked
retained samples.
Attributes:
| Name | Type | Description |
|---|---|---|
step_size |
float
|
The Langevin step size |
burn_in |
int
|
The number of initial update steps whose positions are
discarded. Defaults to |
thinning |
int
|
Retain one position every |
decay |
float
|
The RMSprop decay of the squared-gradient average, in
|
stability |
float
|
Added to |
supports_early_stopping
property
¶
False: an early stopper would truncate the chain.
init ¶
Start a chain at the problem's warm start, discarding any samples.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
problem
|
PosteriorProblem
|
The posterior problem. |
required |
Source code in src/stagereg/jax/psgld.py
update ¶
Take one Langevin step, retaining the new position if it is due.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
batch
|
Batch
|
The training batch. |
required |
key
|
Array
|
The PRNG key of this step's injected noise. |
required |
Returns:
| Type | Description |
|---|---|
Mapping[str, Any]
|
|
Mapping[str, Any]
|
position before the step. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the method was not initialized. |
Source code in src/stagereg/jax/psgld.py
posterior ¶
Return the posterior of the samples retained so far.
Returns:
| Type | Description |
|---|---|
RetainedSamplesPosterior
|
A finite posterior with one draw per retained sample. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no sample has been retained yet, e.g. during burn-in. |
Source code in src/stagereg/jax/psgld.py
state ¶
Return the chain's full state, from which it can resume.
Returns:
| Type | Description |
|---|---|
PyTree
|
The position, the preconditioner's squared-gradient average, the |
PyTree
|
step count and the retained samples (stacked, possibly none). |
Source code in src/stagereg/jax/psgld.py
load_state ¶
Resume the chain from a state returned by state().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state
|
PyTree
|
A state previously returned by
|
required |
Source code in src/stagereg/jax/psgld.py
posterior_state ¶
Return the retained samples, stacked along a leading axis.
Returns:
| Type | Description |
|---|---|
PyTree
|
The parameter tree with a leading sample axis. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no sample has been retained yet. |
Source code in src/stagereg/jax/psgld.py
load_posterior ¶
Rebuild the posterior of the given retained samples after init.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state
|
PyTree
|
Stacked samples previously returned by
|
required |
Source code in src/stagereg/jax/psgld.py
RetainedSamplesPosterior
dataclass
¶
A finite posterior whose draws are retained parameter samples.
Draw s is the posterior network with the s-th retained
parameters, so it is the same mean function at every input, and every
call uses all the draws.
Attributes:
| Name | Type | Description |
|---|---|---|
mean_function |
Callable[[PyTree, PyTree], Array]
|
Maps |
samples |
PyTree
|
The retained parameter trees, stacked along a leading axis of
length |
sample_means ¶
Evaluate every retained sample's mean function at inputs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
inputs
|
PyTree
|
Model inputs with a leading batch dimension. |
required |
key
|
Array
|
Ignored: the draws are fixed. |
required |
num_samples
|
int | None
|
Must be |
None
|
Returns:
| Type | Description |
|---|---|
Array
|
The mean predictions, shaped |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in src/stagereg/jax/psgld.py
stagereg.jax.rng¶
split_key ¶
Return the next persistent key and one key for a single operation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
Array
|
The current JAX PRNG key. |
required |
Returns:
| Type | Description |
|---|---|
Array
|
A tuple |
Array
|
replace |
tuple[Array, Array]
|
consumed by a single random operation. |
Source code in src/stagereg/jax/rng.py
stagereg.jax.state¶
NnxSnapshot
dataclass
¶
An opaque, complete snapshot of an NNX graph and its state.
Attributes:
| Name | Type | Description |
|---|---|---|
graphdef |
GraphDef
|
The static NNX graph definition. |
state |
State
|
The NNX variable state captured at snapshot time. |
create_optimizer ¶
Create an NNX optimizer that updates all model parameters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
Module
|
The NNX module whose parameters will be optimized. |
required |
transformation
|
GradientTransformation
|
The Optax gradient transformation defining the optimization algorithm. |
required |
Returns:
| Type | Description |
|---|---|
Optimizer
|
An |
Source code in src/stagereg/jax/state.py
initialize_training_state ¶
initialize_training_state(
model: Module,
optimizer: Optimizer,
*,
rng_key: Array,
model_name: str = "model",
optimizer_name: str = "optimizer",
) -> TrainingState
Create generic training state backed by an NNX model and optimizer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
Module
|
The NNX module to register as a model component. |
required |
optimizer
|
Optimizer
|
The NNX optimizer to register as an optimizer state. |
required |
rng_key
|
Array
|
The initial JAX PRNG key for the training state. |
required |
model_name
|
str
|
Key under which |
'model'
|
optimizer_name
|
str
|
Key under which |
'optimizer'
|
Returns:
| Type | Description |
|---|---|
TrainingState
|
A |
TrainingState
|
|
TrainingState
|
|
Source code in src/stagereg/jax/state.py
freeze_training_state ¶
Create an independent, checkpoint-safe snapshot of a training state.
TrainingState holds several mutable containers (metric_history,
checkpoint_registry, parameter_roles) that training runners
keep appending to and mutating in place across epochs. A plain
dataclasses.replace only shallow-copies the state, so a checkpoint
built that way would keep sharing those containers with live
training and silently drift after being "saved". This function
deep-copies every mutable container field instead.
The live model_components and optimizer_states are dropped
from the returned snapshot rather than copied, since they hold
mutable NNX modules/optimizers that keep changing across epochs;
callers that need an immutable capture of model or optimizer state
should use snapshot instead and store it
alongside the frozen training state (see
Checkpoint).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state
|
TrainingState
|
The live training state to snapshot. |
required |
Returns:
| Type | Description |
|---|---|
TrainingState
|
A new |
TrainingState
|
container fields are independent copies, unaffected by later |
TrainingState
|
in-place mutation of |
TrainingState
|
|
Source code in src/stagereg/jax/state.py
snapshot ¶
Capture an NNX module's graph definition and complete variable state.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
module
|
Module
|
The NNX module to snapshot. |
required |
Returns:
| Type | Description |
|---|---|
NnxSnapshot
|
An |
NnxSnapshot
|
graph definition and variable state at the time of the call. |
Source code in src/stagereg/jax/state.py
restore_checkpoint ¶
restore_checkpoint(
checkpoint: Checkpoint,
*,
state: TrainingState,
model: Module,
optimizer: Optimizer,
model_name: str = "model",
optimizer_name: str = "optimizer",
) -> None
Restore a JAX checkpoint into existing live training objects.
The model and optimizer are updated in place so callers retaining their identities, including stage registries, continue to reference the restored objects. Checkpoint-safe training states omit mutable model and optimizer objects, so this helper re-registers the supplied live objects after restoring the backend-neutral state fields.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
checkpoint
|
Checkpoint
|
Checkpoint containing NNX model and optimizer snapshots. |
required |
state
|
TrainingState
|
Existing shared training state to restore in place. |
required |
model
|
Module
|
Live model object updated from |
required |
optimizer
|
Optimizer
|
Live optimizer updated from |
required |
model_name
|
str
|
Registry name for |
'model'
|
optimizer_name
|
str
|
Registry name for |
'optimizer'
|
Raises:
| Type | Description |
|---|---|
TypeError
|
If the checkpoint does not contain NNX snapshots or a JAX random key. |
ValueError
|
If the live model or optimizer is incompatible with the checkpoint snapshot. |
Source code in src/stagereg/jax/state.py
stagereg.jax.supervised¶
make_train_step ¶
make_train_step(
loss: SupervisedLoss,
*,
metrics: Sequence[BatchMetricSpec] = (),
) -> Callable[..., Mapping[str, jax.Array]]
Create a JIT-compiled NNX/Optax supervised training step.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
loss
|
SupervisedLoss
|
A callable computing the supervised loss given a model,
inputs, targets, sample weights, a PRNG key, and a
|
required |
Returns:
| Type | Description |
|---|---|
Callable[..., Mapping[str, Array]]
|
A JIT-compiled function ``train_step(model, optimizer, inputs, |
Callable[..., Mapping[str, Array]]
|
targets, sample_weight, key)`` that performs one gradient update |
Callable[..., Mapping[str, Array]]
|
in place and returns a mapping containing |
Callable[..., Mapping[str, Array]]
|
registered batch metric values. Loss is evaluated on the |
Callable[..., Mapping[str, Array]]
|
pre-update training-state model, while batch metrics are computed |
Callable[..., Mapping[str, Array]]
|
on the same pre-update parameters with |
Callable[..., Mapping[str, Array]]
|
avoid a second state-mutating training-mode forward pass. |
Source code in src/stagereg/jax/supervised.py
run_supervised ¶
run_supervised(
*,
model: Module,
optimizer: Optimizer,
train_loader: LoaderFactory,
loss: SupervisedLoss,
state: TrainingState,
epochs: int,
validation: ValidationStrategy | None = None,
early_stopper: EarlyStopper | None = None,
event_sinks: Sequence[EventSink] = (),
checkpoint_store: CheckpointStore | None = None,
checkpoint_key: str | None = None,
stage: str = "supervised",
model_name: str = "model",
optimizer_name: str = "optimizer",
metrics: MetricSuite | None = None,
) -> StageResult
Train a single NNX model for a fixed or early-stopped number of epochs.
The runner does not restore the best checkpoint: when training ends,
model holds the parameters of the last epoch run. To continue from the
best model, load the checkpoint from checkpoint_store and pass it to
restore_checkpoint.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
Module
|
The NNX module to train, mutated in place. |
required |
optimizer
|
Optimizer
|
The NNX optimizer used to update |
required |
train_loader
|
LoaderFactory
|
Factory producing the training batch loader for a given split and epoch. |
required |
loss
|
SupervisedLoss
|
A callable computing the supervised loss given a model,
inputs, targets, sample weights, a PRNG key, and a
|
required |
state
|
TrainingState
|
The training state to update in place across epochs. |
required |
epochs
|
int
|
The maximum number of epochs to run. |
required |
validation
|
ValidationStrategy | None
|
An optional strategy used to evaluate |
None
|
early_stopper
|
EarlyStopper | None
|
An optional policy that stops training early based on a monitored training or validation metric. |
None
|
event_sinks
|
Sequence[EventSink]
|
Sinks notified of epoch, validation, best-model, and early-stop events. |
()
|
checkpoint_store
|
CheckpointStore | None
|
An optional store used to persist the best
checkpoint when |
None
|
checkpoint_key
|
str | None
|
The checkpoint key under which the best checkpoint
is saved. Defaults to |
None
|
stage
|
str
|
The stage name recorded on |
'supervised'
|
model_name
|
str
|
Name under which |
'model'
|
optimizer_name
|
str
|
Name under which |
'optimizer'
|
metrics
|
MetricSuite | None
|
Optional registered batch/epoch metrics for training. When omitted, only loss is collected. |
None
|
Returns:
| Type | Description |
|---|---|
StageResult
|
A |
StageResult
|
|
StageResult
|
names, and the final training loss. |
StageResult
|
records every metric under its metric tag |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
TypeError
|
If |
Source code in src/stagereg/jax/supervised.py
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 | |
stagereg.jax.supervised_staged¶
materialize_residual_loader ¶
materialize_residual_loader(
mean_model: Module,
source_loader: LoaderFactory,
*,
splits: Sequence[str] = ("train", "validation"),
source_epoch: int = 0,
) -> LoaderFactory
Materialize detached squared residual targets for fixed data splits.
The source loader is consumed exactly once per configured split. The returned loader replays the cached batches for every later epoch, making the Step 1 mean predictions and source data a fixed Step 2 training snapshot.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mean_model
|
Module
|
Trained deterministic mean model. |
required |
source_loader
|
LoaderFactory
|
Loader providing inputs and original regression targets. |
required |
splits
|
Sequence[str]
|
Split names to materialize. Defaults to training and validation. |
('train', 'validation')
|
source_epoch
|
int
|
Source-loader epoch used for the one-time snapshot. |
0
|
Returns:
| Type | Description |
|---|---|
LoaderFactory
|
A loader factory serving cached batches whose targets are detached |
LoaderFactory
|
squared residuals. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If splits are empty, duplicated, unknown at replay time, or produce no batches; if a source batch lacks targets; or if mean predictions and targets have different shapes. |
Source code in src/stagereg/jax/supervised_staged.py
SupervisedStageOptions
dataclass
¶
SupervisedStageOptions(
epochs: int,
validation: ValidationStrategy | None = None,
early_stopper: EarlyStopper | None = None,
event_sinks: Sequence[EventSink] = (),
checkpoint_store: CheckpointStore | None = None,
checkpoint_key: str | None = None,
metrics: MetricSuite = MetricSuite(),
)
Shared epoch-runner options for concrete supervised stages.
Attributes:
| Name | Type | Description |
|---|---|---|
epochs |
int
|
Maximum number of training epochs. |
validation |
ValidationStrategy | None
|
Optional validation strategy. |
early_stopper |
EarlyStopper | None
|
Optional early-stopping policy. |
event_sinks |
Sequence[EventSink]
|
Event consumers notified by the runner. |
checkpoint_store |
CheckpointStore | None
|
Optional best-checkpoint store. |
checkpoint_key |
str | None
|
The checkpoint key the stage saves its best checkpoint
under. Defaults to |
metrics |
MetricSuite
|
Batch and epoch metric registrations. |
MeanStage
dataclass
¶
MeanStage(
model: Module,
optimizer: Optimizer,
train_loader: LoaderFactory,
options: SupervisedStageOptions,
model_name: str = "mean_model",
optimizer_name: str = "mean_optimizer",
loss: SupervisedLoss = (
lambda: make_supervised_loss(SquaredErrorLoss())
)(),
)
Concrete Step 1 stage training a deterministic mean model with MSE.
Attributes:
| Name | Type | Description |
|---|---|---|
model |
Module
|
NNX model producing deterministic mean predictions. |
optimizer |
Optimizer
|
NNX optimizer bound to |
train_loader |
LoaderFactory
|
Factory producing original regression batches. |
options |
SupervisedStageOptions
|
Shared supervised-runner options. |
model_name |
str
|
State registry name for the mean model. |
optimizer_name |
str
|
State registry name for the mean optimizer. |
loss |
SupervisedLoss
|
Scalar supervised loss used to train the mean model. |
prepare ¶
Register Step 1 ownership and initialize the staged lifecycle.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state
|
TrainingState
|
Shared staged training state. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the lifecycle or component ownership is invalid. |
Source code in src/stagereg/jax/supervised_staged.py
train ¶
Train the mean model and transition the workflow to MEAN_READY.
With an early stopper and a checkpoint store configured, the stage then
restores its best checkpoint, so the live mean model holds the best
epoch's weights, and saves it again under the same key as a finalized
MEAN_READY checkpoint with metadata
{"stage": "mean", "stage_complete": True}.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state
|
TrainingState
|
Prepared staged training state. |
required |
Returns:
| Type | Description |
|---|---|
StageResult
|
The supervised runner result, or the restored epoch's training |
StageResult
|
metrics when the best checkpoint was restored. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the stage was not prepared or training is non-finite. |
Source code in src/stagereg/jax/supervised_staged.py
restore ¶
Restore the mean stage's finalized checkpoint into state.
The live model and optimizer take the checkpoint's weights in place and
are registered under model_name and optimizer_name. The restore
is clean-slate, like
restore_checkpoint: other registered
components and optimizers are dropped. Afterwards the state passes
validate, so the variance stage can
be prepared or restored next.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state
|
TrainingState
|
Training state to restore into, typically a fresh one. |
required |
checkpoint
|
Checkpoint
|
The mean stage's finalized checkpoint. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
TypeError
|
As by
|
Source code in src/stagereg/jax/supervised_staged.py
validate ¶
Validate mean-stage lifecycle and ownership invariants.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state
|
TrainingState
|
Shared staged training state. |
required |
Returns:
| Type | Description |
|---|---|
ValidationResult
|
A validation result describing whether Step 1 is ready. |
Source code in src/stagereg/jax/supervised_staged.py
select_checkpoint ¶
Return a reference to the mean stage's best checkpoint.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state
|
TrainingState
|
Shared staged training state. |
required |
Returns:
| Type | Description |
|---|---|
CheckpointRef
|
Reference to the checkpoint key the stage saves under: the |
CheckpointRef
|
configured |
CheckpointRef
|
was configured. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no checkpoint exists under that key. |
Source code in src/stagereg/jax/supervised_staged.py
GammaVarianceStage
dataclass
¶
GammaVarianceStage(
model: Module,
optimizer: Optimizer,
source_loader: LoaderFactory,
options: SupervisedStageOptions,
mean_model_name: str = "mean_model",
mean_optimizer_name: str = "mean_optimizer",
model_name: str = "variance_model",
optimizer_name: str = "variance_optimizer",
splits: Sequence[str] = ("train", "validation"),
source_epoch: int = 0,
validation_factory: Callable[
[LoaderFactory], ValidationStrategy
]
| None = None,
loss: SupervisedLoss = (
lambda: make_supervised_loss(
NegativeLogLikelihoodLoss(
target_transform=add_epsilon()
)
)
)(),
)
Concrete Step 2 stage fitting Gamma-distributed squared residuals.
Attributes:
| Name | Type | Description |
|---|---|---|
model |
Module
|
NNX model producing Gamma residual predictions. |
optimizer |
Optimizer
|
NNX optimizer bound to |
source_loader |
LoaderFactory
|
Factory producing original regression batches. |
options |
SupervisedStageOptions
|
Shared supervised-runner options. |
mean_model_name |
str
|
Registry name of the prepared mean model. |
mean_optimizer_name |
str
|
Registry name of the mean optimizer, kept registered when the stage restores its best checkpoint. |
model_name |
str
|
State registry name for the variance model. |
optimizer_name |
str
|
State registry name for the variance optimizer. |
splits |
Sequence[str]
|
Source split names materialized as residual batches. |
source_epoch |
int
|
Source-loader epoch used for residual materialization. |
validation_factory |
Callable[[LoaderFactory], ValidationStrategy] | None
|
Optional factory adapting the residual loader into a validation strategy. |
loss |
SupervisedLoss
|
Scalar supervised loss used to train the variance model. |
prepare ¶
Validate Step 1 output and materialize fixed residual targets.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state
|
TrainingState
|
Shared state whose mean component is ready. |
required |
Raises:
| Type | Description |
|---|---|
TypeError
|
If the registered mean component is not an NNX module. |
ValueError
|
If lifecycle, ownership, or registrations are invalid. |
Source code in src/stagereg/jax/supervised_staged.py
train ¶
Train the variance model and transition to VARIANCE_READY.
With an early stopper and a checkpoint store configured, the stage then
restores its best checkpoint, so the live variance model holds the best
epoch's weights, while the mean model and, if registered, the mean
optimizer stay registered. It saves the checkpoint again under the same
key as a finalized VARIANCE_READY checkpoint with metadata
{"stage": "variance", "stage_complete": True}.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state
|
TrainingState
|
Prepared state retaining a frozen mean component. |
required |
Returns:
| Type | Description |
|---|---|
StageResult
|
The supervised runner result, or the restored epoch's training |
StageResult
|
metrics when the best checkpoint was restored. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If preparation is incomplete or training is non-finite. |
Source code in src/stagereg/jax/supervised_staged.py
restore ¶
Restore the variance stage's finalized checkpoint into state.
Call it after the mean stage's
restore. The live variance model and
optimizer take the checkpoint's weights in place and are registered
under model_name and optimizer_name. The mean model stays
registered under mean_model_name, and the mean optimizer under
mean_optimizer_name if it was registered before. Afterwards the
state passes validate.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state
|
TrainingState
|
Training state the mean stage has been restored into. |
required |
checkpoint
|
Checkpoint
|
The variance stage's finalized checkpoint. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
TypeError
|
As by
|
Source code in src/stagereg/jax/supervised_staged.py
validate ¶
Validate variance-stage lifecycle, ownership, and freezing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state
|
TrainingState
|
Shared staged training state. |
required |
Returns:
| Type | Description |
|---|---|
ValidationResult
|
A validation result describing whether Step 2 is ready. |
Source code in src/stagereg/jax/supervised_staged.py
select_checkpoint ¶
Return a reference to the variance stage's best checkpoint.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state
|
TrainingState
|
Shared staged training state. |
required |
Returns:
| Type | Description |
|---|---|
CheckpointRef
|
Reference to the checkpoint key the stage saves under: the |
CheckpointRef
|
configured |
CheckpointRef
|
was configured. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no checkpoint exists under that key. |
Source code in src/stagereg/jax/supervised_staged.py
stagereg.jax.validation¶
HeldOutValidation
dataclass
¶
HeldOutValidation(
model: Module,
loader: LoaderFactory,
loss: SupervisedLoss,
metrics: MetricSuite = MetricSuite(),
metadata: dict[str, object] = dict(),
)
Evaluate an NNX model against a held-out validation loader.
Attributes:
| Name | Type | Description |
|---|---|---|
model |
Module
|
The NNX module to evaluate. |
loader |
LoaderFactory
|
Factory producing the validation batch loader for a given split and epoch. |
loss |
SupervisedLoss
|
The supervised loss function used for evaluation. |
metrics |
MetricSuite
|
Registered batch/epoch metrics for validation. |
metadata |
dict[str, object]
|
Arbitrary caller-supplied metadata attached to this strategy. |
__call__ ¶
Evaluate the held-out split after a training epoch.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state
|
TrainingState
|
The current training state, whose |
required |
epoch
|
int
|
The epoch just completed, passed to |
required |
Returns:
| Type | Description |
|---|---|
ValidationResult
|
A |
ValidationResult
|
metric names and |
Raises:
| Type | Description |
|---|---|
TypeError
|
If |