# psqn: Partially Separable Quasi-Newton

$\renewcommand\vec{\boldsymbol} \def\bigO#1{\mathcal{O}(#1)} \def\Cond#1#2{\left(#1\,\middle|\, #2\right)} \def\mat#1{\boldsymbol{#1}} \def\der{{\mathop{}\!\mathrm{d}}} \def\argmax{\text{arg}\,\text{max}} \def\Prob{\text{P}} \def\diag{\text{diag}} \def\argmin{\text{arg}\,\text{min}} \def\Expe{\text{E}}$

This package provides an optimization method for partially separable functions. Partially separable functions are of the following form:

$f(\vec x) = \sum_{i = 1}^n f_i(\vec x_{\mathcal I_i})$

where $$\vec x\in \mathbb R^l$$,

$\vec x_{\mathcal I_i} = (\vec e_{j_{i1}}^\top, \dots ,\vec e_{j_{im_i}}^\top)\vec x, \qquad \mathcal I_i = (j_{i1}, \dots, \mathcal j_{im_i}) \subseteq \{1, \dots, l\},$ and $$\vec e_k$$ is the $$k$$’th column of the $$l$$ dimensional identity matrix. Each function $$f_i$$ is called an element function and only depends on $$m_i \ll l$$ parameters. This allows for an efficient quasi-Newton method when all the $$m_i$$’s are much smaller than the dimension of the parameter vector $$\vec x$$, $$l$$. The framework can be extended to allow for a linear combination of parameters but we do not cover such problems. This vignette closely follows Nocedal and Wright (2006) who cover the methods and alternatives in much greater detail.

We first focus on a more restricted form of the problem. See the section called Generic Example for the more general interface provided by this package. Assume that each index set $$\mathcal I_i$$ is of the form:

\begin{align*} \mathcal I_i &= \{1,\dots, p\} \cup \mathcal J_i \\ \mathcal J_i \cap \mathcal J_j &= \emptyset \qquad j\neq i \\ \mathcal J_i \cap \{1,\dots, p\} &= \emptyset \qquad \forall i = 1,\dots, n \end{align*}.

That is, each index set contains $$p$$ global parameters and $$q_i = \lvert\mathcal J_i\rvert$$ private parameters which are particular for each element function, $$f_i$$. For implementation reason, we let:

\begin{align*} \overleftarrow q_i &= \begin{cases} p & i = 0 \\ p + \sum_{k = 1}^i q_k & i > 0 \end{cases} \\ \mathcal J_i &= \{1 + \overleftarrow q_{i - 1}, \dots , q_i + \overleftarrow q_{i - 1}\} \end{align*}

such that the element functions’ private parameters lies in consecutive parts of $$\vec x$$.

## Example

We are going to consider a Taylor approximation for a generalized linear mixed model. In particular, we focus on a mixed logit regression where:

\begin{align*} \vec U_i &\sim N^{(r)}(\vec 0, \mat\Sigma) \\ \vec\eta_i &= \mat X_i\vec\beta + \mat Z_i\vec U_i \\ Y_{ij} &\sim \text{Bin}(\text{logit}^{-1}(\eta_{ij}), 1), \qquad j = 1, \dots, t_i \end{align*}

where $$N^{(r)}(\vec\mu,\mat\Sigma)$$ means a $$r$$-dimensional a multivariate normal distribution with mean $$\vec\mu$$ and covariance matrix $$\mat\Sigma$$ and $$\text{Bin}(p, k)$$ means a binomial distribution probability $$p$$ and size $$k$$. $$\vec U_i$$ is an unknown random effect with an unknown covariance $$\mat\Sigma$$ and $$\vec\beta\in\mathbb{R}^p$$ are unknown fixed effect coefficients. $$\mat X_i$$ and $$\mat Z_i$$ are known design matrices each with $$t_i$$ rows for each of the $$t_i$$ observed outcomes, the $$y_{ij}$$s.

As part of a Taylor approximation, we find a mode of $$\vec x = (\vec\beta^\top, \widehat{\vec u}_1^\top, \dots, \widehat{\vec u}_n^\top)$$ of the log of the integrand given a covariance matrix estimate, $$\widehat{\mat \Sigma}$$. That is, we are minimizing:

\begin{align*} f(\vec x) &= -\sum_{i = 1}^n \left( \sum_{k = 1}^{t_i}(y_{ij}\eta_{ij} - \log(1 + \exp\eta_{ij})) - \frac 12 \widehat{\vec u}_i^\top\widehat{\mat \Sigma}^{-1} \widehat{\vec u}_i \right) \\ &= -\sum_{i = 1}^n \left( \vec y_i(\mat X_i\vec\beta + \mat Z_i\widehat{\vec u}_i) - \sum_{k = 1}^{t_i} \log(1 + \exp(\vec x_{ik}^\top\vec\beta + \vec z_{ik}^\top\widehat{\vec u}_i)) - \frac 12 \widehat{\vec u}_i^\top\widehat{\mat \Sigma}^{-1} \widehat{\vec u}_i \right) \\ &= \sum_{i = 1}^nf_i((\vec\beta^\top, \widehat{\vec u}_i^\top)^\top) \\ f_i((\vec\beta^\top, \vec u^\top)^\top) &= -\vec y_i(\mat X_i\vec\beta + \mat Z_i\vec u) + \sum_{k = 1}^{t_i} \log(1 + \exp(\vec x_{ik}^\top\vec\beta + \vec z_{ik}^\top\vec u)) + \frac 12 \vec u^\top\widehat{\mat \Sigma}^{-1} \vec u \end{align*}

In this problem, $$\vec\beta$$ are the global parameters and the $$\widehat{\vec u}_i$$’s are the private parameters. Thus, $$l = p + nr$$. We will later return to this example with an implementation which uses this package.

### Variational Approximations

The objective function for variational approximations for mixed models for clustered data is commonly also partially separable. We will briefly summarize the idea here. Ormerod and Wand (2012) and Ormerod (2011) are examples where one might benefit from using the methods in this package.

We let $$\tilde f_i$$ be the log marginal likelihood term from cluster $$i$$. This is of the form:

$\tilde f_i(\vec\omega) = \log \int p_i(\vec y_i, \vec u;\vec\omega)\der \vec u$

where $$\vec\omega$$ are unknown model parameters, $$p_i(\vec u;\vec\omega)$$ is the joint density of the observed data denoted by $$\vec y_i$$, and $$\vec U_i$$ which is a cluster specific random effect. $$\exp \tilde f_i(\vec\omega)$$ is often intractable. An approximation of $$\tilde f_i$$ is to select some variational distribution denoted by $$v_i$$ parameterized by some set $$\Theta_i$$. We then use the approximation:

\begin{align*} \tilde f_i(\vec\omega) &= \int v_i(\vec u; \vec\theta_i) \log\left( \frac{p_i(\vec y_i \vec u;\vec\omega)/v_i(\vec u; \vec\theta_i)} {p_i(\vec u_i \mid \vec y_i;\vec\omega)/v_i(\vec u; \vec\theta_i)} \right)\der\vec u \\ &= \int v_i(\vec u; \vec\theta_i) \log\left( \frac{p_i(\vec y_i, \vec u;\vec\omega)} {v_i(\vec u; \vec\theta_i)} \right)\der\vec u + \int v_i(\vec u; \vec\theta_i) \log\left( \frac{v_i(\vec u; \vec\theta_i)} {p_i(\vec u \mid \vec y_i;\vec\omega)} \right)\der\vec u \\ &\geq \int v_i(\vec u; \vec\theta_i) \log\left( \frac{p_i(\vec y_i, \vec u;\vec\omega)} {v_i(\vec u; \vec\theta_i)} \right)\der\vec u = f_i(\vec\omega,\vec\theta_i) \end{align*}

where $$\vec\theta_i\in\Theta_i$$ and $$p_i(\vec u_i \mid \vec y_i;\vec\omega)$$ is the conditional density of the random effect given the observed data, $$\vec y_i$$, and model parameters, $$\vec\omega$$. $$f_i(\vec\omega,\vec\theta_i)$$ is a lower bound since the Kullback–Leibler divergence

$\int v_i(\vec u; \vec\theta_i)\log\left( \frac{v_i(\vec u; \vec\theta_i)} {p_i(\vec u \mid \vec y_i;\vec\omega)} \right)\der\vec u$

is positive. The idea is to replace the minimization problem:

$\argmin_{\vec\omega} -\sum_{i = 1}^n \tilde f_i(\vec\omega)$

with a variational approximation:

$\argmin_{\vec\omega,\vec\theta_1,\dots,\vec\theta_n} -\sum_{i = 1}^n f_i(\vec\omega,\vec\theta_i)$

This problem fits into the framework in the package where $$\vec\omega$$ are the global parameters and the $$\vec\theta_i$$s are the private parameters.

Variational approximation have the property that if $$v_i(\vec u; \vec\theta_i) = p_i(\vec u \mid \vec y_i;\vec\omega)$$ then the Kullback–Leibler divergence is zero and the lower bound is equal to the log marginal likelihood. Thus, we need to use a family of variational distributions, $$v_i$$, which yields a close approximation of the conditional density of the random effects, $$p_i(\vec u \mid \vec y_i;\vec\omega)$$, for some $$\vec\theta_i\in\Theta_i$$. Moreover, the lower bound also needs to be easy to optimize. Variational approximations have an advantage that given estimates of $$\widehat{\vec\omega},\widehat{\vec\theta}_1,\dots,\widehat{\vec\theta}_n$$ then subsequent inference can be approximated using:

$\Expe\left(h(\vec U_i)\right) = \int h(\vec u) p_i(\vec u \mid \vec y_i;\vec\omega)\der\vec u \approx \int h(\vec u) v_i(\vec u; \widehat{\vec\theta}_i)\der\vec u.$

The latter integral may be much easier to work with for some functions $$h$$ and variational distribution, $$v_i$$.

## Quasi-Newton Method for Partially Separable Functions

We are going to assume some prior knowledge of Newton’s method and the Broyden–Fletcher–Goldfarb–Shanno (BFGS) algorithm and we only provide a few details of these methods. However, will need a bit of notations from these methods to motivate the quasi-Newton method we have implemented.

Newton’s method to minimize a function is to start at some value $$\vec x_0$$. Then we set $$k = 1$$ and

1. compute a direction $$\vec p_k$$ given by $\nabla^2 f(\vec x_{k - 1})\vec p_k = - \nabla f(\vec x_{k -1}),$
2. set $$\vec x_k = \vec x_{k - 1} + \vec p_k$$ or $$\vec x_k = \vec x_{k - 1} + \gamma\vec p_k$$ for $$\gamma \in (0, 1]$$ set to satisfy the Wolfe conditions, and
3. repeat with $$k\leftarrow k + 1$$ if a convergence criterion is not satisfied.

Computing the Hessian, $$\nabla^2 f(\vec x_{k - 1})$$, at every iteration can be expensive. The BFGS algorithm offers an alternative where we use an approximation instead. Here we start with some Hessian approximation $$\mat B_0$$ and

1. compute a direction $$\vec p_k$$ given by $\mat B_{k - 1}\vec p_k = - \nabla f(\vec x_{k -1}),$
2. find a step size $$\alpha$$ such that $$\vec x_{k - 1} + \alpha\vec p_k$$ satisfy the Wolfe conditions,
3. set $$\vec x_k = \vec x_{k - 1} + \alpha\vec p_k$$, $$\vec s_k = \alpha\vec p_k = \vec x_k - \vec x_{k - 1}$$, $$\vec d_k = \nabla f(\vec x_k) - \nabla f(\vec x_{k - 1})$$,
4. perform a rank-two update $\mat B_k = \mat B_{k - 1} + \frac{\vec y_k\vec y_k^\top}{\vec y_k^\top\vec s_k} - \frac{\mat B_{k - 1}\vec s_k\vec s_k^\top\mat B_{k - 1}^\top}{\vec s_k^\top\mat B_{k - 1}\vec s_k},$ and
5. repeat with $$k\leftarrow k + 1$$ if a convergence criterion is not satisfied.

This reduces the cost of computing the Hessian. Further, we can update $$\mat B_k^{-1}$$ to avoid solving $$\mat B_{k - 1}\vec p_k = - \nabla f(\vec x_{k -1})$$. The matrix $$\mat B_k^{-1}$$ will still be large and dense when $$l$$ is large.

### Using Partial Separability

As an alternative, we can exploit the structure of the problem we are solving. Let

$\mat H_i = (\vec e_{j_{i1}}^\top, \dots ,\vec e_{j_{im_i}}^\top).$

The true Hessian in our case is sparse and given by

$\nabla^2 f(\vec x) = \sum_{i = 1}^n \mat H_i^\top\nabla^2f_i(\vec x_{\mathcal I_i})\mat H_i$

Notice that each $$\nabla^2f_i(\vec x_{\mathcal I_i})$$ is only a $$(p + q_i)\times (p + q_i)$$ matrix. We illustrate this below with $$n = 10$$ element functions. Each plot is $$\mat H_i^\top\nabla^2f_i(\vec x_{\mathcal I_i})\mat H_i$$ where black entries are a non-zero.

The whole Hessian is:

We can use the partial separability to implement a BFGS method where we make $$n$$ BFGS approximations, one for each element function, $$f_i$$. Let $$\mat B_{ki}$$ be the approximation of $$\nabla^2f_i(\vec x_{\mathcal I_i})$$ at iteration $$k$$. Then the method we have implemented starts with $$\mat B_{k1},\dots,\mat B_{kn}$$ and

1. computes a direction $$\vec p_k$$ given by $\left(\sum_{i = 1}^n\mat H_i^\top\mat B_{k - 1,i}\mat H_i\right)\vec p_k = - \nabla f(\vec x_{k -1}),$
2. finds a step size $$\alpha$$ such that $$\vec x_{k - 1} + \alpha\vec p_k$$ satisfy the Wolfe conditions,
3. sets $$\vec x_k = \vec x_{k - 1} + \alpha\vec p_k$$,
4. performs BFGS updates for each $$\mat B_{k1},\dots,\mat B_{kn}$$, and
5. repeats with $$k\leftarrow k + 1$$ if a convergence criterion is not satisfied.

This seems as if it is going to be much slower as we are solving a large linear system if $$l$$ is large. However, we can use the conjugate gradient method we describe in the next section. This will be fast if we can perform the following matrix-vector product fast:

$\left(\sum_{i = 1}^n\mat H_i^\top\mat B_{k - 1,i}\mat H_i\right)\vec z.$

To elaborate on this, each $$\mat H_i^\top\mat B_{k - 1,i}\mat H_i\vec z$$ consists of matrix-vector product with a $$o_i \times o_i$$ symmetric matrix and a vector where $$o_i = (p + q_i)$$. This can be done in $$2o_i(o_i + 1)$$ flops. Thus, the total cost is $$2\sum_{i = 1}^n o_i(o_i + 1)$$ flops. This is in contrast to the original $$2l(l + 1)$$ flops with the BFGS method.

As an example suppose that $$q_i = 5$$ for all $$n$$ element functions, $$n = 5000$$, and $$p = 10$$. Then $$o_i = 15$$ and the matrix-vector product above requires $$2\cdot 5000 \cdot 15(15 + 1) = 2400000$$ flops. In contrast $$l = 5000 \cdot 5 + 10 = 25010$$ and the matrix-vector product in the BFGS method requires $$2\cdot 25010 (25010 + 1) = 1251050220$$ flops. That is 521 times more flops. Similar ratios are shown in the BFGS and Partially Separable Quasi-Newton section.

More formerly, the former is $$\mathcal O(\sum_{i = 1}^n(p + q_{i})^2) = \mathcal O(np^2 + np\bar q + \sum_{i = 1}^nq_i^2)$$ where $$\bar q = \sum_{i = 1}^n q_i / n$$ whereas the matrix-vector product in the BFGS method is $$\mathcal O((p + n\bar q)^2) = \mathcal O(p^2 + pn\bar q + (n\bar q)^2)$$. Thus, the former is favorable as long as $$np^2 + \sum_{i = 1}^nq_i^2$$ is small compared with $$(n\bar q)^2$$. Furthermore, the rank-two BFGS updates are cheaper and may converge faster to a good approximation. However, we should keep in mind that the original BFGS method yields an approximation of $$\mat B_k^{-1}$$. Thus, we do not need to solve a linear system. However, we may not need to take many conjugate gradient iterations to get a good approximation with the implemented quasi-Newton method.

The conjugate gradient method we use solves

$\mat A\vec b = \vec v$

which in our quasi-Newton method is

$\left(\sum_{i = 1}^n\mat H_i^\top\mat B_{k - 1,i}\mat H_i\right)\vec p_k = - \nabla f(\vec x_{k -1})$

We start of with some initial value $$\vec x_0$$. Then we set $$k = 0$$, $$\vec r_0 = \mat A\vec x_0 - \vec v$$, $$\vec p_0 = -\vec r_0$$, and:

1. find the step length $\alpha_k = \frac{\vec r_k^\top\vec r_k}{\vec p_k^\top\mat A\vec p_k},$
2. find the new value $\vec x_{k + 1} = \vec x_k + \alpha_k\vec p_k,$
3. find the new residual $\vec r_{k + 1} = \vec r_k + \alpha_k\mat A\vec p_k,$
4. set $$\beta_{k + 1} = (\vec r_k^\top\vec r_k)^{-1}\vec r_{k + 1}^\top\vec r_{k + 1}$$,
5. set the new search direction to $\vec p_{k + 1} = - \vec r_{k + 1} + \beta_{k + 1}\vec p_k,$ and
6. stop if $$\vec r_{k + 1}^\top\vec r_{k + 1}$$ is smaller. Otherwise set $$k\leftarrow k + 1$$ and repeat.

The main issue is the matrix-vector product $$\mat A\vec p_k$$ but as we argued in the previous section that this can be computed in $$\mathcal O(\sum_{i = 1}^n(p + q_{i})^2)$$ time. The conjugate gradient method will at most take $$h$$ iterations where $$h$$ is the number of rows and columns of $$\mat A$$. Moreover, if $$\mat A$$ only has $$r < h$$ distinct eigenvalues then we will at most make $$r$$ conjugate gradient iterations. Lastly, if $$\mat A$$ has clusters of eigenvalues then we may expect to perform only a number of iterations close to the number of distinct clusters.

In practice, we terminate the conjugate gradient method when $$\lVert\vec r_k\rVert < \min (c, \sqrt{\lVert\nabla f(\vec x_{k -1})\rVert})\lVert\nabla f(\vec x_{k -1})\rVert$$ where $$c$$ is a constant the user can set. Moreover, we the package supports diagonal preconditioning, incomplete Cholesky factorization preconditioning from Eigen, and for the psqn function there is also a preconditioning which is based on a block diagonal matrix which ignores the Hessian terms between the global parameters and the private parameters. The diagonal preconditioning is very cheap and may reduce the number of required conjugate gradient iterations. The incomplete Cholesky factorization preconditioning may greatly reduce the number of required conjugate gradient iterations at the cost of having to factorize the Hessian approximation. The block diagonal approach works very well for some problems and is usually much faster than Eigen.

We can compare the flops of the matrix product in BFGS with applying the conjugate gradient method. Assume that all $$q_i$$s are almost $$\bar q$$. Then the ratio of flops is approximately:

$\frac{p^2 + 2pn\bar q + (n\bar q)^2} {n_{\text{cg}}(np^2 + 2pn\bar q + n\bar q^2)}$

where $$n_{\text{cg}}$$ is the number of conjugate gradient iterations. Thus, to get something which is linear in the number of element functions, $$n$$, then we must have that:

\begin{align*} \frac{n_{\text{cg}}(np^2 + 2pn\bar q + n\bar q^2)} {p^2 + 2pn\bar q + (n\bar q)^2} &\leq \frac kn \\ \Leftrightarrow n_{\text{cg}} &\leq \frac kn \frac{p^2 + 2pn\bar q + (n\bar q)^2} {np^2 + 2pn\bar q + n\bar q^2} \\ &= k\frac{p^2 + 2pn\bar q + (n\bar q)^2} {n^2(p^2 + 2p\bar q + \bar q^2)} \\ &\approx k \frac{\bar q^2}{p^2 + 2p\bar q + \bar q^2} \end{align*}

where $$k$$ is some fixed constant with $$k < n$$. An example of the latter ratio is shown in the BFGS and Partially Separable Quasi-Newton section.

We can get rid of the $$p^2$$ in the denominator by once computing the first $$p\times p$$ part of the Hessian approximation prior to performing the conjugate gradient method. This is implemented. The max_cg argument is added because of the considerations above.

## Line Search and Wolfe Condition

We use line search and search for a point which satisfy the strong Wolfe condition by default. The constants in the Wolfe condition can be set by the user. The line search is implemented as described by Nocedal and Wright (2006) with cubic interpolation in the zoom phase.

Symmetric rank-one (SR1) updates are implemented as an alternative to the BFGS updates. The user can set whether the SR1 updates should be used. The SR1 updates do not guarantee that the Hessian approximation is positive definite. Thus, the conjugate gradient method only proceeds if $$\vec p_k^\top\mat A\vec p_k > 0$$. That is, if the new direction is a descent direction.

## Example Using the Implementation

We simulate a data set below from the mixed logit model we showed earlier.

# assign model parameters, number of random effects, and fixed effects
q <- 4 # number of private parameters per cluster
p <- 5 # number of global parameters
beta <- sqrt((1:p) / sum(1:p))
Sigma <- diag(q)

# simulate a data set
n_clusters <- 800L # number of clusters
set.seed(66608927)

sim_dat <- replicate(n_clusters, {
n_members <- sample.int(20L, 1L) + 2L
X <- matrix(runif(p * n_members, -sqrt(6 / 2), sqrt(6 / 2)),
p)
u <- drop(rnorm(q) %*% chol(Sigma))
Z <- matrix(runif(q * n_members, -sqrt(6 / 2 / q), sqrt(6 / 2 / q)),
q)
eta <- drop(beta %*% X + u %*% Z)
y <- as.numeric((1 + exp(-eta))^(-1) > runif(n_members))

list(X = X, Z = Z, y = y, u = u, Sigma_inv = solve(Sigma))
}, simplify = FALSE)

# example of the first cluster
sim_dat[[1L]]
#> $X #> [,1] [,2] [,3] #> [1,] 0.0416 -0.809 -0.1839 #> [2,] 0.6524 -1.373 -0.9254 #> [3,] -1.3339 -0.957 -0.8708 #> [4,] 0.7547 -0.156 0.0178 #> [5,] 0.7191 -0.681 -0.7232 #> #>$Z
#>        [,1]   [,2]   [,3]
#> [1,]  0.167 -0.483 -0.785
#> [2,] -0.266 -0.823  0.794
#> [3,]  0.609 -0.549  0.269
#> [4,] -0.414 -0.457  0.605
#>
#> $y #> [1] 0 0 0 #> #>$u
#> [1]  0.0705 -1.7285  0.1538 -0.3245
#>
#> $Sigma_inv #> [,1] [,2] [,3] [,4] #> [1,] 1 0 0 0 #> [2,] 0 1 0 0 #> [3,] 0 0 1 0 #> [4,] 0 0 0 1 The combined vector with global and private parameters can be created like this (it is a misnoma to call this true_params as the modes of the random effects, the private parameters, should only match the random effects if the clusters are very large): true_params <- c(beta, sapply(sim_dat, function(x) x$u))

# global parameters
true_params[1:p]
#> [1] 0.258 0.365 0.447 0.516 0.577

# some of the private parameters
true_params[1:(4 * q) + p]
#>  [1]  0.0705 -1.7285  0.1538 -0.3245  0.2516 -0.5419 -0.5537 -0.2805 -1.1777
#> [10] -1.7539  1.7338  0.5616 -0.8379  1.2412 -1.2046  1.4547

As a reference, we will create the following function to evaluate the log of the integrand:

eval_integrand <- function(par){
out <- 0.
inc <- p
beta <- par[1:p]
for(i in seq_along(sim_dat)){
dat <- sim_dat[[i]]
X <- dat$X Z <- dat$Z
y <- dat$y Sigma_inv <- dat$Sigma_inv

u <- par[1:q + inc]
inc <- inc + q
eta <- drop(beta %*% X + u %*% Z)

out <- out - drop(y %*% eta) + sum(log(1 + exp(eta))) +
.5 * drop(u %*% Sigma_inv %*% u)
}

out
}

# check the log integrand at true global parameters and the random effects
eval_integrand(true_params)
#> [1] 6898

We will use this function to compare with our C++ implementation.

### R Implementation

A R function which we need to pass to psqn to minimize the partially separable function is given below:

Here is a check that the above yields the same as the function we defined before:

The partially separable function can be minimized like this:

We will later compare this with the result from the C++ implementation which we provide in the next section.

### Polynomial Example

We consider the following trivial (regression) example as there is an explicit solution to compare with:

\begin{align*} \mathcal G &=\{1,\dots, p\} \\ \mathcal G \cap \mathcal P_i &= \emptyset \\ \mathcal P_j \cap \mathcal P_i &= \emptyset, \qquad i\neq j \\ \mathcal I_i &\in \{1,\dots, p\}^{\lvert\mathcal P_i\rvert} \\ f(\vec x) &= (\vec x_{\mathcal G} - \vec\mu_{\mathcal G})^\top (\vec x_{\mathcal G} - \vec\mu_{\mathcal G}) + \sum_{i = 1}^n (\vec x_{\mathcal P_i} - \vec\mu_{\mathcal P_i} - \mat\Psi_i\vec x_{\mathcal I_i})^\top (\vec x_{\mathcal P_i} - \vec\mu_{\mathcal P_i} - \mat\Psi_i\vec x_{\mathcal I_i}) \end{align*} This is not because the problem is interesting per se but it is meant as another illustration. R code to simulate from this model is given below:

# simulate the data
set.seed(1)
n_global <- 10L
n_clusters <- 50L

mu_global <- rnorm(n_global)
idx_start <- n_global

cluster_dat <- replicate(n_clusters, {
n_members <- sample.int(n_global, 1L)
g_idx <- sort(sample.int(n_global, n_members))
mu_cluster <- rnorm(n_members)
Psi <- matrix(rnorm(n_members * n_members), n_members, n_members)

out <- list(idx = idx_start + 1:n_members, g_idx = g_idx,
mu_cluster = mu_cluster, Psi = Psi)
idx_start <<- idx_start + n_members
out
}, simplify = FALSE)

# assign matrices needed for comparisons
library(Matrix)
M <- diag(idx_start)
for(cl in cluster_dat)
M[cl$idx, cl$g_idx] <- -cl$Psi M <- as(M, "dgCMatrix") # Assign two R functions to evaluate the objective function. There are two # versions of the function to show that we get the same with one being # closer to the shown equation fn_one <- function(par, ...){ delta <- par[1:n_global] - mu_global out <- drop(delta %*% delta) for(cl in cluster_dat){ delta <- drop(par[cl$idx] - cl$mu_cluster - cl$Psi %*% par[cl$g_idx]) out <- out + drop(delta %*% delta) } out } fn_two <- function(par, ...){ mu <- c(mu_global, unlist(sapply(cluster_dat, "[[", "mu_cluster"))) delta <- drop(M %*% par - mu) drop(delta %*% delta) } tmp <- rnorm(idx_start) all.equal(fn_one(tmp), fn_two(tmp)) # we get the same w/ the two #> [1] TRUE fn <- fn_two rm(fn_one, fn_two, tmp) # assign gradient function gr <- function(par, ...){ mu <- c(mu_global, unlist(sapply(cluster_dat, "[[", "mu_cluster"))) 2 * drop(crossprod(M, drop(M %*% par - mu))) } # we can easily find the explicit solution mu <- c(mu_global, unlist(sapply(cluster_dat, "[[", "mu_cluster"))) exp_res <- drop(solve(M, mu)) fn(exp_res) # ~ zero as it should be #> [1] 2.98e-29 C++ code to work with this function is provided at system.file("poly-ex.cpp", package = "psqn") with the package and given below: // see mlogit-ex.cpp for an example with more comments // we will use OpenMP to perform the computation in parallel // [[Rcpp::plugins(openmp, cpp11)]] // we use RcppArmadillo to simplify the code // [[Rcpp::depends(RcppArmadillo)]] #include <RcppArmadillo.h> // [[Rcpp::depends(psqn)]] #include "psqn.h" #include "psqn-reporter.h" using namespace Rcpp; using PSQN::psqn_uint; // the unsigned integer type used in the package /// simple function to avoid copying a vector. You can ignore this inline arma::vec vec_no_cp(double const * x, psqn_uint const n_ele){ return arma::vec(const_cast<double *>(x), n_ele, false); } class poly_func final : public PSQN::element_function { /// global parameter indices arma::uvec const g_idx; /// centroid vector arma::vec const mu_cluster; /// matrix used to transform subset of global parameters arma::mat const Psi; /// number of global parameters psqn_uint const n_global; /// global parameter centroid vector arma::vec const mu_global; /** true if this element function should compute the terms from the global paramaters */ bool const comp_global; public: poly_func(List data, arma::vec const &mu_g, bool const comp_global): g_idx (as<arma::uvec>(data["g_idx" ]) - 1L), mu_cluster(as<arma::vec>(data["mu_cluster"]) ), Psi (as<arma::mat>(data["Psi" ]) ), n_global(mu_g.n_elem), mu_global(comp_global ? mu_g : arma::vec() ), comp_global(comp_global) { } psqn_uint global_dim() const { return n_global; } psqn_uint private_dim() const { return mu_cluster.n_elem; } double func(double const *point) const { arma::vec const x_glob = vec_no_cp(point , n_global), x_priv = vec_no_cp(point + n_global, mu_cluster.n_elem), delta = x_priv - Psi * x_glob(g_idx) - mu_cluster; // compute the function double out(0); out += arma::dot(delta, delta); if(comp_global) out += arma::dot(x_glob - mu_global, x_glob - mu_global); return out; } double grad (double const * point, double * gr) const { arma::vec const x_glob = vec_no_cp(point , n_global), x_priv = vec_no_cp(point + n_global, mu_cluster.n_elem), delta = x_priv - Psi * x_glob(g_idx) - mu_cluster; // create objects to write to for the gradient std::fill(gr, gr + x_glob.n_elem, 0.); arma::vec d_glob(gr , x_glob.n_elem, false), d_priv(gr + x_glob.n_elem, x_priv.n_elem, false); // compute the function and the gradient double out(0); out += arma::dot(delta, delta); d_glob(g_idx) -= 2 * Psi.t() * delta; d_priv = 2 * delta; if(comp_global){ out += arma::dot(x_glob - mu_global, x_glob - mu_global); d_glob += 2. * x_glob; d_glob -= 2 * mu_global; } return out; } bool thread_safe() const { return true; } }; using poly_optim = PSQN::optimizer<poly_func, PSQN::R_reporter, PSQN::R_interrupter>; // [[Rcpp::export]] SEXP get_poly_optimizer(List data, arma::vec const &mu_global, unsigned const max_threads){ psqn_uint const n_elem_funcs = data.size(); std::vector<poly_func> funcs; funcs.reserve(n_elem_funcs); bool comp_global(true); for(auto dat : data){ funcs.emplace_back(List(dat), mu_global, comp_global); comp_global = false; } // create an XPtr to the object we will need XPtr<poly_optim>ptr(new poly_optim(funcs, max_threads)); // return the pointer to be used later return ptr; } // [[Rcpp::export]] List optim_poly (NumericVector val, SEXP ptr, double const rel_eps, unsigned const max_it, unsigned const n_threads, double const c1, double const c2, bool const use_bfgs = true, int const trace = 0L, double const cg_tol = .5, bool const strong_wolfe = true, psqn_uint const max_cg = 0L, int const pre_method = 1L){ XPtr<poly_optim> optim(ptr); // check that we pass a parameter value of the right length if(optim->n_par != static_cast<psqn_uint>(val.size())) throw std::invalid_argument("optim_poly: invalid parameter size"); NumericVector par = clone(val); optim->set_n_threads(n_threads); auto res = optim->optim(&par[0], rel_eps, max_it, c1, c2, use_bfgs, trace, cg_tol, strong_wolfe, max_cg, static_cast<PSQN::precondition>(pre_method)); NumericVector counts = NumericVector::create( res.n_eval, res.n_grad, res.n_cg); counts.names() = CharacterVector::create("function", "gradient", "n_cg"); int const info = static_cast<int>(res.info); return List::create( _["par"] = par, _["value"] = res.value, _["info"] = info, _["counts"] = counts, _["convergence"] = res.info == PSQN::info_code::converged); } // [[Rcpp::export]] double eval_poly(NumericVector val, SEXP ptr, unsigned const n_threads){ XPtr<poly_optim> optim(ptr); // check that we pass a parameter value of the right length if(optim->n_par != static_cast<psqn_uint>(val.size())) throw std::invalid_argument("eval_poly: invalid parameter size"); optim->set_n_threads(n_threads); return optim->eval(&val[0], nullptr, false); } // [[Rcpp::export]] NumericVector grad_poly(NumericVector val, SEXP ptr, unsigned const n_threads){ XPtr<poly_optim> optim(ptr); // check that we pass a parameter value of the right length if(optim->n_par != static_cast<psqn_uint>(val.size())) throw std::invalid_argument("grad_poly: invalid parameter size"); NumericVector grad(val.size()); optim->set_n_threads(n_threads); grad.attr("value") = optim->eval(&val[0], &grad[0], true); return grad; } We can Rcpp::sourceCpp the file and use the code like below to find the solution: A version using the R function psqn is: # assign function to pass to psqn r_func <- function(i, par, comp_grad){ dat <- cluster_dat[[i]] g_idx <- dat$g_idx
mu_cluster <- dat$mu_cluster Psi <- dat$Psi

if(length(par) < 1)
# requested the dimension of the parameter
return(c(global_dim = length(mu_global),
private_dim = length(mu_cluster)))

is_glob <- 1:length(mu_global)
x_glob <- par[is_glob]
x_priv <- par[-is_glob]

delta <- drop(x_priv - Psi %*% x_glob[g_idx] - mu_cluster)

out <- drop(delta %*% delta)
if(i == 1L){
delta_glob <- x_glob - mu_global
out <- out + drop(delta_glob %*% delta_glob)
}

grad[g_idx] <- -2 * drop(crossprod(Psi, delta))
if(i == 1L)
}

out
}

# use the function
r_psqn_func <- function(par, n_threads = 2L, c1 = 1e-4, cg_tol = .5,
c2 = .9, trace = 0L, pre_method = 1L)
psqn(par = par, fn = r_func, n_ele_func = n_clusters,
n_threads = n_threads, c1 = c1, c2 = c2, cg_tol = cg_tol,
trace = trace, max_it = 1000L, pre_method = pre_method)

R_res <- r_psqn_func(numeric(idx_start))
all.equal(exp_res, R_res$par) #> [1] TRUE # with the Cholesky factorizations in the diagonal R_res_chol_diag <- r_psqn_func(numeric(idx_start), pre_method = 3L) all.equal(exp_res, R_res_chol_diag$par)
#> [1] TRUE

# some reduction in the number of conjugate gradient steps
R_res$counts #> function gradient n_cg #> 128 127 1284 R_res_chol_diag$counts
#>      140      139      712

### Generic Example

We will provide a toy example of a problem which is partially separable but which does not have the same structure as the problems we have shown before. The problem we consider is:

\begin{align*} f(\vec x) &= \sum_{i = 1}^n -y_i \sum_{j = 1}^{L_i} x_{k_{ij}} +\exp\left(\sum_{j = 1}^{L_i} x_{k_{ij}}\right) , \qquad \vec x\in\mathbb R^K \\ \mathcal K_i &= \{k_{i1} , \dots, k_{iL_i}\} \subseteq \{1, \dots, K\}. \end{align*} This is a special kind of a GLM with a Poison model with the log link. While there are other ways to estimate this model, we will mainly compare the BFGS implementation from optim with the psqn package. For some $$j\neq i$$, we will have that $$\mathcal K_i \cap \mathcal K_j \neq \emptyset$$ without much structure in their intersection unlike before.

There is a class called optimizer_generic provided by the psqn package which can work with more general partially separable problems like the one above. This though yields some additional computational overhead. A C++ implementation to work with the function stated above using the optimizer_generic class is in the generic_example.cpp file which is shown below:

// see mlogit-ex.cpp for an example with more comments

// we will use OpenMP to perform the computation in parallel
// [[Rcpp::plugins(openmp, cpp11)]]

// we change the unsigned integer type that is used by the package by defining
// the PSQN_SIZE_T macro variable
#define PSQN_SIZE_T unsigned int

// we want to use the incomplete Cholesky factorization as the preconditioner
// and therefore with need RcppEigen
#define PSQN_USE_EIGEN
// [[Rcpp::depends(RcppEigen)]]

// [[Rcpp::depends(psqn)]]
#include "psqn-Rcpp-wrapper.h"
#include "psqn-reporter.h"
#include "psqn.h"
using namespace Rcpp;
using PSQN::psqn_uint; // the unsigned integer type used in the package

class generic_example final : public PSQN::element_function_generic {
/// number of argument to this element function;
psqn_uint const n_args_val;
/// indices of the element function parameters
std::unique_ptr<psqn_uint[]> indices_array;
/// y point
double const y;

public:
generic_example(List data):
n_args_val(as<IntegerVector>(data["indices"]).size()),
indices_array(([&]() -> std::unique_ptr<psqn_uint[]> {
IntegerVector indices = as<IntegerVector>(data["indices"]);
std::unique_ptr<psqn_uint[]> out(new psqn_uint[n_args_val]);
for(psqn_uint i = 0; i < n_args_val; ++i)
out[i] = indices[i];
return out;
})()),
y(as<double>(data["y"]))
{ }

// we need to make a copy constructor because of the unique_ptr
generic_example(generic_example const &other):
n_args_val(other.n_args_val),
indices_array(([&]() -> std::unique_ptr<psqn_uint[]> {
std::unique_ptr<psqn_uint[]> out(new psqn_uint[n_args_val]);
for(psqn_uint i = 0; i < n_args_val; ++i)
out[i] = other.indices_array[i];
return out;
})()),
y(other.y) { }

/**
returns the number of parameters that this element function is depending on.
*/
psqn_uint n_args() const {
return n_args_val;
}

/**
zero-based indices to the parameters that this element function is depending
on.
*/
psqn_uint const * indices() const {
return indices_array.get();
}

double func(double const * point) const {
double sum(0.);
for(psqn_uint i = 0; i < n_args_val; ++i)
sum += point[i];
return -y * sum + std::exp(sum);
}

(double const * point, double * gr) const {
double sum(0.);
for(psqn_uint i = 0; i < n_args_val; ++i)
sum += point[i];
double const exp_sum = std::exp(sum),
fact = -y + exp_sum;
for(psqn_uint i = 0; i < n_args_val; ++i)
gr[i] = fact;

return -y * sum + std::exp(sum);
}

return true;
}
};

using generic_opt =
PSQN::optimizer_generic<generic_example, PSQN::R_reporter,
PSQN::R_interrupter>;

// [[Rcpp::export]]
SEXP get_generic_ex_obj(List data, unsigned const max_threads){
psqn_uint const n_elem_funcs = data.size();
std::vector<generic_example> funcs;
funcs.reserve(n_elem_funcs);
for(auto dat : data)
funcs.emplace_back(List(dat));

// create an XPtr to the object we will need

// return the pointer to be used later
return ptr;
}

// [[Rcpp::export]]
List optim_generic_ex
(NumericVector val, SEXP ptr, double const rel_eps, unsigned const max_it,
unsigned const n_threads, double const c1,
double const c2, bool const use_bfgs = true, int const trace = 0L,
double const cg_tol = .5, bool const strong_wolfe = true,
psqn_uint const max_cg = 0L, int const pre_method = 1L,
double const gr_tol = -1){
XPtr<generic_opt> optim(ptr);

// check that we pass a parameter value of the right length
if(optim->n_par != static_cast<psqn_uint>(val.size()))
throw std::invalid_argument("optim_generic_ex: invalid parameter size");

NumericVector par = clone(val);
auto res = optim->optim(&par[0], rel_eps, max_it, c1, c2,
use_bfgs, trace, cg_tol, strong_wolfe, max_cg,
static_cast<PSQN::precondition>(pre_method),
gr_tol);
NumericVector counts = NumericVector::create(

int const info = static_cast<int>(res.info);
return List::create(
_["par"] = par, _["value"] = res.value, _["info"] = info,
_["counts"] = counts,
_["convergence"] =  res.info == PSQN::info_code::converged);
}

// [[Rcpp::export]]
double eval_generic_ex(NumericVector val, SEXP ptr, unsigned const n_threads){
XPtr<generic_opt> optim(ptr);

// check that we pass a parameter value of the right length
if(optim->n_par != static_cast<psqn_uint>(val.size()))
throw std::invalid_argument("eval_generic_ex: invalid parameter size");

return optim->eval(&val[0], nullptr, false);
}

// [[Rcpp::export]]
XPtr<generic_opt> optim(ptr);

// check that we pass a parameter value of the right length
if(optim->n_par != static_cast<psqn_uint>(val.size()))

}

// [[Rcpp::export]]
NumericMatrix get_Hess_approx_generic(SEXP ptr){
XPtr<generic_opt> optim(ptr);

NumericMatrix out(optim->n_par, optim->n_par);
optim->get_hess(&out[0]);

return out;
}

// [[Rcpp::export]]
Eigen::SparseMatrix<double> get_sparse_Hess_approx_generic(SEXP ptr){
return XPtr<generic_opt>(ptr)->get_hess_sparse();
}

// [[Rcpp::export]]
Eigen::SparseMatrix<double> true_hess_sparse
(SEXP ptr, NumericVector val, double const eps = 0.001, double const scale = 2,
double const tol = 0.000000001, unsigned const order = 6){

XPtr<generic_opt> optim(ptr);

// check that we pass a parameter value of the right length
if(optim->n_par != static_cast<psqn_uint>(val.size()))
throw std::invalid_argument("true_hess_sparse: invalid parameter size");

return optim->true_hess_sparse(&val[0], eps, scale, tol, order);
}

// [[Rcpp::export]]
}

// [[Rcpp::export]]
}

The required member functions are very similar to those needed for the optimizer class. We now simulate some data to work with this type of model as an example:

We can minimize this problem using the following R code:

The model can also be estimated using glm:

The above could possibly be done much faster if sparse matrices where used in glm.fit. The problem can also be solved with the C++ implementation using the following code:

# source the C++ version used in this package
library(Rcpp)
sourceCpp(system.file("generic_example.cpp", package = "psqn"))

# create the list to pass to C++
cpp_arg <- lapply(dat, function(x){
x$indices <- x$indices - 1L # C++ needs zero-based indices
x
})
ptr <- get_generic_ex_obj(cpp_arg, max_threads = 4L)

# check that we get the same
noise <- rnorm(K)
all.equal(eval_generic_ex(noise, ptr = ptr, n_threads = 1L),
R_func         (noise))
#> [1] TRUE
R_func_gr            (noise),
check.attributes = FALSE)
#> [1] TRUE
all.equal(attr(gv, "value"), R_func(noise))
#> [1] TRUE

# also gives the same with two threads
all.equal(eval_generic_ex(noise, ptr = ptr, n_threads = 2L),
R_func         (noise))
#> [1] TRUE
R_func_gr            (noise),
check.attributes = FALSE)
#> [1] TRUE
all.equal(attr(gv, "value"), R_func(noise))
#> [1] TRUE

# optimize and compare the result with one thread
psqn_func <- function(par, n_threads = 1L, c1 = 1e-4, c2 = .1, trace = 0L,
pre_method = 1L, cg_tol = .5)
optim_generic_ex(val = par, ptr = ptr, rel_eps = 1e-9, max_it = 1000L,
n_threads = n_threads, c1 = c1, c2 = c2, trace = trace,
cg_tol = cg_tol, pre_method = pre_method)

opt_psqn <- psqn_func(start)
all.equal(opt_psqn$par, opt$par, tolerance = 1e-3)
#> [1] TRUE
all.equal(opt_psqn$value, opt$value)
#> [1] TRUE
opt_psqn$value - opt$value # (negative values implies a better solution)
#> [1] -0.000102

all.equal(opt_psqn$par, glm_fit$coefficients, tolerance = 1e-3)
#> [1] TRUE
all.equal(opt_psqn$value, R_func(glm_fit$coefficients))
#> [1] TRUE

# compare counts
opt_psqn$counts #> function gradient n_cg #> 93 59 67 opt$counts
#>      425      103

# we can do the same with two threads
opt_psqn <- psqn_func(start, n_threads = 2L)
all.equal(opt_psqn$par, opt$par, tolerance = 1e-3)
#> [1] TRUE
all.equal(opt_psqn$value, opt$value)
#> [1] TRUE
opt_psqn$value - opt$value # (negative values implies a better solution)
#> [1] -0.000102

# compare counts
opt_psqn$counts #> function gradient n_cg #> 93 59 67 opt$counts
#>      425      103

The C++ version is much faster:

#### Generic Example: R Interface

A R interface to the optimizer_generic class is provided through the psqn_generic function. We show an example below of how the R interface can be used to solve the same problem we had before:

The R version is much slower though in this case. The reason is that the element functions are extremely cheap computationally to evaluate and therefore the extra overhead from the R interface is an issue.

### Using Kahan Summation Algorithm

By default, Kahan summation algorithm is used with the optimizer_generic class. This can be avoided by defining PSQN_NO_USE_KAHAN prior to including any headers from the psqn package. One may want to do so if numerical stability does not matter for a given problem. Notice though that the extra computation time may only be substantial if the func and grad member functions are evaluated very fast.

To illustrate this, we will show that the previous method yields almost the same regardless of the number of threads. Then we will show that the difference is larger when we define PSQN_NO_USE_KAHAN but the computation time is reduced.

# we get almost the same regardless of the number of threads. We show this by
# looking at the mean relative error of the gradient

mean(abs((g1 - g2) / g1))
#> [1] 1.3e-16
mean(abs((g1 - g3) / g1))
#> [1] 1.23e-16

# the computation time is as follows
bench::mark(
1 thread  = grad_generic_ex(noise, ptr = ptr, n_threads = 1L),
2 threads = grad_generic_ex(noise, ptr = ptr, n_threads = 2L),
3 threads = grad_generic_ex(noise, ptr = ptr, n_threads = 3L))
#> # A tibble: 3 × 6
#>   expression      min   median itr/sec mem_alloc gc/sec
#>   <bch:expr> <bch:tm> <bch:tm>     <dbl> <bch:byt>    <dbl>
#> 1 1 thread      361µs    372µs     2641.    18.2KB     0
#> 2 2 threads     168µs    175µs     5601.    18.2KB     0
#> 3 3 threads     119µs    123µs     7967.    18.2KB     2.02

# next, we compile the file but having defined PSQN_NO_USE_KAHAN in the
# beginning
tmp_file <- paste0(tempfile(), ".cpp")
tmp_file_con <- file(tmp_file)
writeLines(
# add the macro definition to the beginning of the file
c("#define PSQN_NO_USE_KAHAN",
tmp_file_con)
close(tmp_file_con)
sourceCpp(tmp_file) # source the file again

# re-compute the gradient and the mean relative error of the gradient
ptr <- get_generic_ex_obj(cpp_arg, max_threads = 4L)

mean(abs((g1     - new_g1) / g1    ))
#> [1] 3.9e-16
mean(abs((new_g1 - new_g2) / new_g1))
#> [1] 2.49e-16
mean(abs((new_g1 - new_g3) / new_g1))
#> [1] 2.76e-16

# check the new computation time
bench::mark(
1 thread  = grad_generic_ex(noise, ptr = ptr, n_threads = 1L),
2 threads = grad_generic_ex(noise, ptr = ptr, n_threads = 2L),
3 threads = grad_generic_ex(noise, ptr = ptr, n_threads = 3L))
#> # A tibble: 3 × 6
#>   expression      min   median itr/sec mem_alloc gc/sec
#>   <bch:expr> <bch:tm> <bch:tm>     <dbl> <bch:byt>    <dbl>
#> 1 1 thread      334µs    339µs     2920.    18.2KB     0
#> 2 2 threads     156µs    161µs     6076.    18.2KB     0
#> 3 3 threads     111µs    115µs     8568.    18.2KB     2.02

The error is only slightly larger in the latter case in this example and the computation time is reduced because the func and grad member functions are cheap to evaluate computationally.

## Details

### Using the Code in a Package

The main part of this packages is a header-only library. Thus, the code can be used within a R package by adding psqn to LinkingTo in the DESCRIPTION file. This is an advantage as one can avoid repeated compilation of the code.

Moreover, since the main part of the code is a header-only library, this package can easily be used within languages which can easily call C++ code.

### BFGS Method

There is also a BFGS implementation in the package. This is both available in R through the psqn_bfgs function and in C++ in the psqn-bfgs.h header file. An example is provided below using the example from optim:

### BFGS and Partially Separable Quasi-Newton

Below we show the ratio of flops required in the matrix-vector product in a BFGS method relative to the flops required in the matrix-vector product for the conjugate gradient method for the quasi-Newton method:

n p/q 4 8 16 32 64 128 256
256 4 57 105 156 196 223 238 247
512 4 114 210 312 393 447 477 494
1024 4 228 420 624 787 894 955 988
2048 4 455 840 1248 1574 1787 1911 1977
4096 4 910 1680 2496 3149 3575 3822 3955
8192 4 1820 3361 4993 6297 7151 7645 7911
256 8 26 60 109 160 199 225 239
512 8 52 120 218 320 399 450 479
1024 8 105 241 437 639 798 900 959
2048 8 210 482 874 1279 1596 1801 1918
4096 8 420 964 1748 2557 3192 3601 3837
8192 8 840 1928 3495 5115 6384 7203 7674
256 16 10 27 62 111 162 201 226
512 16 19 55 124 223 323 401 451
1024 16 39 109 248 446 647 803 903
2048 16 78 218 496 892 1294 1607 1807
4096 16 156 437 993 1783 2589 3214 3615
8192 16 312 874 1986 3567 5178 6428 7230

The

$\frac{\bar q^2}{p^2 + 2p\bar q + \bar q^2}$

ratio from the section called Conjugate Gradient Method is shown below:

p/q 4 8 16 32 64 128 256 512 1024
4 0.2500 0.4444 0.6400 0.7901 0.886 0.940 0.970 0.985 0.992
8 0.1111 0.2500 0.4444 0.6400 0.790 0.886 0.940 0.970 0.985
16 0.0400 0.1111 0.2500 0.4444 0.640 0.790 0.886 0.940 0.970
32 0.0123 0.0400 0.1111 0.2500 0.444 0.640 0.790 0.886 0.940
64 0.0035 0.0123 0.0400 0.1111 0.250 0.444 0.640 0.790 0.886
128 0.0009 0.0035 0.0123 0.0400 0.111 0.250 0.444 0.640 0.790
256 0.0002 0.0009 0.0035 0.0123 0.040 0.111 0.250 0.444 0.640

We can get rid of the $$p^2$$ term which gives us:

p/q 4 8 16 32 64 128 256 512 1024
4 0.3333 0.5000 0.6667 0.8000 0.889 0.941 0.970 0.985 0.992
8 0.2000 0.3333 0.5000 0.6667 0.800 0.889 0.941 0.970 0.985
16 0.1111 0.2000 0.3333 0.5000 0.667 0.800 0.889 0.941 0.970
32 0.0588 0.1111 0.2000 0.3333 0.500 0.667 0.800 0.889 0.941
64 0.0303 0.0588 0.1111 0.2000 0.333 0.500 0.667 0.800 0.889
128 0.0154 0.0303 0.0588 0.1111 0.200 0.333 0.500 0.667 0.800
256 0.0078 0.0154 0.0303 0.0588 0.111 0.200 0.333 0.500 0.667

This is implemented.

## References

Nocedal, Jorge, and Stephen Wright. 2006. Numerical Optimization. 2nd ed. Springer Science & Business Media. https://doi.org/10.1007/978-0-387-40065-5.

Ormerod, J. T. 2011. “Skew-Normal Variational Approximations for Bayesian Inference.” Unpublished Article.

Ormerod, J. T., and M. P. Wand. 2012. “Gaussian Variational Approximate Inference for Generalized Linear Mixed Models.” Journal of Computational and Graphical Statistics 21 (1): 2–17. https://doi.org/10.1198/jcgs.2011.09118.