dingo.core.inference package

Submodules

dingo.core.inference.composer module

The chain composer and runner of the factorized sampler.

A ChainComposer runs a chain of steps (dingo.core.inference.steps) in order, building up a table of named parameter columns together with the summed log probability, and can re-evaluate that log probability at given samples by folding the chain in reverse. GibbsBlock wraps a Gibbs loop as a single density-free step, and ComposedSampler is the generic runner that returns the samples as a DataFrame. The concepts are explained in the “Sampling chains” page of the documentation.

class dingo.core.inference.composer.ChainComposer(steps: list[Step])

Bases: object

Runs a chain of steps in order, building up a table of samples and the summed proposal log probability.

The composer holds the steps as an ordered list. At construction it checks that the order is consistent: every column a step reads must be produced by an earlier step, and no step may overwrite an existing column, except a Reparametrization replacing its own inputs. Sampling folds the steps forward, drawing at each step that draws and summing the log-probability contributions; log_prob folds the steps in reverse to re-evaluate the same density at given samples. If any step is density-free (a GibbsBlock), the chain has no tractable density and sample omits log_prob.

This one class covers plain NPE, single-step GNPE, prior conditioning, synthetic phase, and, through GibbsBlock, multi-iteration GNPE. See the “Sampling chains” page of the documentation.

Parameters:

steps (list[Step]) – The chain, in order.

Raises:

ValueError – If a step reads a column that no earlier step produces, or would overwrite an existing column.

log_prob(samples: dict[str, Tensor], context: SamplerContext) → Tensor

Evaluate the chain’s proposal log probability at given samples.

Importance sampling does not need this: the proposal density of a chain’s own samples is returned by sample_and_log_prob and stored with them. The reverse fold evaluates the same density at parameters the chain did not draw (for diagnostics, or to compare proposals), and is what makes the stored density a well-defined function of the final columns. The steps are folded in reverse order, so that the columns are restored to the state each step saw during sampling: a Reparametrization rebuilds the inputs it replaced via inverse (for example ra@t_ref from the event-frame ra) and contributes -log|det J|; a Factor contributes its log_prob at the restored conditioning; a TargetCorrection contributes nothing.

Parameters:
  • samples (dict[str, torch.Tensor]) – The chain’s output columns, one value per row. Replaced inputs are rebuilt by the reparametrization inverses, and side channels are not needed.

  • context (SamplerContext) – The per-event shared state.

Returns:

The proposal log probability per row.

Return type:

torch.Tensor

Raises:

ValueError – If the chain is density-free (contains a GibbsBlock).

sample(num_samples: int | Sequence[int], context: SamplerContext, batch_size: int | None = None) → dict[str, Tensor]

Draw samples and return them as a single dict.

The arguments are those of sample_and_log_prob.

Returns:

The chain’s columns, plus a log_prob entry unless the chain is density-free.

Return type:

dict[str, torch.Tensor]

sample_and_log_prob(num_samples: int | Sequence[int], context: SamplerContext, batch_size: int | None = None) → tuple[dict[str, Tensor], Tensor | None]

Draw samples from the chain.

Parameters:
  • num_samples (int or sequence of int) – How many samples to draw for each row of the table, at each step that draws. An int is the count for the first drawing step (typically the flow), after which any later drawing step draws one sample per row. This is the usual case: the int is the total for a chain with a single root row (a pin or a flow at the root), or the number per table row for a chain rooted in a SampleTableFactor. A sequence instead gives one count per drawing step, in chain order, so that a later step may draw several samples for each row it receives (for example several extrinsic draws per intrinsic sample). Steps that do not draw (pins, tables, reparametrizations, target corrections) take no count. A chain with no drawing step at all (a stored table run through a reparametrization, say) runs once, with num_samples=1.

  • context (SamplerContext) – The per-event shared state.

  • batch_size (int, optional) – Chunk the first count into batches of this size, to cap the peak memory. None draws in one pass. For a chain rooted in a sample table, the rows of the result are then grouped by chunk rather than by table row.

Returns:

  • samples (dict[str, torch.Tensor]) – The chain’s columns, with (root rows) * prod(counts) rows.

  • log_prob (torch.Tensor or None) – The proposal log probability per row, or None if any step is density-free.

Raises:

ValueError – If a sequence of counts does not have one entry per drawing step, a count is below 1, or the chain has no drawing step and num_samples is not 1.

class dingo.core.inference.composer.ComposedSampler(composer: ChainComposer, context: SamplerContext)

Bases: object

Runs a ChainComposer over a SamplerContext and returns the samples as a DataFrame.

All domain-specific processing lives in the chain’s steps and in the context, so the runner itself is domain-agnostic; it also assembles the provenance record of how the samples were made (sampler_provenance). The gravitational-wave subclass is dingo.gw.inference.sampler.GWComposedSampler.

Parameters:
run_sampler(num_samples: int | Sequence[int], batch_size: int | None = None) → DataFrame

Draw samples and store them as a DataFrame.

Parameters:
  • num_samples (int or sequence of int) – The number of samples per root row, or one count per drawing step (see ChainComposer.sample_and_log_prob).

  • batch_size (int, optional) – Chunk size for drawing. None draws in one pass.

Returns:

One row per sample, with a log_prob column unless the chain is density-free. Also stored as self.samples, with the request as self.num_samples.

Return type:

pandas.DataFrame

sampler_provenance() → dict

Provenance of how the samples were made: the executed chain in order (one descriptor per step, via Step.describe()), the num_samples requested of run_sampler (an int, or one count per drawing step; absent before sampling), plus anything in provenance_extra. A domain runner stores the block with its exported result (the gravitational-wave subclass as settings[“sampler”] of the Result). It is purely a record; nothing consumes it at load time.

Returns:

The provenance block, of literal values only.

Return type:

dict

class dingo.core.inference.composer.GibbsBlock(init_factor: Factor, factors: list[Factor], num_iterations: int)

Bases: object

A step that runs blocked Gibbs sampling internally and yields no log probability.

The block seeds its state from an init factor, then sweeps its list of factors in order for num_iterations iterations; each factor conditions on the current state and overwrites its own block. Because of the cyclic dependency the result has no tractable density, so the step returns None for the log probability, and a chain containing it is density-free: its samples carry no log_prob, and the density must be recovered afterwards (by fitting an unconditional model to the samples and taking a chain step with it). Dingo uses this for multi-iteration GNPE, with the factors in dingo.gw.inference.steps, but the loop is generic.

Batching is handled by the enclosing ChainComposer, which runs the whole loop for each chunk of walkers.

Parameters:
  • init_factor (Factor) – Seeds the state (for example an init network’s detector times).

  • factors (list[Factor]) – The factors swept in order in each iteration. Each conditions on the current state and overwrites its own block.

  • num_iterations (int) – Number of Gibbs sweeps.

annotations: list[str] = []
describe() → dict

Describe the Gibbs structure, with nested descriptors for the init factor and the swept factors. See Factor.describe.

draws = True
property produces: list[str]

The emitted columns (the swept parameter blocks).

sample_and_log_prob(num_samples: int, context: SamplerContext, given: dict[str, Tensor] | None = None) → tuple[dict[str, Tensor], None]

Run the Gibbs loop.

Parameters:
  • num_samples (int) – The number of walkers, one row each (the block’s count in the chain).

  • context (SamplerContext) – The per-event shared state.

  • given (dict, optional) – Ignored; the block is unconditioned.

Returns:

  • samples (dict[str, torch.Tensor]) – The swept parameter blocks, one row per walker.

  • log_prob (None)

dingo.core.inference.composer.chunk_and_concat(total: int, batch_size: int | None, run_once: Callable[[int], tuple[dict[str, Tensor], Tensor | None]]) → tuple[dict[str, Tensor], Tensor | None]

Run run_once in chunks and concatenate the results.

This caps the peak memory at one chunk. The log probability may be None, for a density-free chain (one containing a GibbsBlock).

Parameters:
  • total (int) – Total number of samples to produce.

  • batch_size (int, optional) – Chunk size; None runs total in a single call.

  • run_once (callable) – run_once(n) -> (samples, log_prob) for one chunk of n samples.

Returns:

  • samples (dict[str, torch.Tensor]) – The concatenated per-name sample tensors.

  • log_prob (torch.Tensor or None) – The concatenated log-probs, or None when run_once returns None.

dingo.core.inference.context module

The per-event context protocol of the factorized sampler.

Every step of a chain reads the event through a shared context: the data in the representation the networks were trained on, the per-event metadata, and the likelihood. This module defines the protocol; the gravitational-wave implementation is dingo.gw.inference.context.GWSamplerContext.

class dingo.core.inference.context.SamplerContext(*args, **kwargs)

Bases: Protocol

Protocol for the per-event state shared by all steps of a chain.

A context holds the event data and metadata, and everything derived from them that a step may need: the data in the representation the networks were trained on (prepared_data), and the likelihood. Steps never receive the data directly; they read it through the context. Concrete implementations are domain-specific; see dingo.gw.inference.context.GWSamplerContext.

Variables:
  • event_metadata (dict or None) – Per-event metadata, such as the event time and analysis settings.

  • device (torch.device or str) – The device the chain runs on. Steps that create new tensors, rather than transforming existing ones, create them on this device so that they can be combined with the outputs of networks running on a GPU.

device: device | str
event_metadata: dict | None
likelihood()

The likelihood of the event data, for likelihood-based factors (such as the synthetic phase) and for importance sampling.

prepared_data(conditioning=None) → Tensor

The event data in the representation the networks condition on.

Parameters:

conditioning (dict[str, torch.Tensor], optional) – Chain columns available to a conditioned factor. Without it, the single shared representation is returned, computed once and cached. With it, the result has one data row per conditioning row. Only the columns the data preparation depends on (for example a heterodyning proxy) affect the result; the other columns condition the network alone.

Return type:

torch.Tensor

dingo.core.inference.steps module

Chain steps of the factorized sampler: factors, reparametrizations, and target corrections.

Dingo samples the posterior with a chain of steps, run by the composer in dingo.core.inference.composer. The factors among the steps write the posterior as an ordered product of conditionals,

q(theta_1, …, theta_n | d) = prod_i q_i(theta_i | theta_<i, d),

each drawing one block of parameters and returning its own log probability. Other steps reparametrize existing columns, or annotate the importance-sampling target. Everything in this module is domain-agnostic. The gravitational-wave steps and the per-event context live in dingo.gw.inference. The concepts are explained in the “Sampling chains” page of the documentation.

Factors work in physical parameter space. A network’s standardized space exists only inside its forward pass, mediated by Standardization.

class dingo.core.inference.steps.DeltaFactor(values: dict[str, float])

Bases: Factor

A point mass q_i = delta(theta_i - c) that pins parameters to fixed values.

A delta factor is used in two ways: as the root of a chain, supplying pinned values (a known proxy, or a prior-conditioning pin) that later factors condition on; and as a filler, supplying delta-prior parameters that the network does not infer. It contributes zero to the proposal log probability: the chain’s log probability covers only the parameters that are sampled, and the pinned block is conditioned on rather than integrated over. The importance-sampling target uses the same convention, so the factor cancels in the weights.

Every draw returns the same values, so the factor does not draw (draws = False). As a root it is run once, and the chain’s num_samples is drawn by the first step that does draw.

Parameters:

values (dict[str, float]) – The pinned value of each parameter.

describe() → dict

The default descriptor, plus the pinned values.

draws = False
log_prob(theta_i, context, given=None)

Return zero for every row.

The chain only evaluates log_prob at its own samples, so the point mass is always evaluated on its support; values off the support are not represented. See Factor.log_prob.

sample_and_log_prob(num_samples, context, given=None)

Return num_samples copies of the pinned values, with zero log probability. See Factor.sample_and_log_prob.

class dingo.core.inference.steps.Factor

Bases: ABC

Base class for a factor: one conditional distribution q_i(theta_i | theta_<i, d) in the product that makes up the proposal.

A factor draws one block of parameters and returns its own log probability, both in physical parameter space (any network standardization is internal). When conditioned, it draws num_samples samples for each row of the conditioning, returning n_rows * num_samples rows with the draws for a given conditioning row adjacent. This matches the convention of the posterior models, sample_and_log_prob(*context, num_samples=n) -> (n_rows, n, dim).

Variables:
  • parameters (list[str]) – The parameters this factor produces.

  • conditioning (list[str]) – Earlier chain columns this factor conditions on. The data is not listed here; it enters through the context.

  • draws (bool) – Whether the factor draws new samples (the default) or is a point mass or fixed table that is run once. The chain’s sample counts go to the steps that draw, one each; an int num_samples is the count for the first.

  • annotations (list[str]) – Columns the factor emits beyond its parameters that are kept in the chain output for importance sampling, such as a cached log likelihood. They are part of produces; side channels are dropped. Target corrections declare their columns the same way.

annotations: list[str] = []
conditioning: list[str]
describe() → dict

Describe the step for the provenance record of a saved result.

The default descriptor records the class name, the parameters produced, and the conditioning. Steps with settings worth recording override this. The descriptor must be literal-only: every value round-trips through str and ast.literal_eval in the saved settings.

Return type:

dict

draws = True
abstract log_prob(theta_i: dict[str, Tensor], context: SamplerContext, given: dict[str, Tensor] | None = None) → Tensor

Evaluate the log probability at given parameter values.

Parameters:
  • theta_i (dict[str, torch.Tensor]) – Values of this factor’s parameters, one row each.

  • context (SamplerContext) – The per-event shared state.

  • given (dict[str, torch.Tensor], optional) – The conditioning columns, one row per row of theta_i.

Returns:

The log probability per row, in physical parameter space.

Return type:

torch.Tensor

parameters: list[str]
property produces: list[str]

parameters and annotations, plus any side channels (overridden then). A side channel is an intermediate that later steps may read, such as the detector times a GNPE network recomputes; unlike an annotation, it is not part of the chain’s output.

Type:

The emitted columns

abstract sample_and_log_prob(num_samples: int, context: SamplerContext, given: dict[str, Tensor] | None = None) → tuple[dict[str, Tensor], Tensor]

Draw samples and evaluate their log probability.

Parameters:
  • num_samples (int) – Number of samples to draw per conditioning row.

  • context (SamplerContext) – The per-event shared state.

  • given (dict[str, torch.Tensor], optional) – The conditioning columns, one row each. Omitted for an unconditioned factor.

Returns:

  • samples (dict[str, torch.Tensor]) – The drawn values, keyed by parameter name, with n_rows * num_samples rows. The dict may also contain named columns beyond parameters.

  • log_prob (torch.Tensor) – The log probability of each row, in physical parameter space.

class dingo.core.inference.steps.FlowFactor(model: BasePosteriorModel, aliases: dict[str, str] | None = None)

Bases: Factor

Factor wrapping a posterior model (an NPE flow, FMPE, and so on).

The factor handles the network’s standardization internally, so its interface is in physical parameter space. Three kinds of model are supported. A data-conditional model draws from the shared data representation, SamplerContext.prepared_data() (one tensor, or the list of tensors a tokenized network takes). A model with context_parameters (for example GNPE proxies, or a prior-conditioning pin) additionally conditions on those chain columns, and the data representation may depend on their values. An unconditional model (flagged unconditional in its training metadata, such as a density-recovery NDE) takes no input at all and does not touch the context.

A factor may expose a trained parameter under an alias (for example ra as ra@t_ref), so that a later step can convert reference frames by name.

Parameters:
  • model (BasePosteriorModel) – The posterior model (NPE flow, FMPE, …) wrapped by this factor. The parameter names and any context_parameters are read from its training metadata (for an unconditional NDE these are its own, e.g. the GNPE proxies it was trained on).

  • aliases (dict[str, str], optional) – Map from a trained parameter name to the name exposed in the chain (for example {“ra”: “ra@t_ref”}), so that a later reparametrization can convert reference frames by name without retraining.

describe() → dict

The default descriptor, plus whether the model is unconditional.

log_prob(theta_i, context, given=None)

Evaluate the model’s log probability at theta_i, in physical parameter space. See Factor.log_prob.

sample_and_log_prob(num_samples, context, given=None)

Draw samples from the model.

A data-conditional model draws from the shared data representation; a model with context parameters draws num_samples for each row of given, with the data prepared per row; an unconditional model draws with no input. See Factor.sample_and_log_prob for the arguments and the row layout.

class dingo.core.inference.steps.PriorFactor(prior)

Bases: Factor

An unconditioned factor that draws a block of parameters from a prior.

The prior is any object with the interface of a bilby PriorDict (sample and ln_prob). Drawing from the prior makes the prior the proposal for this block, so its log probability enters the chain’s proposal density and cancels against the importance-sampling target. It is used, for example, to add detector calibration parameters to previously drawn samples, one draw per sample.

Parameters:

prior (bilby.core.prior.PriorDict) – The prior to draw from. Constraints are applied but not sampled. Fixed parameters (e.g. delta functions) are emitted at their values, and, as for DeltaFactor, contribute nothing to the log probability (their density at the drawn point is infinite).

describe() → dict

The default descriptor, plus the prior of each parameter.

log_prob(theta_i, context, given=None)

Evaluate the prior log probability. See Factor.log_prob.

sample_and_log_prob(num_samples, context, given=None)

Draw num_samples samples from the prior, with their prior log probability. See Factor.sample_and_log_prob.

class dingo.core.inference.steps.ProxyOffsetReparam(parameter_name: str)

Bases: Reparametrization

Reconstruct a physical parameter from a network’s offset output and its proxy, X = delta_X + X_proxy.

A proxy-conditioned network (for example the chirp-mass prior conditioning of DINGO-BNS) infers the offset delta_X = X - X_proxy rather than X itself. This step rebuilds X. The offset is its input, replaced by X; the proxy is read-only conditioning and stays in the chain, where it is recorded with the samples (like the GNPE time proxies). At a fixed proxy the map is a pure shift, so log_det is zero; inverse recovers the offset from the proxy, which the reverse fold supplies.

Parameters:

parameter_name (str) – The physical parameter name X. The step reads delta_X and X_proxy and produces X.

forward(given, context)

Apply the change of variables.

Parameters:
  • given (dict[str, torch.Tensor]) – The inputs and conditioning columns, one row each.

  • context (SamplerContext) – The per-event shared state.

Returns:

The parameters columns.

Return type:

dict[str, torch.Tensor]

inverse(params, context, given=None)

Rebuild the inputs from the produced parameters.

Parameters:
  • params (dict[str, torch.Tensor]) – The parameters columns, one row each.

  • context (SamplerContext) – The per-event shared state.

  • given (dict[str, torch.Tensor], optional) – The read-only conditioning columns, still in the chain, for example a proxy the map shifts by. Maps that depend only on their own outputs may ignore it.

Returns:

The inputs columns.

Return type:

dict[str, torch.Tensor]

class dingo.core.inference.steps.Reparametrization

Bases: ABC

Base class for a reparametrization: a deterministic, invertible change of variables applied to existing chain columns.

A reparametrization does not sample. Its forward map takes its inputs, along with any read-only conditioning, to the parameters it produces, which replace the inputs in the chain; it contributes -log|det J| to the proposal log probability (zero for a measure-preserving map, the default). It is one-to-one, with one output row per input row, so it carries no sample multiplicity. The inverse map rebuilds the inputs from the outputs, which is what lets ChainComposer.log_prob re-evaluate a chain at given samples. Typical uses relate a network’s coordinates to physical ones, such as rotating the right ascension from the training reference frame to the event frame.

Subclasses implement forward and inverse, and log_det when the map is not measure-preserving.

Variables:
  • parameters (list[str]) – The columns produced. They replace inputs in the chain; a map that overwrites a column in place names it in both.

  • inputs (list[str]) – The columns transformed. They leave the chain after the step (unless also produced), and inverse rebuilds them.

  • conditioning (list[str]) – Further columns the map reads but does not transform, for example a proxy it shifts by. They stay in the chain.

annotations: list[str] = []
conditioning: list[str]
describe() → dict

The default descriptor, plus the transformed inputs. See Factor.describe.

draws = False
abstract forward(given: dict[str, Tensor], context: SamplerContext) → dict[str, Tensor]

Apply the change of variables.

Parameters:
  • given (dict[str, torch.Tensor]) – The inputs and conditioning columns, one row each.

  • context (SamplerContext) – The per-event shared state.

Returns:

The parameters columns.

Return type:

dict[str, torch.Tensor]

inputs: list[str]
abstract inverse(params: dict[str, Tensor], context: SamplerContext, given: dict[str, Tensor] | None = None) → dict[str, Tensor]

Rebuild the inputs from the produced parameters.

Parameters:
  • params (dict[str, torch.Tensor]) – The parameters columns, one row each.

  • context (SamplerContext) – The per-event shared state.

  • given (dict[str, torch.Tensor], optional) – The read-only conditioning columns, still in the chain, for example a proxy the map shifts by. Maps that depend only on their own outputs may ignore it.

Returns:

The inputs columns.

Return type:

dict[str, torch.Tensor]

log_det(given: dict[str, Tensor], context: SamplerContext) → Tensor

The log-Jacobian log|det J| of forward, per row.

The default is zero, for a measure-preserving map.

Parameters:
  • given (dict[str, torch.Tensor]) – The inputs and conditioning columns, one row each.

  • context (SamplerContext) – The per-event shared state.

Returns:

One value per row, on the device of the transformed rows.

Return type:

torch.Tensor

parameters: list[str]
property produces: list[str]

The emitted columns (the transformed parameters).

sample_and_log_prob(num_samples: int, context: SamplerContext, given: dict[str, Tensor] | None = None) → tuple[dict[str, Tensor], Tensor]

Apply forward and contribute -log|det J|.

num_samples must be 1, since a reparametrization is one-to-one. See Factor.sample_and_log_prob for the arguments.

Raises:

ValueError – If num_samples is not 1.

class dingo.core.inference.steps.SampleTableFactor(table: dict, log_prob=None)

Bases: Factor

A chain root that emits a fixed table of existing samples, together with their stored log probability.

Use this to continue a chain from samples drawn earlier. For example, the synthetic phase is added to previously drawn samples by a chain rooted in their table, and the chain’s summed log probability is then the joint proposal density log q(theta) + log q(phase | theta). Without a stored log probability the chain is density-free.

Unlike a DeltaFactor, a sample table is not a distribution: it carries the density of the chain that produced its rows and cannot be evaluated at other points, so its log_prob raises. Like a delta factor it does not draw (draws = False). The table is emitted once, and the chain’s num_samples is drawn per table row by the first step that does draw (one phase per sample, or num_samples posterior draws per grid point in the chirp-mass scan).

Parameters:
  • table (dict) – The existing samples, one array-like column per parameter. Their dtype is kept, so that later steps see exactly the stored values (a caller feeding a network casts to its dtype first).

  • log_prob (array-like, optional) – The stored log probability of each row. If omitted, the chain has no tractable density.

draws = False
log_prob(theta_i, context, given=None)

Raise NotImplementedError: a table is not a density. Evaluate the log probability through the chain that produced the samples instead.

sample_and_log_prob(num_samples, context, given=None)

Emit the table and its stored log probability.

Parameters:
  • num_samples (int) – Must be 1: the table is emitted once.

  • context (SamplerContext) – The per-event shared state. The table is moved to its device.

  • given (dict, optional) – Ignored; a table is unconditioned.

Returns:

  • samples (dict[str, torch.Tensor]) – The table columns.

  • log_prob (torch.Tensor or None) – The stored log probability per row, or None if none was given.

Raises:

ValueError – If num_samples is not 1.

class dingo.core.inference.steps.Standardization(mean: dict[str, float], std: dict[str, float])

Bases: object

Affine map between a network’s standardized parameter space and physical parameter space, z = (theta - mean) / std.

Each network has its own mean and std, so each FlowFactor holds its own instance. The map is used in both directions: network outputs are de-standardized into physical samples, and physical parameters are standardized before a log_prob evaluation.

Parameters:
  • mean (dict[str, float]) – Standardization mean, keyed by parameter name.

  • std (dict[str, float]) – Standardization standard deviation, keyed by parameter name.

destandardize(z: Tensor, names: list[str]) → dict[str, Tensor]

Map standardized values back to physical parameter values.

Parameters:
  • z (torch.Tensor) – Standardized values, with columns in names order.

  • names (list[str]) – The parameter name of each column.

Returns:

Physical values, keyed by parameter name.

Return type:

dict[str, torch.Tensor]

log_det(names: list[str]) → float

The log-Jacobian term that converts a network log probability to physical parameter space, log p(theta) = log p(z) - sum(log std).

The same term is added when sampling and when evaluating log_prob.

Parameters:

names (list[str]) – The parameters included in the network’s output.

Returns:

The value of -sum(log std) over names.

Return type:

float

standardize(values: dict[str, Tensor], names: list[str]) → Tensor

Standardize physical parameter values.

Parameters:
  • values (dict[str, torch.Tensor]) – Physical values, keyed by parameter name.

  • names (list[str]) – The parameters to include, in column order.

Returns:

Standardized values, with one column per entry of names.

Return type:

torch.Tensor

class dingo.core.inference.steps.Step(*args, **kwargs)

Bases: Protocol

Protocol for one entry of a chain: anything a ChainComposer can fold over.

A step names the parameters it samples (parameters) and the earlier columns it reads (conditioning), and implements sample_and_log_prob. A factor returns a log-probability tensor; a density-free block (GibbsBlock) returns None. The data is not part of the interface; steps read it through the context. A Reparametrization additionally names the columns it transforms (inputs), which its outputs replace.

Variables:
  • parameters (list[str]) – The parameters sampled (or transformed): the chain’s output columns.

  • conditioning (list[str]) – The earlier columns read.

  • draws (bool) – Whether the step draws new samples, and so takes one of the chain’s sample counts, or is run once (a point mass, a sample table, a one-to-one transform).

  • produces (list[str]) – All columns emitted: parameters, plus annotations and side channels (intermediates for later steps, dropped from the output).

  • annotations (list[str]) – Emitted columns beyond parameters that are kept in the output for importance sampling, such as a TargetCorrection’s or a cached log likelihood.

annotations: list[str]
conditioning: list[str]
draws: bool
parameters: list[str]
produces: list[str]
sample_and_log_prob(num_samples: int, context: SamplerContext, given: dict[str, Tensor] | None = None) → tuple[dict[str, Tensor], Tensor | None]

Produce the step’s columns and its proposal log-probability contribution (None for a density-free step). See Factor.sample_and_log_prob.

class dingo.core.inference.steps.TargetCorrection

Bases: ABC

Base class for a target correction: a step that annotates the importance-sampling target and contributes nothing to the proposal.

Some targets are not simply prior times likelihood. A target correction reads earlier columns and emits an annotation column (delta_log_prob_target in Dingo’s use), which importance sampling adds to the target log density; the step contributes zero to the proposal. It samples nothing, so its parameters are empty and the annotation is declared in produces. It is one-to-one, with one output row per input row. It has no inverse, and ChainComposer.log_prob skips it.

Variables:
  • produces (list[str]) – The annotation column(s) emitted.

  • conditioning (list[str]) – The columns read.

property annotations: list[str]

The emitted annotation columns, which the chain keeps in its output.

conditioning: list[str]
abstract correction(given: dict[str, Tensor], context: SamplerContext) → dict[str, Tensor]

Compute the correction column(s).

Parameters:
  • given (dict[str, torch.Tensor]) – The conditioning columns, one row each.

  • context (SamplerContext) – The per-event shared state.

Returns:

The emitted column(s), one value per row.

Return type:

dict[str, torch.Tensor]

describe() → dict

The default descriptor, plus the annotation column(s) in produces. See Factor.describe.

draws = False
parameters: list[str] = []
produces: list[str]
sample_and_log_prob(num_samples: int, context: SamplerContext, given: dict[str, Tensor] | None = None) → tuple[dict[str, Tensor], Tensor]

Emit the correction, with zero proposal log probability.

num_samples must be 1, since a target correction is one-to-one. See Factor.sample_and_log_prob for the arguments.

Raises:

ValueError – If num_samples is not 1.

Module contents