"""
JAX transpilation helpers for pyhs3.
Provides :func:`~pyhs3.jaxify` and :class:`JaxifiedGraph` for converting any PyTensor
expression into a callable JAX function suitable for use with JAX-based
optimizers (e.g. ``optimistix``).
Requires the ``jax`` optional extra::
pip install pyhs3[jax]
which pulls in ``pytensor[jax]`` and, transitively, JAX itself.
The callable :func:`~pyhs3.jaxify` returns is not jitted. Wrap it in ``jax.jit`` for
any repeated evaluation; see :class:`JaxifiedGraph`.
"""
from __future__ import annotations
from collections import Counter
from collections.abc import Callable, Sequence
from dataclasses import dataclass, field
from typing import cast
from pytensor.compile import mode as _ptmode
from pytensor.graph.fg import FunctionGraph
from pytensor.graph.traversal import explicit_graph_inputs
from pyhs3.typing.aliases import TensorVar
# ---------------------------------------------------------------------------
# Public API
# ---------------------------------------------------------------------------
[docs]
@dataclass(frozen=True)
class JaxifiedGraph:
"""A JAX-callable wrapper around a compiled PyTensor expression.
Produced by :func:`~pyhs3.jaxify`. Supports keyword-argument calls (the primary
interface for dict-pytree-based optimizers like optimistix or everwillow)
and positional calls via :meth:`call_positional`.
Calling a ``JaxifiedGraph`` does not jit it: JAX runs the graph eagerly,
one operation at a time, which on a large likelihood is orders of
magnitude slower than the same call wrapped in ``jax.jit``. Wrap it for
any repeated evaluation::
jg = jaxify(model.log_prob)
nll = jax.jit(lambda params: -jg(**params)[0])
For a likelihood evaluated repeatedly without JAX,
:meth:`pyhs3.Model.compile_nll` compiles it for you.
Attributes:
inputs: Tuple of PyTensor input variables, in evaluation order.
input_names: Names of those variables (same order as ``inputs``).
fn: The raw JAX callable returned by ``jax_funcify``.
"""
inputs: tuple[TensorVar, ...]
input_names: tuple[str, ...]
fn: Callable[..., tuple] # type: ignore[type-arg]
_expected_names: frozenset[str] = field(init=False, repr=False, compare=False)
def __post_init__(self) -> None:
# Built once so that validating the keywords of a call is a set
# comparison, not a rebuild of the expected names.
object.__setattr__(self, "_expected_names", frozenset(self.input_names))
def __call__(self, **kwargs: object) -> object:
"""Call by original PyTensor input name.
This call is not jitted; wrap it in ``jax.jit`` for repeated use (see
:class:`JaxifiedGraph`).
``jax_funcify`` generates a function whose parameter names are
sanitized versions of the PyTensor variable names (for example,
consecutive underscores are collapsed), so forwarding kwargs by name
fails for some valid names. The kwargs are instead reordered into the
declared positional order of :attr:`input_names`. A ``TypeError``
lists any missing or unexpected names.
The typical usage pattern with optimistix or everwillow is to jaxify
the log-space graph directly (e.g. ``model.log_prob``) rather than
jaxifying a probability-space pdf and taking ``jnp.log`` of the
result — the latter underflows to ``-inf`` for realistic HistFactory
channels, where the probability-space product can be smaller than
the smallest representable float::
jg = jaxify(model.log_prob)
@jax.jit
def nll(free_params): # free_params is a dict pytree
all_params = {**free_params, **fixed_params}
return -2 * jg(**all_params)[0]
Parameters
----------
**kwargs:
One value per input name, as JAX arrays or Python scalars.
Returns
-------
Whatever :attr:`fn` returns (typically a 1-tuple of JAX arrays).
"""
received = kwargs.keys()
if received != self._expected_names:
details = []
if missing := sorted(self._expected_names - received):
details.append(f"missing {missing}")
if unexpected := sorted(received - self._expected_names):
details.append(f"unexpected {unexpected}")
msg = "Invalid JAX graph inputs: " + ", ".join(details)
raise TypeError(msg)
return self.fn(*(kwargs[name] for name in self.input_names))
[docs]
def call_positional(self, *args: object) -> object:
"""Call with positional arguments — pure passthrough to :attr:`fn`.
Like calling the graph, this is not jitted; wrap it in ``jax.jit`` for
repeated use.
Parameters
----------
*args:
Values in the same order as ``self.input_names``.
Returns
-------
Whatever :attr:`fn` returns (typically a 1-tuple of JAX arrays).
"""
return self.fn(*args)
[docs]
def jaxify(
output: TensorVar,
*,
inputs: Sequence[TensorVar] | None = None,
) -> JaxifiedGraph:
"""Convert a PyTensor expression into a JAX-callable :class:`JaxifiedGraph`.
The returned callable is not jitted: calling it runs JAX eagerly, one
operation at a time, which on a large likelihood is orders of magnitude
slower than the same call wrapped in ``jax.jit``. Jit it for repeated
calls::
jg = jaxify(model.log_prob)
nll = jax.jit(lambda params: -jg(**params)[0])
Parameters
----------
output:
The PyTensor output variable to compile.
inputs:
Explicit list of input variables. If ``None``, the full set of
graph inputs (variables with no owner, i.e. symbolic parameters) is
discovered automatically via ``explicit_graph_inputs``.
Returns
-------
JaxifiedGraph
Wrapper exposing the compiled JAX function plus input metadata.
Examples
--------
>>> import math
>>> import pytensor.tensor as pt
>>> x = pt.scalar("x")
>>> mu = pt.scalar("mu")
>>> sigma = pt.scalar("sigma")
>>> pdf = pt.exp(-0.5 * ((x - mu) / sigma) ** 2) / (
... sigma * pt.sqrt(pt.constant(2 * math.pi, dtype="float64"))
... )
>>> from pyhs3.transpile import jaxify
>>> jg = jaxify(pdf)
>>> float(jg(x=0.0, mu=0.0, sigma=1.0)[0])
0.3989422804014327
"""
try:
from pytensor.link.jax.dispatch.basic import jax_funcify # noqa: PLC0415
except ImportError as exc:
msg = "pyhs3.transpile requires JAX. Install with `pip install pyhs3[jax]`."
raise ImportError(msg) from exc
if inputs is None:
# Filter out unnamed nodes (constants, shared vars without explicit names)
# so that every entry in input_names is a non-None string.
inputs = cast(
list[TensorVar],
[v for v in explicit_graph_inputs([output]) if v.name is not None],
)
named_inputs: tuple[TensorVar, ...] = tuple(inputs)
raw_names = tuple(v.name for v in named_inputs)
if any(name is None for name in raw_names):
msg = (
"All inputs must be named for kwargs-based dispatch. "
"Provide named TensorVariables or use call_positional()."
)
raise ValueError(msg)
names: tuple[str, ...] = tuple(cast(str, name) for name in raw_names)
duplicates = sorted(name for name, n in Counter(names).items() if n > 1)
if duplicates:
msg = f"Input names must be unique; duplicates found: {duplicates}"
raise ValueError(msg)
fgraph = FunctionGraph(inputs=list(inputs), outputs=[output], clone=True)
_ptmode.JAX.optimizer.rewrite(fgraph)
fn = jax_funcify(fgraph)
return JaxifiedGraph(named_inputs, names, fn)