Skip to content

Commit b7eceb4

Browse files
made TODOs more verbose
1 parent e7b22ac commit b7eceb4

File tree

2 files changed

+80
-31
lines changed

2 files changed

+80
-31
lines changed

pymc_extras/inference/laplace.py

Lines changed: 79 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@
3939
from pymc.model.transform.conditioning import remove_value_transforms
4040
from pymc.model.transform.optimization import freeze_dims_and_data
4141
from pymc.util import get_default_varnames
42-
from pytensor.tensor import TensorVariable
42+
from pytensor.tensor import TensorLike, TensorVariable
4343
from pytensor.tensor.optimize import minimize
4444
from scipy import stats
4545

@@ -420,28 +420,60 @@ def sample_laplace_posterior(
420420
def find_mode(
421421
x: TensorVariable,
422422
args: dict,
423-
inputs: list[TensorVariable] | None = None,
424-
x0: TensorVariable
425-
| None = None, # TODO This isn't a TensorVariable, not sure what the general datatype for numeric arraylikes is
423+
x0: TensorLike | None = None,
426424
model: pm.Model | None = None,
427425
method: minimize_method = "BFGS",
428426
use_jac: bool = True,
429-
use_hess: bool = False,
427+
use_hess: bool = False, # TODO Tbh we can probably just remove this arg and pass True to the minimizer all the time, but if this is the case, it will throw a warning when the hessian doesn't need to be computed for a particular optimisation routine.
430428
optimizer_kwargs: dict | None = None,
431-
): # TODO Output type is list of same type as x0
429+
) -> list[TensorLike]:
430+
"""
431+
Estimates the mode and hessian of a model by minimizing negative log likelihood. Wrapper for (pytensor-native) scipy.optimize.minimize.
432+
433+
Parameters
434+
----------
435+
x: TensorVariable
436+
The parameter with which to minimize wrt (that is, find the mode in x).
437+
args: dict
438+
A dictionary of the form {tensorvariable_name: TensorLike}, where tensorvariable_name is the (exact) name of TensorVariable which is to be provided some numerical value. Same usage as args in scipy.optimize.minimize.
439+
x0: TensorLike
440+
Initial guess for the mode (in x). Initialised over a uniform distribution if unspecified.
441+
model: Model
442+
PyMC model to use.
443+
method: minimize_method
444+
Which minimization algorithm to use.
445+
use_jac: bool
446+
If true, the minimizer will compute and store the Jacobian.
447+
use_hess: bool
448+
If true, the minimizer will compute and store the Hessian (note that the Hessian will be computed explicitely even if this is False).
449+
optimizer_kwargs: dict
450+
Kwargs to pass to scipy.optimize.minimize.
451+
452+
Returns
453+
-------
454+
mu: TensorLike
455+
The mode of the model.
456+
hess:
457+
Hessian evalulated at mu.
458+
"""
432459
model = pm.modelcontext(model)
433460

434-
# if x0 is None:
435-
# #TODO Issue with X not being an RV
436-
# print(model.initial_point())
461+
# # TODO I would like to generate a random initialisation for x0 if set to None. Ideally this would be done using something like np.random.rand(x.shape), however I don't believe x.shape is
462+
# # immediately accessible in pytensor. model.initial_point() throws the following error:
463+
464+
# # MissingInputError: Input 0 (X) of the graph (indices start from 0), used to compute Transpose{axes=[1, 0]}(X), was not provided and not given a value. Use the PyTensor flag exception_verbosity='high', for more information on this error.
437465

466+
# # Instead I've tried to follow what find_MAP does (below), but this doesn't really get me anywhere unfortunately.
467+
# # if x0 is None:
468+
# # Yes ik this is here, just for debugging purposes
438469
# from pymc.initial_point import make_initial_point_fn
470+
439471
# frozen_model = freeze_dims_and_data(model)
440472
# ipfn = make_initial_point_fn(
441-
# model=model,
442-
# jitter_rvs=set(),#(jitter_rvs),
473+
# model=frozen_model,
474+
# jitter_rvs=set(), # (jitter_rvs),
443475
# return_transformed=True,
444-
# overrides=args,
476+
# overrides={x.name: x0}, # x0 is here for debugging purposes
445477
# )
446478

447479
# random_seed = None
@@ -450,6 +482,7 @@ def find_mode(
450482
# initial_params = DictToArrayBijection.map(
451483
# {var_name: value for var_name, value in start_dict.items() if var_name in vars_dict}
452484
# )
485+
# # Printing this should return {'name of x TensorVariable': initialised values for x}
453486
# print(initial_params)
454487

455488
# Minimise negative log likelihood
@@ -463,30 +496,46 @@ def find_mode(
463496
optimizer_kwargs=optimizer_kwargs,
464497
)
465498

466-
# Get input variables
467-
# TODO issue when this is nll
468-
if inputs is None:
469-
inputs = [
470-
pytensor.graph.basic.get_var_by_name(model.basic_RVs[1], target_var_id=var)[0]
471-
for var in args
472-
]
473-
for i, var in enumerate(inputs):
474-
try:
475-
inputs[i] = model.rvs_to_values[var]
476-
except KeyError:
477-
pass
478-
inputs.insert(0, x)
499+
# TODO To prevent needing to user to pass in the TensorVariables alongside their names (e.g. args = {'X': [X, [0,0]], 'beta': [beta_val, [1]], ...}) the codeblock below digs up the
500+
# TensorVariables associated with the names listed in args from the graph. The sensible graph to use here would be nll, because that is what is going into the minimize function, however doing
501+
# so results in the following error:
502+
#
503+
# TypeError: TensorType does not support iteration.
504+
# Did you pass a PyTensor variable to a function that expects a list?
505+
# Maybe you are using builtins.sum instead of pytensor.tensor.sum?
506+
#
507+
# Using model.basic_RVs[1] instead works, but note that this is a hardcoded fix because the model I'm testing on happens to have all of the relevant TensorVariables in the graph of model.basic_RVs[1],
508+
# but this isn't true in general.
509+
510+
# Get arg TensorVariables
511+
arg_tensorvars = [
512+
pytensor.graph.basic.get_var_by_name(model.basic_RVs[1], target_var_id=var)[0]
513+
# pytensor.graph.basic.get_var_by_name(nll, target_var_id=var)[0]
514+
for var in args
515+
]
516+
for i, var in enumerate(arg_tensorvars):
517+
try:
518+
arg_tensorvars[i] = model.rvs_to_values[var]
519+
except KeyError:
520+
pass
521+
arg_tensorvars.insert(0, x)
522+
523+
# TODO: Jesse suggested I use this graph_replace function, but it seems that "mode" here is a different type to soln:
524+
#
525+
# TypeError: Cannot convert Type Vector(float64, shape=(10,)) (of Variable MinimizeOp(method=BFGS, jac=True, hess=True, hessp=False).0) into Type Scalar(float64, shape=()). You can try to manually convert MinimizeOp(method=BFGS, jac=True, hess=True, hessp=False).0 into a Scalar(float64, shape=()).
526+
#
527+
# My understanding here is that for some function which evaluates the hessian at x, we're replacing "x" in the hess graph with the subgraph that computes "x" (i.e. soln)?
479528

480529
# Obtain the Hessian (re-use graph if already computed in minimize)
481530
if use_hess:
482-
hess = soln.owner.op.inner_outputs[-1]
483-
hess = pytensor.graph.replace.graph_replace(
484-
hess, {x: soln}
485-
) # TODO: x here is 'beta', soln is a MinimizeOp. There's no instance of MinimizeOp in the hessian graph
531+
mode, _, hess = (
532+
soln.owner.op.inner_outputs
533+
) # Note that this mode, _, hess will need to be slightly more elaborate for when use_jac is False (2 items to unpack instead of 3). Just a few if-blocks, but not implemented for now while we're debugging
534+
hess = pytensor.graph.replace.graph_replace(hess, {mode: soln})
486535
else:
487536
hess = pytensor.gradient.hessian(nll, x)
488537

489-
get_mode_and_hessian = pytensor.function(inputs, [soln, hess])
538+
get_mode_and_hessian = pytensor.function(arg_tensorvars, [soln, hess])
490539
return get_mode_and_hessian(x0, **args)
491540

492541

tests/test_laplace.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -289,7 +289,7 @@ def test_find_mode():
289289
y = pt.vector("y", dtype="int64")
290290
X = pt.matrix("X", shape=(N, k))
291291

292-
# Pre-commit did this. Quite ugly. Should compute hess in code rather than storing a hardcoded array.
292+
# TODO Pre-commit formatted it like this. Quite ugly. Should compute hess in code rather than storing a hardcoded array.
293293
true_hess = np.array(
294294
[
295295
[

0 commit comments

Comments
 (0)