Simulating a Markov Chain [MC, QMC, RQMC]

One of the first steps in the Matched-Expectations Path (MEP) algorithm for solving Heterogeneous Agent models with Aggregate Shocks is to generate a T-period sequence of values of the Markov process on the aggregate shock. The obvious and simplest way to do this is to simulate the process —pick an arbitrary value for period 1, then use a random number generator together with the markov transition matrix to iteratively create periods 2 to T— which is formally known as Monte Carlo simulation of the markov chain. This is the approach used by both Hanbaek Lee’s codes, and the original implementation of MEP in VFI Toolkit.

Creating this sequence is low cost (relative to the rest of the algorithm) and the choice of sequence is likely important to the performance of the MEP algorithm (as an extreme, there is a non-zero probability we just simulate a path that takes the same value of the aggregate shock in every period in which case the MEP will fail). This suggests that if we can find a way to ‘reliably’ produce the sequence of aggregate shocks with ‘good properties’, and if the cost of doing so is moderate, then it will improve the performance of MEP. Hopefully it will allow using smaller T, but at a minimum it should make the algorithm more ‘stable’ across runs.

In what follows I will first explain MC, QMC, and RQMC in the context of uniformly distributed i.i.d random variables, and then once we have established these concepts I will extend them to more general i.i.d. random variables and to markov chains. To fix ideas, we will initially pretend that the ‘good property’ we want our shock sequences to have is simply an unbiased low-variance estimator of the mean, and then later we will think more generally what ‘good properties’ might mean in the context of the MEP algorithm.

Imagine that our interest is around simulating an i.i.d random variable X \sim Uniform(0,1), and the ‘good property’ we care about is estimating the mean of the random variable, \mu=E[X]. Focusing on a uniform i.i.d. variable will make it easier to introduce the concepts, and will turn out to easily generalize to cover lots of other situations.

Monte Carlo (MC) method estimates \mu by
\bar{X}_n = \frac{1}{n} \sum_{i=1}^{n} X_i
where X_1, X_2, \dots, X_n are n independent U(0,1) random variables. To implement this we simply use a random number generator to create the X_i and then compute their sum.

Using random sequences like this leaves us open to the aforementioned issue that on rare occasion we will be very unlucky in our random draw and get, e.g., that all n=10 draws of our U(0,1) are less than 0.1.

Quasi-Monte Carlo (QMC) replaces the independent random draws X_i with a set of deterministic points P_n=\{y_1,y_2,\dots,y_n\} that cover [0,1) more evenly. QMC estimates \mu by,
\bar{\mu}_n = \frac{1}{n} \sum_{i=1}^{n} y_i
Roughly speaking, P_n is called a highly-uniform point set or low-discrepancy point set if some measure of discrepancy between the empirical distribution of P_n and the uniform distribution converges to 0 faster than \mathcal{O}(n^{-1/2}), which is the typical rate for independent random points, as n \to \infty.

There are two main problems with QMC, both stemming directly from the fact it is deterministic. The first is that QMC will have a non-zero error in the estimate (we cannot call it biased, due to the non-random nature you cannot even define what unbiased would mean but it is a problem in a similar vein to bias). The second is that QMC does not allow us to compute the variance of the estimator (again, inescapably due to the non-random nature of QMC). Both of these are ‘fixed’ by Randomized Quasi-Monte Carlo (RQMC), which as it turns out also happily happens to provide convergence of the estimator at least as fast as QMC, and in some situations even faster than QMC, as well as having a few other minor nicer properties than QMC.

Randomized Quasi-Monte Carlo (RQMC) takes the QMC and shifts/scrambles the points such that
(i) each individual point is uniformly distributed (0,1), marginally
(ii) the set of points collectively retain their low-discrepancy structure
Implementing RQMC involves applying some form of shifting/scrambling that constructs our random set \{z_1,z_2,\dots,z_n\} from the QMC set \{y_1,y_2,\dots,y_n\}, and this shifting/scrambling is done in such a way as to introduce (i), while maintaining (ii). RQMC estimates \mu by,
\bar{\mu}_{n,rqmc} = \frac{1}{n} \sum_{i=1}^{n} z_i
a later post will discuss how to perform shifting/scrambling, but some of the main methods are lattice rules and digital nets. As long as we are careful about both how the deterministic sequence was created, and about how the shifting/scrambling was implemented the RQMC gives us an unbiased and low-variance estimator for \mu. Simulation studies show that RQMC often substantially outperforms both MC and QMC, with the gains depending on the application.

So far everything has been done with a one-dimensional Uniform(0,1) i.i.d. random variable. All of this extends trivially to s-dimensions, with a Uniform(0,1)^s i.i.d random variables. Since most i.i.d. distributions can be expressed as a function of a uniform variable, we simply switch all the above sums to look like \frac{1}{n} \sum_{i=1}^{n} f(x_i) with f(x_i) in place of x_i and this covers essentially all other random variables of interest. [In fact ‘create uniform and transform to desired distribution’ is how computers create draws from essentially all the other distributions.] Notice that this same f(x_i) setting also covers when our interest is in the behaviour of higher-order moments, rather than the mean.

That will do for this post. We have seen the ideas of MC, QMC and RQMC for i.i.d. random variables. In the next post I will describe how to construct the deterministic set for QMC and how to perform the shifting/scrambling involved in getting from QMC to RQMC. The post after that will discuss how to extend all of this to Markov Chains. The post after that will discuss the application to MEP.

PS. This post leans heavily on L’Ecuyer - Randomized Quasi-Monte Carlo: An Introduction for Practitioners.

PPS. Of course in practice the random numbers used by computers are not truly random. Instead they come from a pseudo-random number generator, a deterministic sequence constructed to look random (Matlab’s default is the Mersenne Twister). Good pseudo-random number generators are themselves designed on discrepancy-like criteria: the set of all points the generator can ever produce is made as uniform as possible (1,2). So your “random” numbers are, in a sense, a random slice of one enormous QMC-like point set. There is no theorem that MC with a pseudo-random number generator converges exactly as MC with true randomness would, but modern generators pass extensive empirical test batteries and this has not been found to matter in practice.

1 Like

RQMC involves building a set \{z_1,z_2,\dots,z_n\} of n points in U(0,1)^s, where s is the dimension of the space. This set of points is required to satisfy two conditions,
(i) each individual point is uniformly distributed (0,1), marginally
(ii) the set of points collectively are low-discrepancy

There are three main approaches to doing this, all of which can be thought of as consisting of two steps, the first step is to create a deterministic set of low-discrepancy points, and the second step is to ‘add’ some randomness to these (without breaking the low-discrepancy). Notice that the first step is essentially to create the QMC set, and the second converts this to a RQMC set. These three are stratification, lattice rules, and digital nets.

First stratification. Say we have a (s=1) Uniform(0,1) i.i.d random variable, and consider building a sample of n=3 points (n=3 is too small in practice, but helps keep the example simple). MC would involve drawing n=3 points at random. QMC using stratification would divide the [0,1] interval into three equally size (equally probable) sections, [0,1/3], [1/3,2/3], and [2/3,1], and then choosing the midpoint of each of these as the point for our set which would thus be \{1/6,1/2,5/6\}. RQMC using stratification would instead use the same three sections and draw a random number from each interval (this can be thought of as two steps, first the QMC, then add randomness drawn from U(-1/6,1/6) to shift each point).

Second, digital nets. Digital nets are a generalization of the Sobol sequence, perhaps the best known QMC method. There are a lot of materials to explain Sobol sequences online (the picture in top right of wikipedia gives you main idea), and they are non-trivial so I won’t attempt to do so here (plus you are unlikely to code them yourself as there are a lot of implementations out there). To create a RQMC you add a ‘random diagonal shift in base 2’ to the Sobol sequence (the Sobol sequence is constructed around base 2). Importantly, a more powerful but more computationally costly randomization for digital nets is ‘Owen Scrambling’ which is a ‘nested uniform scramble’.

I won’t attempt to explain lattice rules here. For lattice rules, and for much more detail on both stratification and digital nets, see Section 2 of L’Ecuyer - Randomized Quasi-Monte Carlo: An Introduction for Practitioners.

The choice of method has important implications for the asymptotic properties of an RQMC-based estimator. If we were to use standard MC, the asymptotic distribution of the estimates would be normally distributed. If we use an RQMC estimator with a randomly-shifted lattice rule, the limiting distribution as n \to \infty is usually a spline, not a normal distribution [https://doi.org/10.1214/10-EJS574]. If we use an RQMC estimator with a digital net and a digital random shift, this is also not normally distributed (in one dimension it is equivalent to a randomly-shifted lattice). If we use an RQMC estimator with a digital net and nested uniform scrambling (Owen scrambling) then a standard CLT applies and the asymptotic distribution is normally distributed [https://doi.org/10.1214/aos/1059655914].

Summing up. To build the RQMC sets we typically first build a QMC set using some deterministic rule (stratification, lattice rules, digital nets) and then convert this into a RQMC set by adding randomness (being very careful exactly how the randomness is added so as not to break the low-discrepancy properties of the set). Using RQMC in place of MC can mess with the asymptotic properties of an estimator, the exception is using a digital net with Owen scrambling, which, for smooth functions, gives a normal limit once we normalize by the true standard deviation. Theory tells us that RQMC has faster rates of convergence than MC (RQMC has the same rates of convergence as QMC in most situations, faster than QMC is a few situations).

Here are some codes illustrating MC, QMC and RQMC for estimating the mean of a Uniform(0,1) i.i.d. random variable. QMC is done with stratification and with Sobol sequence. RQMC does (i) stratification+random shift (it applies the same random shift to all, rather than doing a different shift for each, both are valid), (ii) Sobol sequence + random shift, (iii) Sobol sequence + Owen scrambling, (iv) Sobol sequence + Matlab’s built-in scramble(p,‘MatousekAffineOwen’). You can clearly see that the RQMC is much lower variance than the MC, that the QMC is deterministic, and that RQMC typically does not produce normally distributed asymptotic distributions, except when Owen nested scrambling is used (which is what Owen scrambling is designed to do).

PS. At first glance QMC looks a lot like quadrature (such as the quadrature methods of Tauchen, Rouwenhorst, Tanaka-Toda and Farmer-Toda which are all widely used in Economics). Both involve replacing random variables with a deterministic set of points. The difference is in what the objective is when choosing the points. Quadrature aims to place the points to evaluate integrals of smooth functions in low dimensions. QMC aims to place the points to be evenly spread.

To extend these ideas to a Markov chain, where we want to create a T-period sequence of states, \{x^1, x^2, \dots, x^T\}, the basic idea in all cases is that the rows of the transition matrix can be drawn from using a Uniform(0,1) i.i.d. draw. Since we already have MC, QMC and RQMC methods for generating Uniform(0,1) i.i.d. draws it is simply a question of exactly how to apply them.

To fix ideas, say our Markov chain has n possible state values, x_1, x_2, \dots, x_n (note the subscript for state value, while the superscript denoted time period of the time series) and transition matrix
P = \left[ \begin{array}{cccc} p_{11} & p_{12} & \cdots & p_{1n} \\ p_{21} & p_{22} & \cdots & p_{2n} \\ \vdots & \vdots & \ddots & \vdots \\ p_{n1} & p_{n2} & \cdots & p_{nn} \end{array} \right]
where p_{ij} is the probability of transitioning to x_j next period given we are in x_i this period. By definition, for any row i the values must sum to one (we must go ‘somewhere’ next period), that is \sum_{j=1}^n p_{ij} = 1 for all i=1,\dots,n.

For MC of a Markov Chain we pick some starting state, say x^1=x_2. Then in period t=1 we consider the row [p_{21}, p_{22}, \dots, p_{2n}] and draw a Uniform(0,1) i.i.d. number, we then set x^2=x_j*, where x_j* is such our uniform draw lies between the cumulative sum of the transition probabilities including and not-including x_j*. For example, say we set n=3, a three-state Markov Chain, with the starting state x^1=x_2 and the second row of our transition matrix is [0.2,0.6,0.2]: if we draw the random U(0,1) number and get 0.79, we go to x^2=x_2 because this is above 0.2 and below 0.8 (=0.2+0.6); more generally if we are in state x_2 and draw a random number \leq 0.2 then we will transition to state one, if we draw a random number >0.2 but \leq 0.8 (=0.2+0.6) then we go to state two, and if we draw a random number >0.8 but \leq 1 (=0.2+0.6+0.2) we go to state three.

Rewriting this more formally. For MC of a Markov Chain we pick some starting state, say x^1=x_2. Then in period t=1 we consider the row [p_{21}, p_{22}, \dots, p_{2n}] and draw a Uniform(0,1) i.i.d. number, u^1, we then set x^2=x_j where j is the smallest index such that u^1 \leq \sum_{k=1}^{j} p_{2k}. That is, we compute the cumulative sums of the row, \mathit{cs}_{2j} = \sum_{k=1}^{j} p_{2k} for j=1,\dots,n (so \mathit{cs}_{2n}=1), and set x^2=x_j if \mathit{cs}_{2,j-1} < u^1 \leq \mathit{cs}_{2j} (with \mathit{cs}_{20}=0). Because u^1 is uniform, the probability that it falls in the interval (\mathit{cs}_{2,j-1}, \mathit{cs}_{2j}] is exactly \mathit{cs}_{2j}-\mathit{cs}_{2,j-1}=p_{2j}, so x^2 has the correct conditional distribution. We then repeat: in period t=2, if x^2=x_j we use row j of the transition matrix and a new independent draw u^2 to get x^3, and so on for t=3,\dots,T, giving the simulated time series x^1, x^2, \dots, x^T.

So our basic MC for a Markov chain loops from t=1 up to t=T and in each period we use a random number generator to draw from U(0,1) and then based on the row of the transition matrix we decide where to transition. Notice that this involves a sequence of length T of draws from U(0,1), which could be precomputed to improve runtimes. We talk about this sequence of uniform random numbers ‘driving’ the Markov chain. With MC of a Markov Chain the empirical transition matrix converges at rate 1/\sqrt{T} in root-mean-square (the scale of the CLT), while almost surely the error is of order \sqrt{\log\log T / T} (the law of the iterated logarithm). (Meyn & Tweedie, Chpt 17).

The obvious extension to QMC is simply to do the same loop from t=1 up to t=T but replacing the use of a random number generator with the QMC methods we saw for generating the sequence of length T of draws from U(0,1). We then just use this QMC-generated uniform sequence to drive the Markov chain exactly as before. Theory tells us that if the QMC method we use is ‘completely uniformly distributed’ (not a given, using Sobol sequences would fail this) then the generated Markov simulations are consistent for the empirical state frequencies and time averages, provided the chain has a unique stationary distribution. (Chentsov, 1967).

An improvement to this QMC approach turns out to be just doing much the same, but with a separate QMC-generated uniform sequence used for the transitions out of each state, so if we have Markov chain with three state values we would use three QMC-generated uniform sequences. This is known formally as a “stack” representation in which each state has its own stack (its own low-discrepancy stream) of uniforms, and the k-th visit to state i uses point k of stack i. Theory tells us the departures from each state are balanced, so the empirical transition matrix and the empirical state frequencies converge at O(\log T / T), faster than the 1/\sqrt{T} of MC. This holds for every realization, with or without a random digital shift or Owen scrambling of each state’s Sobol sequence.

Our next idea is ‘conditional MC’. We construct our sequence of length T to have exactly the expected number of transitions. We want to get counts n_{ij} = T \pi_i p_{ij}, rounded so that every state is entered as often as it is left (allowing for the first and last states). Here n_{ij} is the count for how many transitions from i to j we want to see, T is the sequence length, \pi_i is the probability of state i in the stationary distribution of the Markov, and p_{ij} are the transitions probabilities. Then sample uniformly among all paths with those counts. This is quite tricky, as we want to sample paths, but it can be done with some more advanced techniques that we won’t look into here: these paths are Eulerian trails, and the BEST theorem with a random spanning tree gives an exact sampler (overview/explanation).

We can take the “stack” approach to its deterministic limit, which is called a “rotor”. A rotor is a per-state stack, but instead of a low-discrepancy sequence, each state’s stack is a fixed cycle of next states, ordered so that every stretch of the cycle is balanced. The k-th departure from state i goes to entry k of the i-th cycle. A by-product of rotors is that we achieve the same exact expected number of transitions that we did by conditional MC (but as an output rather than direct input to the construction of the sequence). Theory shows that the error in occupation frequencies is O(1/T), better than QMC’s O(log T / T) (Holroyd & Propp, 2010). Rotors can be understood as the RQMC version of ‘conditional MC’.

One last concept relates to the advanced techniques of how to choose the path that were mentioned in ‘conditional MC’. Rotors perform poorly in terms of spell lengths because their balanced ordering makes the path too regular. A path can also be seen as a sequence of spells, each some periods in the same state. Under the Markov chain spell lengths in state i are geometric with stay probability p_{ii}. We can keep the counts from the rotor and the random order of spells from conditional MC, but draw the spell lengths in each state by stratified sampling from the geometric distribution (one draw in each of K equal intervals, where K is the number of spells in that state) rather than at random, adjusting them slightly so they add up to the total time spent in that state. This turned out to be the best performing approach in our codes.

Here are some codes illustrating MC, QMC and RQMC for simulating a T-period path of a Markov chain, for a two-state chain (like the aggregate shock in Krusell & Smith, 1998) and a five-state Farmer-Toda discretization of an AR(1) with autocorrelation 0.95. QMC is done with (a) a single Sobol sequence driving the whole path, (b) one Sobol sequence per state, (c) a full-period linear congruential generator, which behaves like a CUD sequence when T is small relative to its period, and (d) a rotor-router. RQMC does (i) CUD + random shift, (ii) one Sobol sequence per state + random digital shift, (iii) one Sobol sequence per state + Owen scrambling, (iv) randomized rotor-router (each state starts at a random point of its cycle), (v) fixed transition counts with a random order (a uniformly random path among all paths with the same transition counts as (iv); this is conditional Monte Carlo rather than RQMC), (vi) the same but fixing the two-step counts, and (vii) the same transition counts as (v) but with the lengths of the spells in each state drawn by stratified sampling from a geometric distribution. Besides the mean and variance of the estimator of E[x], the codes report how representative each path is: the error in the empirical transition matrix, in the empirical stationary distribution, in the number of each transition, and in the distribution of spell lengths.

You can clearly see that just swapping the random numbers for a Sobol sequence in (a) fails badly. Balancing the departures from each state ((ii)-(iv)) gets the transition counts almost exactly right, but makes the path far too regular: in the two-state chain every spell lasts exactly 8 periods, rather than being geometric with mean 8. Fixing the counts but randomizing the order (v) keeps the exact counts and gets the spell lengths as right as MC (it is exactly MC conditional on the counts), fixing the two-step counts (vi) does not improve on this, and stratifying the spell lengths (vii) gets them three to four times more accurate than MC (two-and-a-half times in the five-state chain). CUD (i) improves on MC for everything, but by much less. As in the i.i.d. case, the RQMC estimators are typically not normally distributed, although in the five-state chain normality cannot be rejected for the per-state Sobol sequences ((ii) and (iii)); the theory points to normality depending on the choice of T.

PS. I have ignored issues of burn-in here (we want to eliminate dependence on our arbitrary x^1 choice). Burn-in is standard in time series simulation and should be done here for the Markov Chains in most applications. I omitted it in the above descriptions for simplicity.

PPS. MCMC, Markov Chain Monte Carlo is a completely different concept from the ‘Monte Carlo of a Markov Chain’ that we are doing here. MCMC is focused on drawing from a (typically complicated) target distribution, and simply uses Markov Chains as a tool to enable clever sampling.

PPPS. One important RQMC approach used when computing the statistics (mean, variance, evaluate a fn of the markov) is Array-RQMC. We simulate M sequences each of which is length T/M, and the draws for each sequence are done jointly (like cross-equation restrictions). I ignore this here as it is not useful for our goal of using RQMC in the Matched Expectations Path algorithm (although conceptually you might try an ‘Array-MEP’ approach, it would be complicated).

placeholder - MEP algorithm

I build a Lean formalization of all the RQMC theory discussed in the above posts that gives more precise statements of all the results than the above discussion which is aimed more at communicating the concepts.