Posterior predictive problems using a CustomDist distribution with a blackbox

Hello

I am trying to create a CustomDist with a black box with gradient for a generic function. The black box seems to work fine : it performs samples using NUTS and it is in good agreement with non-NUTS sampling using a function wrapping.

The problems appears when I try to perform pm.sample_posterior_predictive (to estimate the hdi of my data). Without the black box, the posterior predictive samples are corrects. With the black box, the posterior predictive samples are incorrect and even produce Nan.

I try to check where the problem appears but obviously I missed something… I suppose it is the random function, but it answers compatible values during the sampling…

The blackbox is mainly inspired from the one in pymc examples and is adapted to treat multiple variables inputs.

I have just install the environment :
python 3.12, pymc 6.3.2, xarray 2026.9.0, pytensor 3.3.4, numpy 2.5.4

The code reproducing the problem is here :


import numpy as np
import pymc as pm
import pytensor
import pytensor.tensor as pt
from typing import Optional, Tuple
from pytensor.graph import Apply, Op
from scipy.optimize import approx_fprime


sigma = 0.1
nsample = 5000
nchains = 1
probabilite = 0.95

noise = 0.1
npts = 50
tx = np.linspace(0,10,npts)

def fonctest0(tx,para):
  res = para[0]*tx*tx+para[1]*tx+para[2]  #simple, for test purpose
  return res

para0=[1.,2.,3.]
ty=fonctest0(tx,para0)+noise*(2*np.random.random(npts)-1.)

def random(
  *tmu: np.ndarray ,
  rng: Optional[np.random.Generator] = None,
  size : Optional[Tuple[int]]=None,
  ) -> np.ndarray :
  res=[]
  for mu in tmu[0]:
    r = rng.normal(loc = mu, scale=tmu[1], size=size)
    res.append(r)
  return np.asarray(res)


class calculMCMC():
  def __init__(self,funct,tx,ty,npara):
    self.funct=funct
    self.tx=tx
    self.ty=ty
    self.npara=npara
    
  def calcul(self,para):
    return self.funct(self.tx,para)
   
  def my_loglike(self,para, sigma,  data):
      for param in (para, sigma, data):
          if not isinstance(param, (float, np.ndarray)):
              raise TypeError(f"Invalid input type to loglike: {type(param)}")
      model = self.calcul(para)
      return -0.5 * ((data - model) / sigma) ** 2 - np.log(np.sqrt(2 * np.pi)) - np.log(sigma)
  
  def finite_differences_loglike(self,para, sigma, data, eps=1e-7):
      grad = approx_fprime(para, self.my_loglike, [eps]*self.npara, sigma, data)
      return grad

  
class LogLikeWithGrad(Op):
  def __init__(self,calcul):
    self.calcul=calcul
    self.calcul_grad=LogLikeGrad(calcul,calcul.npara)
    self.npara=calcul.npara
  def make_node(self, para, sigma, data) -> Apply:
    tp=pt.as_tensor(para)
    sigma = pt.as_tensor(sigma)
    data = pt.as_tensor(data)
    inputs = [tp, sigma, data]
    outputs = [data.type()]
    return Apply(self, inputs, outputs)

  def perform(self, node: Apply, inputs: list[np.ndarray], outputs: list[list[None]]) -> None:
    para, sigma, data = inputs  
    loglike_eval = self.calcul.my_loglike(para, sigma, data)
    outputs[0][0] = np.asarray(loglike_eval)

  def grad(self, inputs: list[pt.TensorVariable], g: list[pt.TensorVariable]) -> list[pt.TensorVariable]:
    para, sigma, data = inputs
    grad = self.calcul_grad(para, sigma, data)
    # out_grad is a tensor of gradients of the Op outputs wrt to the function cost
    [out_grad] = g
    return [
      pt.as_tensor([pt.sum(out_grad*gr) for gr in grad]),
      pytensor.gradient.grad_not_implemented(self, 2, sigma),
      pytensor.gradient.grad_not_implemented(self, 3, data),
    ]


class LogLikeGrad(Op):
  def __init__(self,calcul,npara):
    self.calcul=calcul
    self.npara=npara
  def make_node(self, para, sigma, data) -> Apply:
    tp=pt.as_tensor(para)
    sigma = pt.as_tensor(sigma)
    data = pt.as_tensor(data)

    inputs = [tp, sigma, data]
    outputs=[]
    for i in range(self.npara):
      outputs.append(data.type())

    return Apply(self, inputs, outputs)

  def perform(self, node: Apply, inputs: list[np.ndarray], outputs: list[list[None]]) -> None:
    para, sigma, data = inputs

    grad = self.calcul.finite_differences_loglike(para, sigma, data)
    for i in range(self.npara):
      outputs[i][0] = grad[:,i]
        

cal = calculMCMC(fonctest0,tx,ty,len(para0))

# Initialize the Ops
loglikewithgrad_op = LogLikeWithGrad(cal)


sigma = 0.1  # standard deviation of noise

def custom_dist_loglike(data, para, sigma):
    # data, or observed is always passed as the first input of CustomDist
    return loglikewithgrad_op(para, sigma, data)

# use PyMC to sampler from log-likelihood
with pm.Model() as grad_model:
    para=[]
    for k in range(cal.npara):
      para.append(pm.Uniform('a{}'.format(k), lower=-10., upper=10.))
    tp=pt.stack(para)
    # use a CustomDist with a custom logp function
    likelihood = pm.CustomDist(
        "likelihood", tp, sigma, observed=ty,
        logp=custom_dist_loglike,random=random)

    idata_grad = pm.sample(3000, tune=1000)
    posterior_predictive=pm.sample_posterior_predictive(idata_grad)

print(np.max(posterior_predictive['posterior_predictive']['likelihood'].data)) 
#answer : Nan where it should be around 150

If someone can help me with this problem. Thanks

Do you need a custom loglikelihood or it’s just gaussian around a blackbox? If the latter you can just use CustomOp for that part and forego all the complexity of CustomDist

Hello. Thank you for the answer.

When I started using pymc (pymc3.6 if I remember), I searched how to use custom function inside a model. I found 2 ways : using as_op or a black box. I did not find other ways (maybe I did not look enough). Currently, I’m trying to update my tool with pymc6 and I did not check if there are new possibilities.

I will try with CustomOp. I think it will answer my problem (calibration of experimental data knowing their uncertainties using custom model). I’ve found an example using a web research. I will test it in a day or two.

Just for me : do you know where I can find a complete example (with random function) of a customDist so that I can compare and understand why my version is broken?

Thanks again.

Without knowing the actual problem you want to solve, it’s hard to give concrete advice. What you’re doing is essentially the worst-case fallback, when you cannot write your generative graph using pytensor. If I could see what you are actually trying to do, I could give more tailored advice on how to proceed.

The specific problem you are having, though, is because your random function has incorrect shapes, leading to a weird memory access bug.

pm.sample_posterior_predictive calls the random function with inputs (tp, sigma), where tp has shape (3,), and with size=(50,), taken from the observed data. You are looping over the 3 parameters in tp and drawing normals around each one, giving an array noise with shape (3, 50). There’s no shape validation, so when this gets passed to numba, it reads it as shape 3 with a stride of 50 bytes. So you get back a posterior of (4, 3000, 3) instead of (4, 3000, 50) and with random garbage memory in the array (from the 50-byte stride).

If you use a different backend you’ll get a non-nan answer but still with the wrong shape. You want to draw noise around the mean:

def random(para, sigma, rng=None, size=None):
    return rng.normal(loc=fonctest0(tx, para), scale=sigma, size=size)

To Ricardo’s point, if your function is just a black-box mean with Gaussian noise, you can skip the CustomDist and just use a pytensor Op:

@pytensor.wrap_py(itypes=[pt.dvector], otypes=[pt.dmatrix])
def black_box_jacobian(para):
    return approx_fprime(para, lambda p: fonctest0(tx, p), 1e-7)


class BlackBoxMean(Op):
    itypes = [pt.dvector]
    otypes = [pt.dvector]

    def perform(self, node, inputs, outputs):
        [para] = inputs
        outputs[0][0] = fonctest0(tx, para)

    def pullback(self, inputs, outputs, cotangents):
        [para] = inputs
        [mean_cotangent] = cotangents
        return [mean_cotangent @ black_box_jacobian(para)]


mean_op = BlackBoxMean()

with pm.Model() as black_box_model:
    para = pm.Uniform("para", lower=-10., upper=10., shape=len(para0))
    pm.Normal("likelihood", mu=mean_op(para), sigma=sigma, observed=ty)

    idata_black_box = pm.sample(random_seed=1)
    posterior_predictive_black_box = pm.sample_posterior_predictive(idata_black_box, random_seed=1)

Results:

black_box_draws = posterior_predictive_black_box['posterior_predictive']['likelihood'].data
print("posterior means:", idata_black_box.posterior['para'].mean(dim=['chain', 'draw']).values)
print("ppc draws shape:", black_box_draws.shape, "| NaN count:", int(np.isnan(black_box_draws).sum()))
print("max draw:", black_box_draws.max(), "| max observed:", ty.max())

# posterior means: [0.99965329 2.00320243 3.00793135]
# ppc draws shape: (4, 1000, 50) | NaN count: 0
# max draw: 123.39558869838716 | max observed: 122.9311170578055

Also most times you don’t need a custom function, if you can write it with numpy code, you can write it with pytensor

Thanks for your answer.

Indeed, my random function wasn’t well designed : I tried to create it from the examples and I misunderstand them : I was thinking that the purpose of this function was to compute random parameter (here size 3) for the external function and not random values of the function (size 50).

The solution you propose using pytensor Op is simpler and, I think, it will answer my problem.

I’ve build and maintained a toolbox for several users. Its aim is to process some experimental data (drawing, comparison, sensitivity, model, …). One of the function of this toolbox is to run calibrations to determine the posterior distribution of parameters (the choice of the prior of each parameter is given by the user).

I used several physical models: most of them are simple and can easily be write with pytensor but some of them are given by external libraries. That’s why I need to use black box or pytensor Op.

Thanks again