Bayesian Lifts¶
These functions convert non-Bayesian models to MonadicProgram
instances for inference. They cover four model interfaces:
bayesian_lift_parametersassigns Normal priors to learnable parameters. It can also lift intermediatesamplesites as NUTS latents through placeholder cancellation.lift_to_bayesian_programcombines a parameter-only morphism with a chosen observation family, which may be anytorch.distributions.Distributionsubclass. Itslocation_fncallback handlesrsampleoutputs,tensorattributes, andprogram(x)outputs.lift_from_log_probaccepts a parameter-only model whose forward method already computeslog_prob(x, y), such as the induced density of composed Normal kernels.monte_carlo_log_jointestimates a conditional likelihood from one draw at an intermediate latent site. It is a stochastic-gradient estimator for SVI, not a replacement for the joint lift used with NUTS.
lifts
¶
Lift non-Bayesian morphisms into Bayesian MonadicPrograms.
The inference layer (SVI, NUTS, LatentRegistry) operates on
MonadicPrograms with explicit sample priors and observe
likelihood steps. Two patterns require a lift before that contract
applies:
-
A composed deterministic morphism (e.g. a chain of
[role=kernel]morphisms whose composition has no~ Familyprior) carries learnablenn.Parameters but no priors and no observation family.lift_to_bayesian_programproduces a properMonadicProgramby attaching a Normal prior to every parameter and an observation family of the user's choice on the morphism's output. -
A
MonadicProgramdeclares intermediate latents viasamplesteps that have no externally observed value (an LM's hidden stateh, a state-space model's per-step latent vector). The inference layer expects the caller to supply every latent in the observations dict.monte_carlo_log_jointforward-samples the named latents from their declared family and merges the draws into the observations dict before calling the inner'slog_joint.
Both functions return artefacts the inference layer consumes directly; no adapter classes, no per-family helpers.
bayesian_lift_parameters
¶
bayesian_lift_parameters(inner_model: Module, x: Tensor, observations: dict[str, Tensor], *, prior_scale: float = 1.0, site_prefix: str = 'theta', additional_latents: dict[str, tuple[int, ...]] | None = None, latent_placeholder_scale: float = 10.0) -> tuple[MonadicProgram, Tensor, dict[str, Tensor]]
Lift model parameters and selected latents into sample sites.
Each learnable parameter receives an independent
:math:\mathcal{N}(0, \sigma_\theta^2) prior. Entries in
additional_latents receive placeholder Normal priors. The score term
subtracts those placeholder log densities from inner_model.log_joint,
so they cancel pointwise; latent_placeholder_scale affects
initialization and adaptation, not the represented density.
Learnable parameters must use unconstrained real coordinates. Use explicit priors when an independent zero-centered Normal does not represent the intended parameter prior.
| PARAMETER | DESCRIPTION |
|---|---|
inner_model
|
Module exposing
TYPE:
|
x
|
Input passed to
TYPE:
|
observations
|
Observations passed to
TYPE:
|
prior_scale
|
Standard deviation of each parameter prior.
TYPE:
|
site_prefix
|
Prefix for parameter sample-site names.
TYPE:
|
additional_latents
|
Latent names and tensor shapes, excluding any batch dimension.
TYPE:
|
latent_placeholder_scale
|
Standard deviation of each placeholder latent prior.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple[MonadicProgram, Tensor, dict[str, Tensor]]
|
Lifted program, placeholder input, and empty observation mapping. |
Source code in src/quivers/inference/lifts.py
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 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 | |
lift_to_bayesian_program
¶
lift_to_bayesian_program(parameter_module: Module, *, location_fn: Callable[[Tensor], Tensor], parameter_prior_scale: float = 1.0, observation_family: type[Distribution], observation_kwargs: Mapping[str, DistributionArg] | None = None, target_key: str = 'Y', x: Tensor | None = None, observations: dict[str, Tensor] | None = None) -> tuple[MonadicProgram, Tensor, dict[str, Tensor]]
Lift a deterministic parameter-only model into a Bayesian
MonadicProgram under a chosen observation family.
The returned program has:
- one Normal prior sample site per learnable
torch.nn.Parameterofparameter_module(the parameter lift, with standard deviationparameter_prior_scale); - one score step that
(i) substitutes the sampled values into
parameter_module's parameter slots, (ii) callslocation_fn(x)to obtain the family's location tensor (e.g.lambda x: morphism.rsample(x)for input-driven morphisms,lambda _: morphism.tensorfor parameter-only morphisms whose output is exposed via thetensorattribute, orlambda x: prog(x)for a program's forward call), (iii) buildsobservation_family(location, **observation_kwargs), and (iv) returns its log-probability atobservations[target_key], reduced over event axes.
Any torch.distributions.Distribution subclass works as
observation_family. The first positional parameter of the
family (loc for Normal, probs / logits for
Categorical, etc.) receives location_fn's output; the
remaining parameters come from observation_kwargs.
| PARAMETER | DESCRIPTION |
|---|---|
parameter_module
|
The module whose learnable parameters get Normal priors.
For an input-driven morphism this is typically the
morphism itself. For a program whose morphism is a
parameter-only
TYPE:
|
location_fn
|
TYPE:
|
parameter_prior_scale
|
Standard deviation of the Normal prior on every parameter.
TYPE:
|
observation_family
|
TYPE:
|
observation_kwargs
|
Keyword arguments forwarded to
TYPE:
|
target_key
|
Key in the observations dict whose value is the observed data.
TYPE:
|
x
|
The forward input and the surrounding observations dict.
TYPE:
|
observations
|
The forward input and the surrounding observations dict.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
(model, x_, observations_)
|
The lifted program plus the input + empty observation dict
the inference layer feeds it. The original
|
Source code in src/quivers/inference/lifts.py
327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 | |
lift_from_log_prob
¶
lift_from_log_prob(parameter_module: Module, *, log_prob_fn: Callable[[Tensor, Tensor], Tensor], parameter_prior_scale: float = 1.0, target_key: str = 'Y', x: Tensor | None = None, observations: dict[str, Tensor] | None = None) -> tuple[MonadicProgram, Tensor, dict[str, Tensor]]
Lift a parameter-only model whose forward is a
log_prob(x, y)-style function into a Bayesian
MonadicProgram over its parameters.
Use this when the wrapped morphism already exposes a method
that returns :math:\log p(y \mid x) directly (e.g. a
SampledComposition over a Normal kernel, a VAE's
encoder-decoder composition). The lifted program puts Normal
priors on every learnable parameter and uses the supplied
log_prob_fn to score the observation.
| PARAMETER | DESCRIPTION |
|---|---|
parameter_module
|
Module whose learnable parameters get Normal priors.
TYPE:
|
log_prob_fn
|
TYPE:
|
parameter_prior_scale
|
Standard deviation of the Normal prior on every parameter.
TYPE:
|
target_key
|
Observation-dict key for the observed data
TYPE:
|
x
|
Forward input and observations dict; defaults are
TYPE:
|
observations
|
Forward input and observations dict; defaults are
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
(model, x_, observations_)
|
The lifted program plus the input + empty observation dict the inference layer feeds it. |
Source code in src/quivers/inference/lifts.py
464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 | |
monte_carlo_log_joint
¶
monte_carlo_log_joint(inner_model: Module, *, sample_sites: list[str], keep_inner_observations: bool = True) -> Module
Wrap a program so its log_joint MC-draws the named
intermediate sample sites and returns the conditional data
likelihood at the draw.
Mathematics
Given an inner program with parameters :math:\theta, named
intermediate latents :math:\mathbf{z} (in sample_sites),
and observed data :math:y, the wrapper returns
.. math:: \log p_{\mathrm{inner}}(y \mid \mathbf{z}, \theta), \qquad \mathbf{z}_ \sim p \mid x, \theta).}}(\mathbf{z
This is a single-sample Monte-Carlo estimator of
:math:\log p_{\mathrm{inner}}(y \mid x, \theta). By Jensen,
its expectation lower-bounds the true marginal likelihood:
.. math:: \mathbb{E}_{\mathbf{z}}\bigl[\log p(y \mid \mathbf{z}, \theta)\bigr] \;\le\; \log p(y \mid x, \theta).
Implementation: for each name in sample_sites the wrapper
resolves the site's morphism (through the inner's
_step_specs or, as a fallback, inner._modules under the
conventional _step_<site> / <site> keys), draws
:math:\mathbf{z}_* = \mathrm{morphism.rsample}(x), merges
the draws into the observation dict, calls
inner_model.log_joint(x, merged_obs), and subtracts
:math:\log p(\mathbf{z}_* \mid x, \theta) so the residual
is the conditional likelihood above (not the joint, which
would double-count the latent's prior).
Intended use
- SVI / SGD: this is a valid stochastic gradient estimator
of the parameters' marginal-likelihood gradient. The mean of
:math:
\nabla_\theta \log p(y \mid \mathbf{z}_*, \theta)over draws of :math:\mathbf{z}_*equals the corresponding ELBO-style descent direction, and SVI converges to a stationary point of that bound. - NUTS / HMC: do not use this wrapper for NUTS over a
model whose log-density depends on :math:
\mathbf{z}. Re-drawing :math:\mathbf{z}_*on every leapfrog evaluation makes the energy stochastic, which breaks the Hamiltonian symplectic invariant and biases the chain. The rigorous route is to lift :math:\mathbf{z}as an additional NUTS latent viabayesian_lift_parameterswithadditional_latents={'<name>': <shape>}and let NUTS sample :math:(\theta, \mathbf{z})from the exact joint posterior. The lifted log-density is then deterministic given the full state.
Gradient flow back to the inner's parameters is preserved
when the underlying morphisms are reparameterised
(Normal, MultivariateNormal, etc.).
| PARAMETER | DESCRIPTION |
|---|---|
inner_model
|
Typically a
TYPE:
|
sample_sites
|
Names of
TYPE:
|
keep_inner_observations
|
When True, the wrapper merges its caller's observations dict with the MC draws; when False, only the MC draws are forwarded.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Module
|
Exposes |
Source code in src/quivers/inference/lifts.py
550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 | |