|
| 1 | +""" |
| 2 | +Core computations for DADVI. |
| 3 | +""" |
| 4 | + |
| 5 | +from typing import NamedTuple, Callable, Optional, Dict |
| 6 | + |
| 7 | +from scipy.sparse.linalg import LinearOperator |
| 8 | + |
| 9 | +import numpy as np |
| 10 | +from pymc_extras.inference.deterministic_advi.optimization import optimize_with_hvp |
| 11 | + |
| 12 | + |
| 13 | +class DADVIFuns(NamedTuple): |
| 14 | + """ |
| 15 | + This NamedTuple holds the functions required to run DADVI. |
| 16 | +
|
| 17 | + Args: |
| 18 | + kl_est_and_grad_fun: Function of eta [variational parameters] and zs [draws]. |
| 19 | + zs should have shape [M, D], where M is number of fixed draws and D is |
| 20 | + problem dimension. Returns a tuple whose first argument is the estimate |
| 21 | + of the KL divergence, and the second is its gradient w.r.t. eta. |
| 22 | + kl_est_hvp_fun: Function of eta, zs, and b, a vector to compute the hvp |
| 23 | + with. This should return a vector -- the result of the hvp with b. |
| 24 | + """ |
| 25 | + |
| 26 | + kl_est_and_grad_fun: Callable[[np.ndarray, np.ndarray], np.ndarray] |
| 27 | + kl_est_hvp_fun: Optional[Callable[[np.ndarray, np.ndarray, np.ndarray], np.ndarray]] |
| 28 | + |
| 29 | + |
| 30 | +def find_dadvi_optimum( |
| 31 | + init_params: np.ndarray, |
| 32 | + zs: np.ndarray, |
| 33 | + dadvi_funs: DADVIFuns, |
| 34 | + opt_method: str = "trust-ncg", |
| 35 | + callback_fun: Optional[Callable] = None, |
| 36 | + verbose: bool = False, |
| 37 | +) -> Dict: |
| 38 | + """ |
| 39 | + Optimises the DADVI objective. |
| 40 | +
|
| 41 | + Args: |
| 42 | + init_params: The initial variational parameters to use. This should be a |
| 43 | + vector of length 2D, where D is the problem dimension. The first D |
| 44 | + entries specify the variational means, while the last D specify the log |
| 45 | + standard deviations. |
| 46 | + zs: The fixed draws to use in the optimisation. They must be of shape |
| 47 | + [M, D], where D is the problem dimension and M is the number of fixed |
| 48 | + draws. |
| 49 | + dadvi_funs: The objective to optimise. See the definition of DADVIFuns for |
| 50 | + more information. The kl_est_and_grad_fun is required for optimisation; |
| 51 | + the kl_est_hvp_fun is needed only for some optimisers. |
| 52 | + opt_method: The optimisation method to use. This must be one of the methods |
| 53 | + listed for scipy.optimize.minimize |
| 54 | + [https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.minimize.html]. |
| 55 | + Defaults to trust-ncg, which requires the hvp to be available. For |
| 56 | + gradient-only optimisation, L-BFGS-B generally works well. |
| 57 | + callback_fun: If provided, this callback function is passed to |
| 58 | + scipy.optimize.minimize. See that function's documentation for more. |
| 59 | + verbose: If True, prints the progress of the optimisation by showing the |
| 60 | + value and gradient norm at each iteration of the optimizer. |
| 61 | +
|
| 62 | + Returns: |
| 63 | + A dictionary with entries "opt_result", containing the results of running |
| 64 | + scipy.optimize.minimize, and "evaluation_count", containing the number of |
| 65 | + times the hvp and gradient functions were called. |
| 66 | + """ |
| 67 | + |
| 68 | + val_and_grad_fun = lambda var_params: dadvi_funs.kl_est_and_grad_fun(var_params, zs) |
| 69 | + hvp_fun = ( |
| 70 | + None |
| 71 | + if dadvi_funs.kl_est_hvp_fun is None |
| 72 | + else lambda var_params, b: dadvi_funs.kl_est_hvp_fun(var_params, zs, b) |
| 73 | + ) |
| 74 | + |
| 75 | + opt_result, eval_count = optimize_with_hvp( |
| 76 | + val_and_grad_fun, |
| 77 | + hvp_fun, |
| 78 | + init_params, |
| 79 | + opt_method=opt_method, |
| 80 | + callback_fun=callback_fun, |
| 81 | + verbose=verbose, |
| 82 | + ) |
| 83 | + |
| 84 | + to_return = { |
| 85 | + "opt_result": opt_result, |
| 86 | + "evaluation_count": eval_count, |
| 87 | + } |
| 88 | + |
| 89 | + # TODO: Here I originally had a Newton step check to assess |
| 90 | + # convergence. Could add this back in. |
| 91 | + |
| 92 | + return to_return |
| 93 | + |
| 94 | + |
| 95 | +def get_dadvi_draws(var_params: np.ndarray, zs: np.ndarray) -> np.ndarray: |
| 96 | + """ |
| 97 | + Computes draws from the mean-field variational approximation given |
| 98 | + variational parameters and a matrix of fixed draws. |
| 99 | +
|
| 100 | + Args: |
| 101 | + var_params: A vector of shape 2D, the first D entries specifying the |
| 102 | + means for the D model parameters, and the last D the log standard |
| 103 | + deviations. |
| 104 | + zs: A matrix of shape [N, D], containing the draws to use to sample the |
| 105 | + variational approximation. |
| 106 | +
|
| 107 | + Returns: |
| 108 | + A matrix of shape [N, D] containing N draws from the variational |
| 109 | + approximation. |
| 110 | + """ |
| 111 | + |
| 112 | + # TODO: Could use JAX here |
| 113 | + means, log_sds = np.split(var_params, 2) |
| 114 | + sds = np.exp(log_sds) |
| 115 | + |
| 116 | + draws = means.reshape(1, -1) + zs * sds.reshape(1, -1) |
| 117 | + |
| 118 | + return draws |
| 119 | + |
| 120 | + |
| 121 | +# TODO -- I think the functions above cover the basic functionality of |
| 122 | +# fixed-draw ADVI. But I have not yet included the LRVB portion of the |
| 123 | +# code, in the interest of keeping it simple. Can add later. |
0 commit comments