Encodings¶
Encodings \(E\) are the instance-specific part of PAVI's variational parameters: small vectors that encode the statistics of each instance's posterior (see plate amortization). They are created by an encoding manager, passed to the guide as encoding_manager=....
As a reminder, a site is a random variable of the Pyro model, declared with pyro.sample("name", ...). A site inside one or several plates has one instance per plate element (or per combination of elements). Each instance gets its own encoding, which conditions the transforms of the site.
Two managers¶
The managers differ in how they build the encoding of an instance in several plates. Consider a site theta in two plates, subjects (size S) and vertices (size N):
JointEM |
FactorizedEM |
|
|---|---|---|
| Encoding of instance (s, n) | its own vector \(E^{s,n}\) | built from one encoding per plate: \([E^s, E^n]\) (concatenation) or \(E^s + E^n\) (sum) |
| Number of encodings stored | S × N | S + N |
Choosing a manager¶
JointEMgives every instance its own encoding. It is the most flexible choice and the natural one for sites in a single plate, where both managers are equivalent. For sites in several plates, the number of encodings is the product of the plate sizes (e.g. subjects × vertices), which can be prohibitive.FactorizedEMbuilds the encoding of a multi-plate instance from per-plate encodings, so the number of encodings is the sum of the plate sizes. This is the manager used for the brain model (subjects × 60k vertices). Its subject encodings are the per-subject representation that is refitted for new subjects. Per-plate encodings are concatenated (agg_type="concat", default) or summed (agg_type="sum", which requires the same size for all the plates of a site).
Sharing between sites. By default (share_across_sites=True), sites in the same plates reuse the same encodings: with FactorizedEM, a site mu in the subjects plate and the site theta above both use encodings.subjects. With share_across_sites=False, each site gets its own tables, named after the site: encodings.mu.subjects, encodings.theta.subjects, encodings.theta.vertices.
Large tables. Two options save GPU memory: sparse gradients (sparse=True) only update the encodings of the current mini-batch, and the tables can be kept in CPU memory (device_params="cpu") while the rest of the guide runs on the GPU.
encoding_size¶
The encoding size is the dimension \(m\) of each encoding: an int (the same for every table), or a dict.
JointEM: a dict keyed by plate combinations, with plate names joined by|in any order:{"subjects": 8, "subjects|vertices": 4}.FactorizedEM: a dict keyed by single plate names:{"subjects": 120, "vertices": 8}. The context size of a site is the sum of its plates' sizes (concat) or their common size (sum).
A size of 0 disables the corresponding encodings. A missing entry raises a KeyError naming the site and the plates.
Parameter names¶
Encodings are torch.nn.Embedding tables in guide.encodings, with one row per instance. Their parameter names are stable, so they can be matched by per-variable learning rates (InferenceModule(lr_per_rv={"encodings": ...})) or selected for freezing:
- shared tables (default):
encodings.<plates>.weight, e.g.encodings.subjects.weightorencodings.subjects|vertices.weight; - per-site tables (
share_across_sites=False):encodings.<site>.<plates>.weight, e.g.encodings.theta.subjects|vertices.weight.
<plates> lists the plates of the table, joined by | from the outermost to the innermost plate.
Example: two plates, two sites¶
import pyro
import pyro.distributions as dist
import torch
from pavi.core import FactorizedEM, JointEM, NormalizingFlowScheme, PAVIGuide
from pavi.distributions import conditional_affine
S, N, D = 4, 6, 3 # subjects, vertices, event size
def model(data=None, idx=None):
idx = idx or {}
with pyro.plate("subjects", S, subsample=idx.get("subjects"), dim=-2):
mu = pyro.sample("mu", dist.Normal(torch.zeros(D), 1.0).to_event(1))
with pyro.plate("vertices", N, subsample=idx.get("vertices"), dim=-1):
theta = pyro.sample("theta", dist.Normal(mu, 1.0).to_event(1))
pyro.sample("X", dist.Normal(theta, 0.1).to_event(1), obs=data)
X = torch.randn(S, N, D)
transforms = {"mu": [conditional_affine([16])], "theta": [conditional_affine([16])]}
for manager in [
JointEM(encoding_size={"subjects": 2, "subjects|vertices": 4}),
FactorizedEM(encoding_size={"subjects": 2, "vertices": 3}),
FactorizedEM(encoding_size=3, agg_type="sum", share_across_sites=False),
]:
pyro.clear_param_store()
guide = PAVIGuide(model, transforms, NormalizingFlowScheme, manager, hidden_sites=["X"], device="cpu", data=X)
sizes = {name: tuple(p.shape) for name, p in guide.named_parameters() if name.startswith("encodings")}
print(type(manager).__name__, sizes)
# JointEM {'encodings.subjects.weight': (4, 2), 'encodings.subjects|vertices.weight': (24, 4)}
# FactorizedEM {'encodings.subjects.weight': (4, 2), 'encodings.vertices.weight': (6, 3)}
# FactorizedEM {'encodings.mu.subjects.weight': (4, 3), 'encodings.theta.subjects.weight': (4, 3), 'encodings.theta.vertices.weight': (6, 3)}
- With
JointEM,thetagets one of 24 joint encodings of size 4. - With
FactorizedEM, it gets a subject encoding (2) concatenated with a vertex encoding (3), andmureuses the same subject encodings. - In the last case,
thetagets the sum of its own subject and vertex encodings (3), andmuhas its own subject encodings.
Options¶
| Argument | Managers | Meaning |
|---|---|---|
share_across_sites |
both | reuse the same tables for sites in the same plates (default True) or give each site its own |
agg_type |
FactorizedEM |
"concat" (default) or "sum" |
expose |
both | restrict the manager to these sites (default None: all); the other sites get no encodings |
sparse |
both | sparse gradients: only the encodings of the current mini-batch are updated, which saves GPU memory. Optimize with SparseAdam (InferenceModule does it automatically) |
device_params |
both | device of the tables, e.g. "cpu" to keep large tables in CPU memory while the guide runs on the GPU (default: the guide's device) |
init_scale |
both | standard deviation of the Normal initialization of the encodings (default 0.1) |
Note
JointEM and FactorizedEM replace the former EmbeddingPlainEM, CrossEM and PlateCrossEM (the latter is FactorizedEM(share_across_sites=False)). Checkpoints saved with the former managers may use other parameter names (e.g. encodings.subjects_vertices.weight, encodings.plate_sub_unconstrained) and then cannot be loaded.
Refitting encodings for new data¶
To infer new instances while reusing what was learned, freeze everything except the encodings (see inference on new subjects). On the getting-started model:
NUM_GROUPS, NUM_OBS, DIM = 5, 50, 2
def hgm(data=None, idx=None):
idx = idx or {}
z_2 = pyro.sample("z_2", dist.Normal(torch.zeros(DIM), 1.0).to_event(1))
with pyro.plate("P_1", NUM_GROUPS, subsample=idx.get("P_1"), dim=-1):
z_1 = pyro.sample("z_1", dist.Normal(z_2, 5.0).to_event(1))
with pyro.plate("P_0", NUM_OBS, subsample=idx.get("P_0"), dim=-2):
pyro.sample("X", dist.Normal(z_1, 1.0).to_event(1), obs=data)
pyro.clear_param_store()
X_hgm = pyro.poutine.trace(hgm).get_trace().nodes["X"]["value"]
guide = PAVIGuide(
hgm,
{"z_1": [conditional_affine(hidden_layers=[32, 32])]},
NormalizingFlowScheme,
JointEM(encoding_size={"P_1": 8}),
hidden_sites=["X"],
device="cpu",
data=X_hgm,
)
# ... train the guide on a first dataset, then, for new data X_new:
for name, param in guide.named_parameters():
param.requires_grad = name.startswith("encodings.")
encodings = [p for p in guide.parameters() if p.requires_grad]
print([name for name, p in guide.named_parameters() if p.requires_grad]) # ['encodings.P_1.weight']
optimizer = torch.optim.Adam(encodings, lr=1e-2)
In the brain application this is done by experiments/scripts/inferring.py, which unfreezes only the subject encodings (guide.encodings.plate_sub.weight) and rebuilds the guide for the new subjects.
Writing your own manager¶
Subclass pavi.core.encoding_manager.EncodingManager. To reuse its embedding tables, lookup and options, implement:
_site_tables(plates): the plates of each table used by a site inplates(e.g.[plates]forJointEM, one plate per table forFactorizedEM);_table_size(plates, name_site): the encoding size of a table;_combine(encodings)and_context_size(sizes, name_site): how the encodings of a site's tables are combined into its context, and the resulting size.
For a different storage, override the public methods instead:
init_encodings(guide): create the parameters and attach them toguide.encodings. The guide'ssample_plate,plate_size,plate_dim,all_platesanddeviceare available.get_encodings(guide, name_sample, idx=None, device=None): return a tensor broadcastable to the site's batch shape, with the context in the last dimension, for the plate elements inidx(all of them whenidxisNone).get_sample_encodings_size(guide, name_sample): the context size of a site, used ascontext_dimfor its transforms.