# 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
```

## 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.

### 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")
print(
f"""
x type: {x.type}
x name = {x.name}
---
y type: {y.type}
y name = {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
z.name = "x + y"
```

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

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

We can use the `dprint()`

function to print the computational graph of any given tensor.

```
aesara.dprint(w)
```

```
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 0x7ff8aabe7670>
```

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.])
```

Tip

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
c.name = "a / b"
aesara.dprint(c)
```

```
Elemwise{true_div,no_inplace} [id A] 'a / b'
|a [id B]
|b [id C]
```

```
<ipykernel.iostream.OutStream at 0x7ff8aabe7670>
```

Now let us multiply `b`

times `c`

. This should result in simply `a`

.

```
d = b * c
d.name = "b * c"
aesara.dprint(d)
```

```
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 0x7ff8aabe7670>
```

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)
aesara.dprint(g)
```

```
DeepCopyOp [id A] 'a' 0
|a [id B]
```

```
<ipykernel.iostream.OutStream at 0x7ff8aabe7670>
```

### What is in an Aesara graph?#

The following diagram shows the basic structure of an `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`

.

```
print(
f"""
z type: {z.type}
z name = {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:
print("---")
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}")
stack.append(input)
else:
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.

```
aesara.dprint(w)
```

```
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 0x7ff8aabe7670>
```

### 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
list(aesara.graph.graph_inputs(graphs=[w]))
```

```
[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
new_parent_of_w.name = "exp(x + y)"
```

Note that the graph of `w`

has actually not changed:

```
aesara.dprint(w)
```

```
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 0x7ff8aabe7670>
```

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]
new_w.name = "log(exp(x + y))"
aesara.dprint(new_w)
```

```
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 0x7ff8aabe7670>
```

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.

Note

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)
aesara.dprint(f)
```

```
Elemwise{add,no_inplace} [id A] 'x + y' 1
|InplaceDimShuffle{x} [id B] 0
| |x [id C]
|y [id D]
```

```
<ipykernel.iostream.OutStream at 0x7ff8aabe7670>
```

```
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")
y.type
```

```
TensorType(float64, ())
```

Next, we show the graph using `dprint()`

.

```
aesara.dprint(y)
```

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

```
<ipykernel.iostream.OutStream at 0x7ff8aabe7670>
```

The inputs are always in the following order:

`rng`

shared variable`size`

`dtype`

(number code)`arg1`

`arg2`

`argn`

We *could* sample by calling `eval()`

. on the random variable.

```
y.eval()
```

```
array(-1.96919646)
```

Note however that these samples are always the same!

```
for i in range(10):
print(f"Sample {i}: {y.eval()}")
```

```
Sample 0: -1.969196457220078
Sample 1: -1.969196457220078
Sample 2: -1.969196457220078
Sample 3: -1.969196457220078
Sample 4: -1.969196457220078
Sample 5: -1.969196457220078
Sample 6: -1.969196457220078
Sample 7: -1.969196457220078
Sample 8: -1.969196457220078
Sample 9: -1.969196457220078
```

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#

To do so, we start by defining a `pymc`

normal distribution.

```
x = pm.Normal.dist(mu=0, sigma=1)
aesara.dprint(x)
```

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

```
<ipykernel.iostream.OutStream at 0x7ff8aabe7670>
```

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.963072010795125
Sample 1: -0.963072010795125
Sample 2: -0.963072010795125
Sample 3: -0.963072010795125
Sample 4: -0.963072010795125
Sample 5: -0.963072010795125
Sample 6: -0.963072010795125
Sample 7: -0.963072010795125
Sample 8: -0.963072010795125
Sample 9: -0.963072010795125
```

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]))
aesara.dprint(z)
```

```
normal_rv{0, (0, 0), floatX, False}.1 [id A] 'z'
|RandomGeneratorSharedVariable(<Generator(PCG64) at 0x7FF85F6CF3E0>) [id B]
|TensorConstant{[]} [id C]
|TensorConstant{11} [id D]
|TensorConstant{(2,) of 0} [id E]
|TensorConstant{[1. 2.]} [id F]
```

```
<ipykernel.iostream.OutStream at 0x7ff8aabe7670>
```

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:

```
model.basic_RVs
```

```
[z ~ N(<constant>, <constant>)]
```

```
aesara.dprint(model.basic_RVs[0])
```

```
normal_rv{0, (0, 0), floatX, False}.1 [id A] 'z'
|RandomGeneratorSharedVariable(<Generator(PCG64) at 0x7FF85F6CF3E0>) [id B]
|TensorConstant{[]} [id C]
|TensorConstant{11} [id D]
|TensorConstant{(2,) of 0} [id E]
|TensorConstant{[1. 2.]} [id F]
```

```
<ipykernel.iostream.OutStream at 0x7ff8aabe7670>
```

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.36816521 0.47495408]
Sample 1: [0.36816521 0.47495408]
Sample 2: [0.36816521 0.47495408]
Sample 3: [0.36816521 0.47495408]
Sample 4: [0.36816521 0.47495408]
Sample 5: [0.36816521 0.47495408]
Sample 6: [0.36816521 0.47495408]
Sample 7: [0.36816521 0.47495408]
Sample 8: [0.36816521 0.47495408]
Sample 9: [0.36816521 0.47495408]
```

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

.

```
for i in range(10):
print(f"Sample {i}: {pm.draw(z)}")
```

```
Sample 0: [ 1.2168571 -1.34071802]
Sample 1: [ 0.66245756 -1.64540044]
Sample 2: [ 1.39737355 -2.13722836]
Sample 3: [-1.27801971 -0.48974394]
Sample 4: [ 0.26874478 -1.27601123]
Sample 5: [-0.83749323 0.91468551]
Sample 6: [-0.11878778 -2.09173625]
Sample 7: [ 0.65289735 -0.2833437 ]
Sample 8: [ 0.31546199 -0.43580898]
Sample 9: [0.49094959 2.27887957]
```

```
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:

```
model
```

`pymc`

is able to convert `RandomVariable`

s 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`

.

```
aesara.dprint(z_logp)
```

```
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]
|MakeVector{dtype='bool'} [id U]
|All [id V]
|Elemwise{gt,no_inplace} [id W]
|TensorConstant{[1. 2.]} [id L]
|InplaceDimShuffle{x} [id X]
|TensorConstant{0} [id Y]
```

```
<ipykernel.iostream.OutStream at 0x7ff8aabe7670>
```

Tip

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 `RandomVariable`

s to probability functions. `logp()`

, for instance can be used to extract the joint probability of all variables in the model:

```
aesara.dprint(model.logp(sum=False))
```

```
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]
|MakeVector{dtype='bool'} [id U]
|All [id V]
|Elemwise{gt,no_inplace} [id W]
|TensorConstant{[1. 2.]} [id L]
|InplaceDimShuffle{x} [id X]
|TensorConstant{0} [id Y]
```

```
<ipykernel.iostream.OutStream at 0x7ff8aabe7670>
```

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()
point
```

```
{'z': array([0., 0.])}
```

```
logp_function(point)
```

```
[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 0x7ff85f4506d0>
```

```
# Equivalent to rv_draw = pm.draw(rv, 3)
rv.rvs(3)
```

```
array([ 1.1536972 , 0.41846184, -0.28887025])
```

```
# Equivalent to rv_logp = pm.logp(rv, 1.25)
rv.logpdf(1.25)
```

```
-1.7001885332046727
```

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”:

```
model_2.rvs_to_values
```

```
{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.

```
model_2.value_vars
```

```
[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:

```
print(
f"""
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
```

Note

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.