import keras
import networkx as nx
import numpy as np
from bayesflow.adapters import Adapter
from bayesflow.estimators import Estimator
from bayesflow.networks import ConsistencyModel, InferenceNetwork, StableConsistencyModel
from bayesflow.networks.helpers.standardization.standardization import Standardization
from bayesflow.utils.serialization import serializable, serialize
from ..multilevel_simulator.samples import GraphSamples, NodeSamples, concatenate, num_datasets, to_tensors
from ..graphs import InvertedGraph, SimulationGraph
from ..graphs.simulation_graph import data_nodes
from .batches import SimulationDataset, add_sequence_summaries, network_variables, node_values, to_batch
from .encoder import MultilevelEncoder, gather, segment_count, segment_mean, sum_per_dataset
[docs]
@serializable("bayesflow.experimental")
class MultilevelEstimator(Estimator):
"""
Amortized inference for probabilistic models defined by a directed
acyclic graph.
This estimator is for multilevel models. The dependency structure is
encoded in an :class:`bayesflow.experimental.graphs.InvertedGraph`,
which specifies the order in which variables are summarized, conditioned on,
and inferred.
To define the model, see
:class:`bayesflow.experimental.multilevel_simulator.MultilevelSimulator`.
"""
def __init__(
self,
graph: InvertedGraph,
*,
inference_networks: list[InferenceNetwork],
encoders: list[dict[str, keras.Layer]] | None = None,
adapter: Adapter | None = None,
standardize: str | list[str] | None = "inference_variables",
**kwargs,
):
"""
Parameters
----------
graph : bayesflow.experimental.graphs.InvertedGraph
InvertedGraph capturing the dependency structure. Usually obtained
from the :py:class:`MultilevelSimulator` that defined the model, by
expanding its :py:class:`SimulationGraph` and inverting the result::
graph = simulator.graph.expand().invert()
inference_networks: list[InferenceNetwork]
The inference networks used for posterior estimation. Each network
is responsible for a subset of the variables. Call the
:py:meth:`networks` method of the `InvertedGraph` for an overview
of how variables are assigned to inference networks.
encoders: list[dict[str, keras.Layer]], optional
Only needed to customize the encoders. The layers that summarize
the observed data, so it can be used to condition an inference
network (default is an :py:class:`MultilevelEncoder` for every
node an inference network conditions on). Give one dictionary per
inference network, in the order of ``graph.networks()``, that maps
each data node the network conditions on to its encoder.
An encoder must return one encoding per row, like
:py:class:`MultilevelEncoder`.
adapter: bayesflow.adapters.Adapter, optional
Adapter for data processing (default is an empty Adapter).
standardize : str | list[str] | None
The variables to standardize before passing to the networks.
Can be either "all", "inference_variables", or any subset of the
variables generated by the SimulationGraph the supplied InvertedGraph
was built from (default is "inference_variables").
**kwargs : dict, optional
Additional arguments passed to the
:py:class:`bayesflow.estimators.Estimator` class.
"""
super().__init__(**kwargs)
self.graph = graph
self.inference_networks = inference_networks
self.adapter = adapter or Adapter()
self.standardize = standardize
simulation_graph = graph.expanded_graph.simulation_graph
self.data_nodes = data_nodes(simulation_graph)
self.networks = graph.networks()
for node in simulation_graph:
if simulation_graph.in_degree(node) == 0 and simulation_graph.nodes[node].get("reps", 1) != 1:
raise NotImplementedError(
f"Root node {node} is repeated, but root nodes must have one row per dataset."
)
self.condition_nodes = []
self.sequential = []
for i, target_nodes in enumerate(self.networks):
if not graph.is_amortizable(target_nodes[0]):
if len(target_nodes) > 1:
raise NotImplementedError(f"Network for {target_nodes} infers several non-amortizable nodes.")
if self.inference_networks[i].mask_handler.missing_target_prob > 0.0:
raise NotImplementedError(
f"Network for {target_nodes} cannot marginalize target features without an explicit "
"feature-mask protocol for sequence summaries."
)
self.sequential.append(target_nodes[0])
self.condition_nodes.append(graph.conditions(target_nodes))
if encoders is None:
encoders = []
for condition_nodes in self.condition_nodes:
network_encoders = {}
for node in condition_nodes:
if node in self.data_nodes:
network_encoders[node] = MultilevelEncoder()
encoders.append(network_encoders)
self.encoders = encoders
[docs]
def sample(
self, *, num_samples: int, conditions: GraphSamples, format: str = "long"
) -> GraphSamples | dict[str, np.ndarray]:
"""
Draws posterior samples given observed data.
The `conditions` are preprocessed using the `adapter`. Samples are
converted to NumPy arrays after inference.
Parameters
----------
num_samples : int
Number of posterior samples per dataset.
conditions : GraphSamples
The observed data, as returned by :py:func:`from_table`, or
simulations of the MultilevelSimulator, as returned by its
:py:meth:`sample` method.
Only the values of the data nodes are used.
format : {"long", "tensor"}, optional
The format of the samples (default is "long"). The long format
works for every dataset; the tensor format only works if all
datasets have the same structure.
Returns
-------
GraphSamples or dict[str, np.ndarray]
In long format, the samples of every latent node as
:py:class:`GraphSamples`. Each node keeps the indices of `conditions`,
and each variable has shape `(num_rows, num_samples, dim)`.
In tensor format, one array per variable, as returned by
:py:func:`to_tensors`: shape `(num_datasets, num_samples, dim)` for
root nodes, and `(num_datasets, num_samples, num_groups, dim)` for
all other nodes.
Raises
------
ValueError
If `format` is neither "long" nor "tensor", or if `format` is "tensor"
and the datasets differ in structure. In the latter case, use the long
format, or convert a subset of datasets with :py:func:`to_tensors`.
"""
if format not in ("long", "tensor"):
raise ValueError(f"format must be 'long' or 'tensor', not '{format}'.")
observed = {}
for node, samples in conditions.items():
if node in self.data_nodes:
observed[node] = samples
else:
observed[node] = NodeSamples(samples.indices, {})
batch = self.to_batch(concatenate([observed] * num_samples))
batch = self.standardized(batch, stage="inference")
for i, target_nodes in enumerate(self.networks):
if target_nodes[0] in self.sequential:
self.sample_sequentially(batch, i)
continue
network_conditions = self.network_conditions(batch, i)
batch_shape = (keras.ops.shape(network_conditions)[0],)
samples = self.inference_networks[i].sample(batch_shape, conditions=network_conditions)
for node, values in self.split_values(samples, target_nodes).items():
batch[node]["values"] = values
posterior = {}
for target_nodes in self.networks:
for node in target_nodes:
values = {}
for variable, value in batch[node]["values"].items():
value = self.standardizer.maybe_standardize(value, variable, forward=False)
value = keras.ops.convert_to_numpy(value)
value = value.reshape(num_samples, -1, value.shape[-1])
values[variable] = np.moveaxis(value, 0, 1)
values = self.adapter(values, inverse=True, strict=False)
values = keras.tree.map_structure(keras.ops.convert_to_numpy, values)
posterior[node] = NodeSamples(conditions[node].indices, values)
if format == "tensor":
return to_tensors(posterior)
return posterior
[docs]
def log_prob(self, data: GraphSamples) -> np.ndarray:
"""
computes the log-probability of given data under the model. The `data`
is preprocessed using the `adapter`. Log-probabilities are returned as
Numpy arrays.
Parameters
----------
data : GraphSamples
Samples of every node, for example as returned by the
:py:meth:`sample` method of the MultilevelSimulator.
Returns
-------
np.ndarray
Log-probabilities of the distribution `p(latent variables | data)`,
one per dataset, with shape `(num_datasets,)`. They include the
log-determinants of the standardization and the adapter, so they
refer to the variables before preprocessing.
"""
for network, target_nodes in zip(self.inference_networks, self.networks):
if isinstance(network, (ConsistencyModel, StableConsistencyModel)):
raise NotImplementedError(
f"The {type(network).__name__} for {target_nodes} has no tractable density, "
"so log_prob is not available."
)
batch = self.to_batch(data)
datasets = num_datasets(data)
log_prob = keras.ops.zeros(datasets)
for node, entries in batch.items():
dataset_ids = entries["indices"]["dataset"]
values = {}
for variable, value in entries["values"].items():
values[variable], log_det_jac = self.standardizer.maybe_standardize(value, variable, log_det_jac=True)
if node not in self.data_nodes and variable in self.standardizer.standardize:
log_prob += sum_per_dataset(log_det_jac, dataset_ids, datasets)
entries["values"] = values
for i, target_nodes in enumerate(self.networks):
variables, conditions = self.network_inputs(batch, i)
dataset_ids = batch[target_nodes[0]]["indices"]["dataset"]
network_log_prob = self.inference_networks[i].log_prob(variables, conditions=conditions)
log_prob += sum_per_dataset(network_log_prob, dataset_ids, datasets)
for node in target_nodes:
_, log_det_jac = self.adapter(data[node].values, strict=False, log_det_jac=True)
for value in log_det_jac.values():
value = keras.ops.cast(value, keras.config.floatx())
log_prob += sum_per_dataset(value, dataset_ids, datasets)
return keras.ops.convert_to_numpy(log_prob)
[docs]
def build_dataset(self, *, simulator, batch_size, num_batches):
return SimulationDataset(simulator, batch_size, self.to_batch, num_batches)
[docs]
def fit(
self,
*,
dataset: GraphSamples | keras.utils.PyDataset | None = None,
validation_data: GraphSamples | keras.utils.PyDataset | None = None,
**kwargs,
):
"""
Trains the estimator on the provided dataset or on-demand data
generated from the given simulator.
If `dataset` is not provided, a dataset is built from the `simulator`.
Parameters
----------
dataset : GraphSamples or keras.utils.PyDataset, optional
A dataset containing simulations for training, for example as
returned by the :py:meth:`sample` method of the MultilevelSimulator.
The datasets are shuffled before every epoch.
If provided, `simulator` must be None.
simulator : MultilevelSimulator, optional
A simulator used to generate a dataset. If provided, `dataset`
must be None.
validation_data : GraphSamples or keras.utils.PyDataset, optional
Simulations to compute the validation loss on after every epoch.
**kwargs
Additional keyword arguments passed to `keras.Model.fit()`,
including:
batch_size : int
Number of datasets per gradient update. Required, unless
`dataset` is a `keras.utils.PyDataset`.
num_batches : int
Number of batches per epoch. Required if `simulator` is provided.
validation_batch_size : int, optional
Number of datasets per validation batch (default is `batch_size`).
epochs : int, default=1
verbose : {"auto", 0, 1, 2}, default="auto"
Verbosity mode. 0 = silent, 1 = progress bar, 2 = one line per
epoch.
callbacks : list of keras.callbacks.Callback, optional
List of callbacks to apply during training.
initial_epoch : int, default=0
Epoch at which to start training (useful for resuming training).
Returns
-------
keras.callbacks.History
A history object containing the training loss and metrics values.
Raises
------
ValueError
If both `dataset` and `simulator` is provided or neither is provided.
"""
if isinstance(validation_data, dict):
validation_batch_size = kwargs.pop("validation_batch_size", kwargs.get("batch_size"))
validation_data = SimulationDataset(validation_data, validation_batch_size, self.to_batch)
if isinstance(dataset, dict):
dataset = SimulationDataset(dataset, kwargs.pop("batch_size"), self.to_batch)
return super().fit(dataset=dataset, validation_data=validation_data, **kwargs)
[docs]
def compute_metrics(self, stage: str = "training", **batch):
total_loss = 0
metrics = {}
if not self.built:
self.build_from_data(batch)
batch = self.standardized(batch, stage)
training = stage == "training"
for i, target_nodes in enumerate(self.networks):
variables, conditions = self.network_inputs(batch, i, training=training)
weights = batch[target_nodes[0]].get("weights")
if weights is not None and isinstance(self.inference_networks[i], ConsistencyModel):
weights = keras.ops.expand_dims(weights, -1)
network_metrics = self.inference_networks[i].compute_metrics(
variables, conditions=conditions, sample_weight=weights, stage=stage
)
total_loss += network_metrics["loss"]
for name, value in network_metrics.items():
metrics[f"network_{i}/{name}"] = value
metrics["loss"] = total_loss
return metrics
[docs]
def get_config(self):
config = {
"graph": self.graph,
"inference_networks": self.inference_networks,
"encoders": self.encoders,
"adapter": self.adapter,
"standardize": self.standardize,
}
return super().get_config() | serialize(config)
[docs]
def get_build_config(self):
return {"variable_dims": self.variable_dims}
[docs]
def build_from_config(self, config):
self.variable_dims = config["variable_dims"]
variable_shapes = {}
standardized_variables = []
for node, dims in self.variable_dims.items():
for variable, dim in dims.items():
variable_shapes[variable] = (None, dim)
if self.standardize == "all":
standardized_variables.append(variable)
elif self.standardize == "inference_variables":
if node not in self.data_nodes:
standardized_variables.append(variable)
elif variable in (self.standardize or []):
standardized_variables.append(variable)
self.standardizer = Standardization(standardized_variables)
self.standardizer.build(variable_shapes)
simulation_graph = self.graph.expanded_graph.simulation_graph
samples = placeholder_samples(simulation_graph, self.variable_dims)
batch = self.to_batch(samples, adapter=Adapter())
for i, network in enumerate(self.inference_networks):
if not network.built:
variables, conditions = self.network_inputs(batch, i)
network.build(keras.ops.shape(variables), keras.ops.shape(conditions))
self.built = True
self.compute_metrics(**batch, stage="validation")
[docs]
def to_batch(self, samples: GraphSamples, adapter: Adapter | None = None, padded: bool = False) -> dict:
return to_batch(samples, self.graph, adapter or self.adapter, padded)
[docs]
def network_conditions(self, batch: dict, i: int, training: bool = False):
# the nodes of a network share their rows, so the first one stands in for all of them
target = self.networks[i][0]
target_indices = batch[target]["indices"]
num_target_rows = keras.ops.shape(target_indices[target])[0]
latent = []
observed = []
for node in self.condition_nodes[i]:
if node in self.data_nodes:
observed.append(node)
else:
latent.append(node)
conditions = []
for data_node in observed:
data_indices = batch[data_node]["indices"]
if target not in data_indices:
raise NotImplementedError(f"{target} conditions on {data_node}")
features = [node_values(batch, data_node)]
for node in latent:
if node in data_indices:
values = node_values(batch, node)
features.append(gather(values, data_indices[node]))
groups = []
for name in sorted(batch[data_node]["groups"]):
groups.append(batch[data_node]["groups"][name])
observations = keras.ops.concatenate(features, axis=-1)
encoded = self.encoders[i][data_node](observations, groups, training=training)
target_ids = data_indices[target]
pooled = segment_mean(encoded, target_ids, num_target_rows)
counts = segment_count(target_ids, num_target_rows, pooled.dtype)
conditions.append(pooled)
conditions.append(keras.ops.log1p(counts))
for node in latent:
if node in target_indices:
values = node_values(batch, node)
conditions.append(gather(values, target_indices[node]))
return keras.ops.concatenate(conditions, axis=-1)
[docs]
def split_values(self, samples, target_nodes: list[str]) -> dict[str, dict]:
values_by_node = {}
start = 0
for node in target_nodes:
values = {}
for variable in sorted(self.variable_dims[node]):
dim = self.variable_dims[node][variable]
values[variable] = samples[:, start : start + dim]
start += dim
values_by_node[node] = values
return values_by_node
[docs]
def sample_sequentially(self, batch: dict, i: int):
node = self.networks[i][0]
positions = batch[node]["steps"]["positions"]
values = {}
for variable, dim in self.variable_dims[node].items():
values[variable] = keras.ops.zeros((len(positions), dim))
batch[node]["values"] = values
# the conditions only change through the sequence summaries
conditions = self.network_conditions(batch, i)
for step in range(int(np.max(positions)) + 1):
step_conditions = add_sequence_summaries(batch, node, conditions)
samples = self.inference_networks[i].sample((len(positions),), conditions=step_conditions)
is_step = (positions == step)[:, None]
for variable, value in self.split_values(samples, [node])[node].items():
values[variable] = keras.ops.where(is_step, value, values[variable])
[docs]
def standardized(self, batch: dict, stage: str) -> dict:
result = {}
for node, entries in batch.items():
values = {}
for variable, value in entries["values"].items():
values[variable] = self.standardizer.maybe_standardize(value, variable, stage=stage)
result[node] = entries | {"values": values}
return result
[docs]
def build_from_data(self, batch):
variable_dims = {}
for node, entries in batch.items():
variable_dims[node] = {}
for variable, value in entries["values"].items():
variable_dims[node][variable] = int(keras.ops.shape(value)[-1])
self.build_from_config({"variable_dims": variable_dims})
def _batch_size_from_data(self, data):
root = self.networks[0][0]
return keras.ops.shape(data[root]["indices"][root])[0]
def placeholder_samples(graph: SimulationGraph, variable_dims: dict[str, dict[str, int]]) -> GraphSamples:
samples = {}
for node in graph:
indices = {}
for column in ["dataset", *nx.ancestors(graph, node), node]:
indices[column] = np.zeros(1, dtype=np.int64)
values = {}
for variable, dim in variable_dims[node].items():
values[variable] = np.zeros((1, dim))
samples[node] = NodeSamples(indices, values)
return samples