PyMC and Aesara#

Authors: Ricardo Vieira and Juan Orduz

In this notebook we want to give an introduction of how PyMC models translate to Aesara graphs. The purpose is not to give a detailed description of all aesara’s capabilities but rather focus on the main concepts to understand its connection with PyMC. For a more detailed description of the project please refer to the official documentation.

Prepare Notebook#

First import the required libraries.

import aesara
import aesara.tensor as at
import pymc as pm
import matplotlib.pyplot as plt
import numpy as np
import scipy.stats

# Aesara version: {aesara.__version__}
# PyMC version: {pm.__version__}
# Aesara version: 2.8.2
# PyMC version: 4.2.0+0.g4c92adf9.dirty

Introduction to Aesara#

We start by looking into aesara. According to their documentation

Aesara is a Python library that allows one to define, optimize, and efficiently evaluate mathematical expressions involving multi-dimensional arrays.

aesara logo

A simple example#

To begin, we define some aesara tensors and show how to perform some basic operations.

x = at.scalar(name="x")
y = at.vector(name="y")

x type: {x.type}
x name = {}
y type: {y.type}
y name = {}
x type: TensorType(float64, ())
x name = x
y type: TensorType(float64, (None,))
y name = y

Now that we have defined the x and y tensors, we can create a new one by adding them together.

z = x + y = "x + y"

To make the computation a bit more complex let us take the logarithm of the resulting tensor.

w = at.log(z) = "log(x + y)"

We can use the dprint() function to print the computational graph of any given tensor.

Elemwise{log,no_inplace} [id A] 'log(x + y)'
 |Elemwise{add,no_inplace} [id B] 'x + y'
   |InplaceDimShuffle{x} [id C]
   | |x [id D]
   |y [id E]
<ipykernel.iostream.OutStream at 0x7f1f7b410c10>

Note that this graph does not do any computation (yet!). It is simply defining the sequence of steps to be done. We can use function() to define a callable object so that we can push values trough the graph.

f = aesara.function(inputs=[x, y], outputs=w)

Now that the graph is compiled, we can push some concrete values:

f(x=0, y=[1, np.e])
array([0., 1.])


Sometimes we just want to debug, we can use eval() for that:

w.eval({x: 0, y: [1, np.e]})
array([0., 1.])

You can set intermediate values as well

w.eval({z: [1, np.e]})
array([0., 1.])

Aesara is clever!#

One of the most important features of aesara is that it can automatically optimize the mathematical operations inside a graph. Let’s consider a simple example:

a = at.scalar(name="a")
b = at.scalar(name="b")

c = a / b = "a / b"

Elemwise{true_div,no_inplace} [id A] 'a / b'
 |a [id B]
 |b [id C]
<ipykernel.iostream.OutStream at 0x7f1f7b410c10>

Now let us multiply b times c. This should result in simply a.

d = b * c = "b * c"

Elemwise{mul,no_inplace} [id A] 'b * c'
 |b [id B]
 |Elemwise{true_div,no_inplace} [id C] 'a / b'
   |a [id D]
   |b [id B]
<ipykernel.iostream.OutStream at 0x7f1f7b410c10>

The graph shows the full computation, but once we compile it the operation becomes the identity on a as expected.

g = aesara.function(inputs=[a, b], outputs=d)

DeepCopyOp [id A] 'a' 0
 |a [id B]
<ipykernel.iostream.OutStream at 0x7f1f7b410c10>

What is in an Aesara graph?#

The following diagram shows the basic structure of an aesara graph.

aesara graph

We can can make these concepts more tangible by explicitly indicating them in the first example from the section above. Let us compute the graph components for the tensor z.

z type: {z.type}
z name = {}
z owner = {z.owner}
z owner inputs = {z.owner.inputs}
z owner op = {z.owner.op}
z owner output = {z.owner.outputs}
z type: TensorType(float64, (None,))
z name = x + y
z owner = Elemwise{add,no_inplace}(InplaceDimShuffle{x}.0, y)
z owner inputs = [InplaceDimShuffle{x}.0, y]
z owner op = Elemwise{add,no_inplace}
z owner output = [x + y]

The following code snippet helps us understand these concepts by going through the computational graph of w. The actual code is not as important here, the focus is on the outputs.

# start from the top
stack = [w]

while stack:
    var = stack.pop(0)
    print(f"Checking variable {var} of type {var.type}")
    # check variable is not a root variable
    if var.owner is not None:
        print(f" > Op is {var.owner.op}")
        # loop over the inputs
        for i, input in enumerate(var.owner.inputs):
            print(f" > Input {i} is {input}")
        print(f" > {var} is a root variable")
Checking variable log(x + y) of type TensorType(float64, (None,))
 > Op is Elemwise{log,no_inplace}
 > Input 0 is x + y
Checking variable x + y of type TensorType(float64, (None,))
 > Op is Elemwise{add,no_inplace}
 > Input 0 is InplaceDimShuffle{x}.0
 > Input 1 is y
Checking variable InplaceDimShuffle{x}.0 of type TensorType(float64, (1,))
 > Op is InplaceDimShuffle{x}
 > Input 0 is x
Checking variable y of type TensorType(float64, (None,))
 > y is a root variable
Checking variable x of type TensorType(float64, ())
 > x is a root variable

Note that this is very similar to the output of dprint() function introduced above.

Elemwise{log,no_inplace} [id A] 'log(x + y)'
 |Elemwise{add,no_inplace} [id B] 'x + y'
   |InplaceDimShuffle{x} [id C]
   | |x [id D]
   |y [id E]
<ipykernel.iostream.OutStream at 0x7f1f7b410c10>

Graph manipulation 101#

Another interesting feature of Aesara is the ability to manipulate the computational graph, something that is not possible with TensorFlow or PyTorch. Here we continue with the example above in order to illustrate the main idea around this technique.

# get input tensors
[x, y]

As a simple example, let’s add an exp() before the log() (to get the identity function).

parent_of_w = w.owner.inputs[0]  # get z tensor
new_parent_of_w = at.exp(parent_of_w)  # modify the parent of w = "exp(x + y)"

Note that the graph of w has actually not changed:

Elemwise{log,no_inplace} [id A] 'log(x + y)'
 |Elemwise{add,no_inplace} [id B] 'x + y'
   |InplaceDimShuffle{x} [id C]
   | |x [id D]
   |y [id E]
<ipykernel.iostream.OutStream at 0x7f1f7b410c10>

To modify the graph we need to use the clone_replace() function, which returns a copy of the initial subgraph with the corresponding substitutions.

new_w = aesara.clone_replace(output=[w], replace={parent_of_w: new_parent_of_w})[0] = "log(exp(x + y))"
Elemwise{log,no_inplace} [id A] 'log(exp(x + y))'
 |Elemwise{exp,no_inplace} [id B] 'exp(x + y)'
   |Elemwise{add,no_inplace} [id C] 'x + y'
     |InplaceDimShuffle{x} [id D]
     | |x [id E]
     |y [id F]
<ipykernel.iostream.OutStream at 0x7f1f7b410c10>

Finally, we can test the modified graph by passing some input to the new graph.

new_w.eval({x: 0, y: [1, np.e]})
array([1.        , 2.71828183])

As expected, the new graph is just the identity function.


Again, note that aesara is clever enough to omit the exp and log once we compile the function.

f = aesara.function(inputs=[x, y], outputs=new_w)

Elemwise{add,no_inplace} [id A] 'x + y' 1
 |InplaceDimShuffle{x} [id B] 0
 | |x [id C]
 |y [id D]
<ipykernel.iostream.OutStream at 0x7f1f7b410c10>
f(x=0, y=[1, np.e])
array([1.        , 2.71828183])

Aesara RandomVariables#

Now that we have seen aesara’s basics we want to move in the direction of random variables.

How do we generate random numbers in numpy? To illustrate it we can sample from a normal distribution:

a = np.random.normal(loc=0, scale=1, size=1_000)

fig, ax = plt.subplots(figsize=(8, 6))
ax.hist(a, color="C0", bins=15)
ax.set(title="Samples from a normal distribution using numpy", ylabel="count");

Now let’s try to do it in Aesara.

y = at.random.normal(loc=0, scale=1, name="y")
TensorType(float64, ())

Next, we show the graph using dprint().

normal_rv{0, (0, 0), floatX, False}.1 [id A] 'y'
 |RandomGeneratorSharedVariable(<Generator(PCG64) at 0x7F1F3090D0E0>) [id B]
 |TensorConstant{[]} [id C]
 |TensorConstant{11} [id D]
 |TensorConstant{0} [id E]
 |TensorConstant{1} [id F]
<ipykernel.iostream.OutStream at 0x7f1f7b410c10>

The inputs are always in the following order:

  1. rng shared variable

  2. size

  3. dtype (number code)

  4. arg1

  5. arg2

  6. argn

We could sample by calling eval(). on the random variable.


Note however that these samples are always the same!

for i in range(10):
    print(f"Sample {i}: {y.eval()}")
Sample 0: -0.5260165446973327
Sample 1: -0.5260165446973327
Sample 2: -0.5260165446973327
Sample 3: -0.5260165446973327
Sample 4: -0.5260165446973327
Sample 5: -0.5260165446973327
Sample 6: -0.5260165446973327
Sample 7: -0.5260165446973327
Sample 8: -0.5260165446973327
Sample 9: -0.5260165446973327

We always get the same samples! This has to do with the random seed step in the graph, i.e. RandomGeneratorSharedVariable (we will not go deeper into this subject here). We will show how to generate different samples with pymc below.


pymc logo

To do so, we start by defining a pymc normal distribution.

x = pm.Normal.dist(mu=0, sigma=1)
normal_rv{0, (0, 0), floatX, False}.1 [id A]
 |RandomGeneratorSharedVariable(<Generator(PCG64) at 0x7F1F30821C40>) [id B]
 |TensorConstant{[]} [id C]
 |TensorConstant{11} [id D]
 |TensorConstant{0} [id E]
 |TensorConstant{1.0} [id F]
<ipykernel.iostream.OutStream at 0x7f1f7b410c10>

Observe that x is just a normal RandomVariable and which is the same as y except for the rng.

We can try to generate samples by calling eval() as above.

for i in range(10):
    print(f"Sample {i}: {x.eval()}")
Sample 0: -0.22942897291443926
Sample 1: -0.22942897291443926
Sample 2: -0.22942897291443926
Sample 3: -0.22942897291443926
Sample 4: -0.22942897291443926
Sample 5: -0.22942897291443926
Sample 6: -0.22942897291443926
Sample 7: -0.22942897291443926
Sample 8: -0.22942897291443926
Sample 9: -0.22942897291443926

As before we get the same value for all iterations. The correct way to generate random samples is using draw().

fig, ax = plt.subplots(figsize=(8, 6))
ax.hist(pm.draw(x, draws=1_000), color="C1", bins=15)
ax.set(title="Samples from a normal distribution using pymc", ylabel="count");

Yay! We learned how to sample from a pymc distribution!

What is going on behind the scenes?#

We can now look into how this is done inside a Model.

with pm.Model() as model:
    z = pm.Normal(name="z", mu=np.array([0, 0]), sigma=np.array([1, 2]))

normal_rv{0, (0, 0), floatX, False}.1 [id A]
 |RandomGeneratorSharedVariable(<Generator(PCG64) at 0x7F1F306FDFC0>) [id B]
 |TensorConstant{[]} [id C]
 |TensorConstant{11} [id D]
 |TensorConstant{0} [id E]
 |TensorConstant{1.0} [id F]
<ipykernel.iostream.OutStream at 0x7f1f7b410c10>

We are just creating random variables like we saw before, but now registering them in a pymc model. To extract the list of random variables we can simply do:

[z ~ N(<constant>, <constant>)]
normal_rv{0, (0, 0), floatX, False}.1 [id A] 'z'
 |RandomGeneratorSharedVariable(<Generator(PCG64) at 0x7F1F307934C0>) [id B]
 |TensorConstant{[]} [id C]
 |TensorConstant{11} [id D]
 |TensorConstant{(2,) of 0} [id E]
 |TensorConstant{[1. 2.]} [id F]
<ipykernel.iostream.OutStream at 0x7f1f7b410c10>

We can try to sample via eval() as above and it is no surprise that we are getting the same samples at each iteration.

for i in range(10):
    print(f"Sample {i}: {z.eval()}")
Sample 0: [-0.15970593 -2.21389859]
Sample 1: [-0.15970593 -2.21389859]
Sample 2: [-0.15970593 -2.21389859]
Sample 3: [-0.15970593 -2.21389859]
Sample 4: [-0.15970593 -2.21389859]
Sample 5: [-0.15970593 -2.21389859]
Sample 6: [-0.15970593 -2.21389859]
Sample 7: [-0.15970593 -2.21389859]
Sample 8: [-0.15970593 -2.21389859]
Sample 9: [-0.15970593 -2.21389859]

Again, the correct way of sampling is via draw().

for i in range(10):
    print(f"Sample {i}: {pm.draw(z)}")
Sample 0: [1.2027531  2.85831187]
Sample 1: [-1.71946475  2.15238526]
Sample 2: [-0.76456344 -1.8828697 ]
Sample 3: [-0.88725046 -3.34752945]
Sample 4: [1.15433798 0.57261535]
Sample 5: [-2.67064043 -2.33020766]
Sample 6: [ 0.54132106 -2.34714339]
Sample 7: [0.33256226 1.01477596]
Sample 8: [-0.97606247  2.34394758]
Sample 9: [-0.1742904  -0.26795814]
fig, ax = plt.subplots(figsize=(8, 8))
z_draws = pm.draw(vars=z, draws=10_000)
ax.hist2d(x=z_draws[:, 0], y=z_draws[:, 1], bins=25)
ax.set(title="Samples Histogram");

Enough with Random Variables, I want to see some (log)probabilities!#

Recall we have defined the following model above:

\[ \begin{array}{rcl} \text{z} &\sim & \operatorname{N}(\text{<constant>},~\text{<constant>}) \end{array} \]

pymc is able to convert RandomVariables to their respective probability functions. One simple way is to use logp(), which takes as first input a RandomVariable, and as second input the value at which the logp is evaluated (we will discuss this in more detail later).

z_value = at.vector(name="z")
z_logp = pm.logp(rv=z, value=z_value)

z_logp contains the Aesara graph that represents the log-probability of the normal random variable z, evaluated at z_value.

Check{sigma > 0} [id A] 'z_logprob'
 |Elemwise{sub,no_inplace} [id B]
 | |Elemwise{sub,no_inplace} [id C]
 | | |Elemwise{mul,no_inplace} [id D]
 | | | |InplaceDimShuffle{x} [id E]
 | | | | |TensorConstant{-0.5} [id F]
 | | | |Elemwise{pow,no_inplace} [id G]
 | | |   |Elemwise{true_div,no_inplace} [id H]
 | | |   | |Elemwise{sub,no_inplace} [id I]
 | | |   | | |z [id J]
 | | |   | | |TensorConstant{(2,) of 0} [id K]
 | | |   | |TensorConstant{[1. 2.]} [id L]
 | | |   |InplaceDimShuffle{x} [id M]
 | | |     |TensorConstant{2} [id N]
 | | |InplaceDimShuffle{x} [id O]
 | |   |Elemwise{log,no_inplace} [id P]
 | |     |Elemwise{sqrt,no_inplace} [id Q]
 | |       |TensorConstant{6.283185307179586} [id R]
 | |Elemwise{log,no_inplace} [id S]
 |   |TensorConstant{[1. 2.]} [id L]
 |All [id T]
   |Elemwise{gt,no_inplace} [id U]
     |TensorConstant{[1. 2.]} [id L]
     |InplaceDimShuffle{x} [id V]
       |TensorConstant{0.0} [id W]
<ipykernel.iostream.OutStream at 0x7f1f7b410c10>


There is also a handy pymc function to compute the log cumulative probability of a random variable logcdf().

Observe that, as explained at the beginning, there has been no computation yet. The actual computation is performed after compiling and passing the input. For illustration purposes alone, we will again use the handy eval() method.

z_logp.eval({z_value: [0, 0]})
array([-0.91893853, -1.61208571])

This is nothing else than evaluating the log probability of a normal distribution.

scipy.stats.norm.logpdf(x=np.array([0, 0]), loc=np.array([0, 0]), scale=np.array([1, 2]))
array([-0.91893853, -1.61208571])

pymc models provide some helpful routines to facilitating the conversion of RandomVariables to probability functions. logp(), for instance can be used to extract the joint probability of all variables in the model:

Elemwise{mul,no_inplace} [id A]
 |Check{sigma > 0} [id B] 'z_logprob'
 | |Elemwise{sub,no_inplace} [id C]
 | | |Elemwise{sub,no_inplace} [id D]
 | | | |Elemwise{mul,no_inplace} [id E]
 | | | | |InplaceDimShuffle{x} [id F]
 | | | | | |TensorConstant{-0.5} [id G]
 | | | | |Elemwise{pow,no_inplace} [id H]
 | | | |   |Elemwise{true_div,no_inplace} [id I]
 | | | |   | |Elemwise{sub,no_inplace} [id J]
 | | | |   | | |z [id K]
 | | | |   | | |TensorConstant{(2,) of 0} [id L]
 | | | |   | |TensorConstant{[1. 2.]} [id M]
 | | | |   |InplaceDimShuffle{x} [id N]
 | | | |     |TensorConstant{2} [id O]
 | | | |InplaceDimShuffle{x} [id P]
 | | |   |Elemwise{log,no_inplace} [id Q]
 | | |     |Elemwise{sqrt,no_inplace} [id R]
 | | |       |TensorConstant{6.283185307179586} [id S]
 | | |Elemwise{log,no_inplace} [id T]
 | |   |TensorConstant{[1. 2.]} [id M]
 | |All [id U]
 |   |Elemwise{gt,no_inplace} [id V]
 |     |TensorConstant{[1. 2.]} [id M]
 |     |InplaceDimShuffle{x} [id W]
 |       |TensorConstant{0.0} [id X]
 |InplaceDimShuffle{x} [id Y]
   |TensorConstant{1.0} [id Z]
<ipykernel.iostream.OutStream at 0x7f1f7b410c10>

Because we only have one variable, this function is equivalent to what we obtained by manually calling pm.logp before. We can also use a helper compile_logp() to return an already compiled Aesara function of the model logp.

logp_function = model.compile_logp(sum=False)

This function expects a “point” dictionary as input. We could create it ourselves, but just to illustrate another useful Model method, let’s call initial_point(), which returns the point that most samplers use when deciding where to start sampling.

point = model.initial_point()
{'z': array([0., 0.])}
[array([-0.91893853, -1.61208571])]

What are value variables and why are they important?#

As he have seen above, a logp graph does not have random variables. Instead it’s defined in terms of input (value) variables. When we want to sample, each random variable (RV) is replaced by a logp function evaluated at the respective input (value) variable. Let’s see how this works through some examples. RV and value variables can be observed in these scipy operations:

rv = scipy.stats.norm(0, 1)

# Equivalent to rv = pm.Normal("rv", 0, 1)
scipy.stats.norm(0, 1)
<scipy.stats._distn_infrastructure.rv_continuous_frozen at 0x7f1f308fa2f0>
# Equivalent to rv_draw = pm.draw(rv, 3)
array([ 0.39875892, -0.58430235,  0.23791348])
# Equivalent to rv_logp = pm.logp(rv, 1.25)

Next, let’s look at how these value variables behave in a slightly more complex model.

with pm.Model() as model_2:
    mu = pm.Normal(name="mu", mu=0, sigma=2)
    sigma = pm.HalfNormal(name="sigma", sigma=3)
    x = pm.Normal(name="x", mu=mu, sigma=sigma)

Each model RV is related to a “value variable”:

{mu ~ N(0, 2): mu, sigma ~ N**+(0, 3): sigma_log__, x ~ N(mu, sigma): x}

Observe that for sigma the associated value is in the log scale as in practice we require unbounded values for NUTS sampling.

[mu, sigma_log__, x]

Now that we know how to extract the model variables, we can compute the element-wise log-probability of the model for specific values.

# extract values as aesara.tensor.var.TensorVariable
mu_value = model_2.rvs_to_values[mu]
sigma_log_value = model_2.rvs_to_values[sigma]
x_value = model_2.rvs_to_values[x]
# element-wise log-probability of the model (we do not take te sum)
logp_graph = at.stack(model_2.logp(sum=False))
# evaluate by passing concrete values
logp_graph.eval({mu_value: 0, sigma_log_value: -10, x_value: 0})
array([ -1.61208571, -11.32440364,   9.08106147])

This equivalent to:

mu_value -> {scipy.stats.norm.logpdf(x=0, loc=0, scale=2)}
sigma_log_value -> {- 10 + scipy.stats.halfnorm.logpdf(x=np.exp(-10), loc=0, scale=3)} 
x_value -> {scipy.stats.norm.logpdf(x=0, loc=0, scale=np.exp(-10))}
mu_value -> -1.612085713764618
sigma_log_value -> -11.324403641427345 
x_value -> 9.081061466795328


For sigma_log_value we add the \(-10\) term for the scipy and aesara to match because of the jacobian.

As we already saw, we can also use the method compile_logp() to obtain a compiled aesara function of the model logp, which takes a dictionary of {value variable name : value} as inputs:

model_2.compile_logp(sum=False)({"mu": 0, "sigma_log__": -10, "x": 0})
[array(-1.61208571), array(-11.32440364), array(9.08106147)]

The Model class also has methods to extract the gradient (dlogp()) and the hessian (d2logp()) of the logp.

If you want to go deeper into the internals of aesara RandomVariables and pymc distributions please take a look into the distribution developer guide.