zhusuan.mcmc

SGMCMC

class SGMCMC[source]

Bases: torch.nn.modules.module.Module

Base class for stochastic gradient MCMC (SGMCMC) algorithms.

SGMCMC is a class of MCMC algorithms which utilize stochastic gradients instead of the true gradients. To deal with the problems brought by stochasticity in gradients, more sophisticated updating scheme, such as SGHMC and SGNHT, were proposed. We provided four SGMCMC algorithms here: SGLD, SGHMC.

The typical code for SGMCMC inference is like:

sgmcmc = zs.mcmc.SGLD(learning_rate=lr)
net = BayesianNet()
for epoch in range(epoch_size):
    for step in range(num_batches):
        w_samples = model.sample(net, {'x': x, 'y': y})

        for i, (k, w) in enumerate(w_samples.items()):
            # Utilize stochastic gradients by samples and update parameters.
            ...
forward(bn, observed, resample=False, step=1)[source]

Defines the computation performed at every call.

Should be overridden by all subclasses.

Note

Although the recipe for forward pass needs to be defined within this function, one should call the Module instance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.

initialize()[source]
sample(bn, observed, resample=False, step=1)[source]

Running one sgmcmc iteration.

Parameters
  • bn – A instance of BayesianNet.

  • observed – A dictionary of (string, Tensor) pairs. Mapping from names of observed StochasticTensor s to their values.

  • resample – Flag indicates if the sampler need get the var list of the BayesianNet instance, usually set to True on first sgmcmc iteration.

Returns

A list of Var, samples generated by sgmcmc iteration.

training: bool

SGLD

class SGLD(learning_rate)[source]

Bases: zhusuan.mcmc.SGMCMC.SGMCMC

Subclass of SGMCMC which implements Stochastic Gradient Langevin Dynamics (Welling & Teh, 2011) (SGLD) update. The updating equation implemented below follows Equation (3) in the paper.

  • var_list - The updated values of latent variables.

Parameters

learning_rate – A 0-D float32 Var.

property device

The device this module lies at.

Returns

torch.device

to(device)[source]

Moves and/or casts the parameters and buffers.

This can be called as

to(device=None, dtype=None, non_blocking=False)[source]
to(dtype, non_blocking=False)[source]
to(tensor, non_blocking=False)[source]
to(memory_format=torch.channels_last)[source]

Its signature is similar to torch.Tensor.to(), but only accepts floating point or complex dtypes. In addition, this method will only cast the floating point or complex parameters and buffers to dtype (if given). The integral parameters and buffers will be moved device, if that is given, but with dtypes unchanged. When non_blocking is set, it tries to convert/move asynchronously with respect to the host if possible, e.g., moving CPU Tensors with pinned memory to CUDA devices.

See below for examples.

Note

This method modifies the module in-place.

Args:
device (torch.device): the desired device of the parameters

and buffers in this module

dtype (torch.dtype): the desired floating point or complex dtype of

the parameters and buffers in this module

tensor (torch.Tensor): Tensor whose dtype and device are the desired

dtype and device for all parameters and buffers in this module

memory_format (torch.memory_format): the desired memory

format for 4D parameters and buffers in this module (keyword only argument)

Returns:

Module: self

Examples:

>>> # xdoctest: +IGNORE_WANT("non-deterministic")
>>> linear = nn.Linear(2, 2)
>>> linear.weight
Parameter containing:
tensor([[ 0.1913, -0.3420],
        [-0.5113, -0.2325]])
>>> linear.to(torch.double)
Linear(in_features=2, out_features=2, bias=True)
>>> linear.weight
Parameter containing:
tensor([[ 0.1913, -0.3420],
        [-0.5113, -0.2325]], dtype=torch.float64)
>>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA1)
>>> gpu1 = torch.device("cuda:1")
>>> linear.to(gpu1, dtype=torch.half, non_blocking=True)
Linear(in_features=2, out_features=2, bias=True)
>>> linear.weight
Parameter containing:
tensor([[ 0.1914, -0.3420],
        [-0.5112, -0.2324]], dtype=torch.float16, device='cuda:1')
>>> cpu = torch.device("cpu")
>>> linear.to(cpu)
Linear(in_features=2, out_features=2, bias=True)
>>> linear.weight
Parameter containing:
tensor([[ 0.1914, -0.3420],
        [-0.5112, -0.2324]], dtype=torch.float16)

>>> linear = nn.Linear(2, 2, bias=None).to(torch.cdouble)
>>> linear.weight
Parameter containing:
tensor([[ 0.3741+0.j,  0.2382+0.j],
        [ 0.5593+0.j, -0.4443+0.j]], dtype=torch.complex128)
>>> linear(torch.ones(3, 2, dtype=torch.cdouble))
tensor([[0.6122+0.j, 0.1150+0.j],
        [0.6122+0.j, 0.1150+0.j],
        [0.6122+0.j, 0.1150+0.j]], dtype=torch.complex128)
training: bool

PSGLD

class PSGLD(learning_rate, decay=0.9, epsilon=0.001)[source]

Bases: zhusuan.mcmc.SGLD.SGLD

PSGLD with RMSprop preconditioner, “Preconditioned stochastic gradient Langevin dynamics for deep neural networks”

training: bool

SGHMC

class SGHMC(learning_rate, friction=0.25, variance_estimate=0.0, n_iter_resample_v=20, second_order=True)[source]

Bases: zhusuan.mcmc.SGMCMC.SGMCMC

training: bool