Structural assumptions and assumption-driven rewrites#

PyTensor can track structural properties of symbolic tensors (that a matrix is diagonal, triangular, symmetric, positive-definite, orthogonal, a permutation, and so on) and let graph rewrites use those properties to produce faster compiled functions.

This is a compiler analysis, not a computer-algebra system. The goal is not to prove theorems, but to let a rewrite replace an expensive operation (a general solve, a dense matmul, a Kronecker product) with a cheaper specialized one, without inserting any runtime checks. Facts are attached to (variable, property) pairs inside a FunctionGraph, inference is lazy and cached, and an answer of unknown is both common and legitimate.

A fact is declared with a single function, assume(). Propagation, implication, and the rewrites that consume the facts then follow automatically.

import numpy as np

import pytensor.tensor as pt
from pytensor import dprint, function

from pytensor.assumptions import (
    ALL_KEYS,
    DIAGONAL,
    IMPLIES,
    LOWER_TRIANGULAR,
    ORTHOGONAL,
    POSITIVE_DEFINITE,
    SYMMETRIC,
    UPPER_TRIANGULAR,
    AssumptionFeature,
    ConflictingAssumptionsError,
    FactState,
    assume,
)
from pytensor.graph.fg import FunctionGraph


def facts(var, *keys):
    """Read the facts the system infers about ``var``.

    Attach an ``AssumptionFeature`` to a throwaway ``FunctionGraph`` and return a
    ``{name: FactState}`` mapping. With no keys, report every registered property.
    """
    fg = FunctionGraph(outputs=[var], clone=False)
    feature = AssumptionFeature()
    fg.attach_feature(feature)
    keys = keys or ALL_KEYS
    return {key.name: feature.get(var, key) for key in keys}

Declaring an assumption#

assume() attaches one or more structural assumptions to a tensor. Each keyword is True (assert the property holds), False (assert it does not hold), or omitted (say nothing).

x = pt.matrix("x", shape=(3, 3))
x_diag = assume(x, diagonal=True)

dprint(x_diag, print_assumptions=True);
SpecifyAssumptions{diagonal} [id A] a={diag}
 └─ x [id B]
f = function([x], x_diag)
value = np.arange(9.0).reshape(3, 3)

# assume() is a no-op at runtime: the output is exactly the input.
np.allclose(f(value), value)
True

The output is identical to x at runtime. assume() wraps the input in a SpecifyAssumptions node, a no-op view that carries the declared facts and passes gradients through unchanged. Keeping the assumption in the graph means it survives cloning; a later rewrite drains these markers into the graph’s fact cache and removes them.

debugprint(), imported here as dprint, prints what the system knows about each node as an a={...} tag, here a={diag}.

Three-valued logic#

Assumptions use three-valued logic. A fact about a (variable, property) pair is one of:

FactState

meaning

TRUE

the property provably holds

FALSE

the property provably does not hold

UNKNOWN

the system cannot decide (the default, and very common)

CONFLICT

contradictory evidence, always an error

You rarely construct these yourself. To read the facts the system infers about a variable, attach an AssumptionFeature to a graph and call .get (three-valued) or .check (collapses to a plain bool, True only for TRUE). The facts helper defined above does exactly this.

facts(x_diag, DIAGONAL, SYMMETRIC, POSITIVE_DEFINITE, ORTHOGONAL)
{'diagonal': <FactState.TRUE: 1>,
 'symmetric': <FactState.TRUE: 1>,
 'positive_definite': <FactState.UNKNOWN: 0>,
 'orthogonal': <FactState.UNKNOWN: 0>}

The distinction between UNKNOWN and FALSE matters here. The system cannot determine whether a diagonal matrix is positive-definite (a diagonal matrix may or may not be), so it reports UNKNOWN, not FALSE. .check() collapses both to Python False, so use .get() when the distinction is relevant.

We asserted only diagonal=True, yet symmetric is reported TRUE. That follows from the implication system, described next.

Implications: assert the strongest fact#

Properties are connected by a small, explicit implication lattice. A diagonal matrix is symmetric and both-triangular; a positive-definite matrix is symmetric; a permutation matrix is orthogonal and a selection matrix. The IMPLIES registry holds these edges:

for stronger, weaker in IMPLIES.items():
    print(f"{stronger.name:18s} => {', '.join(w.name for w in weaker)}")
diagonal           => lower_triangular, upper_triangular, symmetric
positive_definite  => symmetric
permutation        => selection, orthogonal
# A single diagonal=True assertion answers all four of these as TRUE.
facts(x_diag, DIAGONAL, SYMMETRIC, LOWER_TRIANGULAR, UPPER_TRIANGULAR)
{'diagonal': <FactState.TRUE: 1>,
 'symmetric': <FactState.TRUE: 1>,
 'lower_triangular': <FactState.TRUE: 1>,
 'upper_triangular': <FactState.TRUE: 1>}

Implication runs in both directions: forward (a stronger TRUE makes the weaker facts TRUE) and contrapositive (a weaker FALSE makes the stronger fact FALSE; a matrix that is not symmetric cannot be diagonal). In practice, assert only the strongest property you know and let the weaker ones follow.

Conflicts are caught#

Because assume(..., property=False) records genuine FALSE evidence, asserting something the system can prove wrong produces a CONFLICT, raised as a ConflictingAssumptionsError the moment the fact is queried. For example, pt.eye(5) is provably diagonal, so asserting that it is not:

contradiction = assume(pt.eye(5), diagonal=False)

try:
    facts(contradiction, DIAGONAL)
except ConflictingAssumptionsError as err:
    print("ConflictingAssumptionsError:", err)
ConflictingAssumptionsError: Conflicting evidence for diagonal on SpecifyAssumptions{!diagonal}.0 from owner-inferred rules.

Facts propagate through the graph#

You annotate the inputs, not every intermediate result, and the system carries properties forward. Inference walks the graph inputs-first, and each operation has rules describing what it does to a property: the cholesky() factor of a diagonal matrix is diagonal, a transpose swaps lower- and upper-triangular, and the product of two diagonals is diagonal. Constants are inspected directly, so a literal identity matrix is recognized as diagonal, orthogonal, and a permutation.

Here the diagonal fact flows from A through cholesky to L with no annotation on L itself:

A = assume(pt.matrix("A", shape=(3, 3)), diagonal=True)
L = pt.linalg.cholesky(A)

dprint(L, print_assumptions=True);
Blockwise{Cholesky{lower=True, overwrite_a=False}, (m,m)->(m,m)} [id A] a={diag}
 └─ SpecifyAssumptions{diagonal} [id B] a={diag}
    └─ A [id C]
# Transposing swaps lower- and upper-triangular.
U = assume(pt.matrix("U", shape=(3, 3)), upper_triangular=True)

print(f"{'U':<5}{facts(U, LOWER_TRIANGULAR, UPPER_TRIANGULAR)}")
print(f"{'U.T':<5}{facts(U.T, LOWER_TRIANGULAR, UPPER_TRIANGULAR)}")
U    {'lower_triangular': <FactState.UNKNOWN: 0>, 'upper_triangular': <FactState.TRUE: 1>}
U.T  {'lower_triangular': <FactState.TRUE: 1>, 'upper_triangular': <FactState.UNKNOWN: 0>}

Rewrites that consume assumptions#

The preceding machinery exists to enable rewrites. Compiling a function with mode="FAST_RUN" runs rewrites that query the fact cache and specialize the graph; the SpecifyAssumptions markers are removed in the process. Each of the four examples below produces a compiled graph in which an expensive operation has been eliminated.

Diagonal matmul becomes an elementwise product#

A general matrix multiply is \(O(n^3)\). If both operands are diagonal, the product is diagonal and reduces to the elementwise product of the two diagonals. No Matmul remains in the compiled graph.

d1 = pt.matrix("d1", shape=(3, 3))
d2 = pt.matrix("d2", shape=(3, 3))
product = assume(d1, diagonal=True) @ assume(d2, diagonal=True)

f_product = function([d1, d2], product, mode="FAST_RUN")
dprint(f_product);
FusedElemwise{Mul} [id A] 3
 ├─ ExtractDiag{offset=0, axis1=0, axis2=1, view=True} [id B] 2
 │  └─ d1 [id C]
 ├─ ExtractDiag{offset=0, axis1=0, axis2=1, view=True} [id D] 1
 │  └─ d2 [id E]
 ├─ [0 1 2] [id F]
 ├─ [0 1 2] [id F]
 └─ Alloc [id G] 0
    ├─ 0.0 [id H]
    ├─ 3 [id I]
    └─ 3 [id I]

Inner graphs:

FusedElemwise{Mul} [id A]
 ← AdvancedSetSubtensor [id J]
    ├─ i4 [id K]
    ├─ Mul [id L]
    │  ├─ i0 [id M]
    │  └─ i1 [id N]
    ├─ i3 [id O]
    └─ i3 [id O]

Orthogonal \(Q Q^\top \to I\)#

For an orthogonal matrix, \(Q Q^\top\) is the identity. The product reduces to a constant, and the multiply is removed entirely.

q = pt.matrix("q", shape=(3, 3))
q_orth = assume(q, orthogonal=True)
gram = q_orth @ q_orth.T

f_gram = function([q], gram, mode="FAST_RUN")
dprint(f_gram);
DeepCopyOp [id A] 0
 └─ [[1. 0. 0. ... 0. 0. 1.]] [id B]

Positive-definite solve becomes a Cholesky solve#

solve() for a general A uses an LU-based solver. If A is positive-definite, a Cholesky-based solver is roughly twice as fast and more numerically stable. The assumption selects the specialized path, visible as assume_a='pos' on the compiled Solve.

A_pd = pt.matrix("A_pd", shape=(3, 3))
b = pt.vector("b", shape=(3,))
solution = pt.linalg.solve(assume(A_pd, positive_definite=True), b)

f_solve = function([A_pd, b], solution, mode="FAST_RUN")
dprint(f_solve);
Solve{assume_a='pos', lower=False, b_ndim=1, overwrite_a=False, overwrite_b=False} [id A] 0
 ├─ A_pd [id B]
 └─ b [id C]

Kronecker product of diagonals#

The kron() product of two diagonal matrices is itself diagonal, so the dense KroneckerProduct op is replaced by a construction from the outer product of the two diagonals. No KroneckerProduct remains in the compiled graph.

k1 = pt.matrix("k1", shape=(3, 3))
k2 = pt.matrix("k2", shape=(4, 4))
kron = pt.linalg.kron(assume(k1, diagonal=True), assume(k2, diagonal=True))

f_kron = function([k1, k2], kron, mode="FAST_RUN")
dprint(f_kron);
AdvancedSetSubtensor [id A] 7
 ├─ Alloc [id B] 6
 │  ├─ 0.0 [id C]
 │  ├─ 12 [id D]
 │  └─ 12 [id D]
 ├─ Reshape{1} [id E] 5
 │  ├─ Mul [id F] 4
 │  │  ├─ ExpandDims{axis=1} [id G] 3
 │  │  │  └─ ExtractDiag{offset=0, axis1=0, axis2=1, view=True} [id H] 2
 │  │  │     └─ k1 [id I]
 │  │  └─ ExpandDims{axis=0} [id J] 1
 │  │     └─ ExtractDiag{offset=0, axis1=0, axis2=1, view=True} [id K] 0
 │  │        └─ k2 [id L]
 │  └─ [-1] [id M]
 ├─ [ 0  1  2 ... 9 10 11] [id N]
 └─ [ 0  1  2 ... 9 10 11] [id N]

Worked example: a Gaussian process marginal likelihood#

Gaussian process regression is a natural setting for structural assumptions, because its central object is a covariance matrix that is symmetric and positive-definite by construction.

For inputs \(X\), targets \(y\), a kernel \(k\), and observation noise \(\sigma^2\), the training covariance is

\[K = k(X, X) + \sigma^2 I,\]

which is symmetric positive-definite. The log marginal likelihood is

\[\log p(y \mid X) = -\tfrac{1}{2}\left(y^\top K^{-1} y + \log|K| + n \log 2\pi\right),\]

and a direct translation writes \(K^{-1}\) as inv(K) and \(\log|K|\) as slogdet(K). This is the pattern GP libraries built on PyTensor use: a kernel annotates every covariance \(k(X, X)\) as symmetric and positive-definite when it is constructed, the likelihood and posterior code is written in this naive form, and the assumption system specializes it.

def linalg_op_counts(fn):
    """Count the linear-algebra ops remaining in a compiled function."""
    keep = ("Cholesky", "Solve", "MatrixInverse", "SLogDet", "Det", "LU")
    counts = {}
    for node in fn.maker.fgraph.apply_nodes:
        name = type(node.op).__name__
        if any(k in name for k in keep):
            counts[name] = counts.get(name, 0) + 1
    return counts
def exp_quad_cov(X, ls):
    """Squared-exponential (RBF) covariance k(X, X)."""
    sq_dist = ((X[:, None, :] - X[None, :, :]) ** 2).sum(-1)
    return pt.exp(-0.5 * sq_dist / ls**2)


X = pt.matrix("X")
y = pt.vector("y")
ls = pt.scalar("ls")
sigma = pt.scalar("sigma")
n = X.shape[0]

K = exp_quad_cov(X, ls) + sigma**2 * pt.eye(n)
def marginal_log_likelihood(cov):
    quad = y @ pt.linalg.inv(cov) @ y  # y^T K^-1 y
    _, logdet = pt.linalg.slogdet(cov)  # log|K|
    return -0.5 * (quad + logdet + n * np.log(2 * np.pi))

Compiled from the plain covariance K, the linear algebra falls back to general routines. PyTensor already avoids forming an explicit inverse, but nothing tells it that K is symmetric or positive-definite, so the solve and the log-determinant become two independent general (LU-based) factorizations:

f_plain = function([X, y, ls, sigma], marginal_log_likelihood(K), mode="FAST_RUN")
linalg_op_counts(f_plain)
{'SLogDet': 1, 'Solve': 1}

Now assert what a GP library knows at construction time: the covariance is symmetric and positive-definite. This is a single call, exactly the annotation a kernel attaches to k(X, X):

K_pd = assume(K, positive_definite=True, symmetric=True)

f_pd = function([X, y, ls, sigma], marginal_log_likelihood(K_pd), mode="FAST_RUN")
linalg_op_counts(f_pd)
{'CholeskySolve': 1, 'Cholesky': 1}

The two general factorizations collapse to a single Cholesky. Both the inverse-solve (CholeskySolve) and the log-determinant reuse that one factor \(L\): since \(K = L L^\top\), the term \(K^{-1} y\) is obtained by triangular solves and \(\log|K| = 2\sum_i \log L_{ii}\). A Cholesky factorization costs about half an LU factorization and is better conditioned for positive-definite matrices, so the assumption improves both speed and numerical stability.

rng = np.random.default_rng(0)
X_val = rng.normal(size=(6, 1))
y_val = rng.normal(size=6)

# Same value, different graph.
f_plain(X_val, y_val, 1.0, 0.5), f_pd(X_val, y_val, 1.0, 0.5)
(array(-13.35336976), array(-13.35336976))

Fitting requires the gradient#

Fitting a GP means optimizing the kernel hyperparameters, which needs the gradient of the marginal likelihood. Taking that gradient and inspecting the compiled graph shows the specialization is not yet complete:

loss = marginal_log_likelihood(K_pd)
grad_ls, grad_sigma = pt.grad(loss, [ls, sigma])

f_grad = function([X, y, ls, sigma], [loss, grad_ls, grad_sigma], mode="FAST_RUN")
linalg_op_counts(f_grad)
{'CholeskySolve': 3, 'MatrixInverse': 1, 'Cholesky': 1}

A MatrixInverse survives. Differentiating \(\log|K|\) produces a standalone \(K^{-1}\), and PyTensor turns an inverse into a solve only when it sits next to a matmul; a bare inverse of a matrix it cannot otherwise tell is positive-definite is left as a general MatrixInverse.

The assumption is still available (check_assumption() returns True for that matrix), so a small rewrite closes the gap. When the inverse is applied to a positive-definite matrix, factor it once and solve with cho_solve():

\[A^{-1} = (L L^\top)^{-1}, \qquad L = \operatorname{chol}(A).\]

inv() batches its input, so the op to match is Blockwise(MatrixInverse), spelled blockwise_of(MatrixInverse):

The next cell is not idempotent: register_specialize adds to a global rewrite database, so f_grad above is the “before” graph only because it was compiled first. Re-running that earlier cell now would compile it with the rewrite applied.

from pytensor.graph.rewriting.basic import node_rewriter
from pytensor.tensor.rewriting.basic import register_specialize
from pytensor.tensor.rewriting.blockwise import blockwise_of
from pytensor.tensor.linalg import MatrixInverse, cholesky, cho_solve
from pytensor.assumptions import check_assumption


@register_specialize
@node_rewriter([blockwise_of(MatrixInverse)])
def inv_of_psd_to_cho_solve(fgraph, node):
    """Replace inv(A) with a Cholesky solve when A is known positive-definite."""
    [A] = node.inputs
    if not check_assumption(fgraph, A, POSITIVE_DEFINITE):
        return None
    L = cholesky(A, lower=True)
    identity = pt.eye(A.shape[-1], dtype=A.dtype)
    return [cho_solve((L, True), identity)]
f_grad_fast = function([X, y, ls, sigma], [loss, grad_ls, grad_sigma], mode="FAST_RUN")

assert np.allclose(
    f_grad(X_val, y_val, 1.0, 0.5),
    f_grad_fast(X_val, y_val, 1.0, 0.5),
)

linalg_op_counts(f_grad_fast)
{'CholeskySolve': 4, 'Cholesky': 1}

The MatrixInverse is gone, and the count still shows a single Cholesky: the factor introduced by the rewrite merges with the one already built for the forward pass, so the whole loss-and-gradient graph shares one factorization. The gradient values are unchanged.

This rewrite is exactly what a GP library ships. In ptgp, for example, it is registered once as matrix_inverse_specialize, alongside companions that lower \(\det(L L^\top)\) and \(\operatorname{diag}(A A^\top)\), so a full marginal-likelihood-and-gradient graph compiles to a single Cholesky and no explicit inverse.

Extending the system#

Constructing an AssumptionKey registers it. From that point the property is a first-class citizen: assume() accepts it by name, dprint(..., print_assumptions=True) reports it, and the rewrite that drains declarations into the fact cache resolves it. Nothing else has to be wired up.

What remains is to say how the property behaves:

  • register_assumption(): a decorator registering a per-operation inference rule. A rule receives (key, op, feature, fgraph, node, input_states) and returns one FactState per output. Pass prepend=True to run ahead of rules already registered for the same pair.

  • register_matrix_property_rules(): install the standard rules for a property of the trailing two axes, so a new matrix property survives transposes, reshapes, indexing and broadcasting without writing any of them.

  • register_implies(): add edges to the implication lattice.

  • register_constant_inference(): infer a fact from the data of a literal constant.

The example below defines an INVERTIBLE property, registers that any identity matrix (Eye) is invertible, and records that positive-definiteness implies invertibility.

from pytensor.assumptions import AssumptionKey, register_assumption, register_implies
from pytensor.tensor.basic import Eye

INVERTIBLE = AssumptionKey("invertible", "inv")


@register_assumption(INVERTIBLE, Eye)
def _eye_is_invertible(key, op, feature, fgraph, node, input_states):
    return [FactState.TRUE]


# A positive-definite matrix is always invertible.
register_implies(POSITIVE_DEFINITE, INVERTIBLE)

pos_def = assume(pt.matrix("m", shape=(3, 3)), positive_definite=True)

# ``eye`` is invertible by the rule above; ``pos_def`` follows from the implication.
print(f"{'eye':<10}{facts(pt.eye(4), INVERTIBLE)}")
print(f"{'pos_def':<10}{facts(pos_def, INVERTIBLE)}")
eye       {'invertible': <FactState.TRUE: 1>}
pos_def   {'invertible': <FactState.TRUE: 1>}

Because the key registered itself, assume() takes invertible=True alongside the built-in keywords, and the key can declare and query the fact directly:

m = pt.matrix("m2", shape=(3, 3))

# The first two are the same declaration written two ways; the third is the control.
declarations = {
    "assume(m, invertible=True)": assume(m, invertible=True),
    "INVERTIBLE.assume(m)": INVERTIBLE.assume(m),
    "m": m,
}

for label, var in declarations.items():
    print(f"{label:<30}{INVERTIBLE.holds(var)}")

dprint(INVERTIBLE.assume(m), print_assumptions=True);
assume(m, invertible=True)    True
INVERTIBLE.assume(m)          True
m                             False
SpecifyAssumptions{invertible} [id A] a={inv}
 └─ m2 [id B]

A matrix property: stochastic matrices#

The rows of a row-stochastic matrix (a Markov transition matrix) sum to one, and the product of two such matrices is again stochastic.

register_matrix_property_rules supplies the plumbing (the property survives batch indexing, reshapes, and broadcasting), leaving only the rule specific to this property:

from pytensor.assumptions import register_matrix_property_rules
from pytensor.tensor.math import Dot, Sum

STOCHASTIC = AssumptionKey("stochastic", "stoch")
register_matrix_property_rules(STOCHASTIC)


@register_assumption(STOCHASTIC, Dot)
def _product_of_stochastic(key, op, feature, fgraph, node, input_states):
    """A product of row-stochastic matrices is row-stochastic."""
    if all(state is FactState.TRUE for state in input_states):
        return [FactState.TRUE]
    return [FactState.UNKNOWN]


P = pt.matrix("P", shape=(3, 3))
Q = pt.matrix("Q", shape=(3, 3))
two_steps = STOCHASTIC.assume(P) @ STOCHASTIC.assume(Q)

# ``@`` is Blockwise(Dot); the delegate every key gets forwards to the core op.
print(f"{'P':<10}{STOCHASTIC.holds(STOCHASTIC.assume(P))}")
print(f"{'P @ Q':<10}{STOCHASTIC.holds(two_steps)}")
P         True
P @ Q     True

The rewrite reads the fact and replaces the reduction with a constant. Because the fact reached the product, the whole two-step chain collapses: the compiled graph contains neither the sum nor the matmul.

@register_specialize
@node_rewriter([Sum])
def _stochastic_rows_sum_to_one(fgraph, node):
    """Replace a row-sum with ones when the matrix is known stochastic."""
    [mat] = node.inputs
    if mat.type.ndim < 2 or node.op.axis != (mat.type.ndim - 1,):
        return None
    if not check_assumption(fgraph, mat, STOCHASTIC):
        return None
    return [pt.ones(mat.shape[:-1], dtype=node.outputs[0].dtype)]


f_rows = function([P, Q], two_steps.sum(axis=-1), mode="FAST_RUN")
dprint(f_rows);
Alloc [id A] 0
 ├─ 1.0 [id B]
 └─ 3 [id C]
stream = np.random.default_rng(1)
rows = stream.dirichlet(np.ones(3), size=3)
cols = stream.dirichlet(np.ones(3), size=3)

# The constant the rewrite inserted is the value the sum would have computed.
np.allclose(f_rows(rows, cols), (rows @ cols).sum(axis=-1))
True

A property that is not about matrices: sorted vectors#

Nothing about the system assumes a property describes a matrix. A vector known to be nondecreasing (a knot vector, bin edges, a grid of quantile levels) makes sort redundant, and a contiguous slice of it is still sorted.

The two rules below are the whole definition.

from pytensor.tensor.sort import SortOp
from pytensor.tensor.subtensor import Subtensor

SORTED = AssumptionKey("sorted", "sort")


@register_assumption(SORTED, Subtensor)
def _slice_of_sorted_is_sorted(key, op, feature, fgraph, node, input_states):
    """A contiguous slice of a sorted vector is still sorted."""
    if input_states[0] is not FactState.TRUE:
        return [FactState.UNKNOWN]
    if all(isinstance(index, slice) for index in op.idx_list):
        return [FactState.TRUE]
    return [FactState.UNKNOWN]


@register_specialize
@node_rewriter([SortOp])
def _sort_of_sorted_is_a_noop(fgraph, node):
    """Sorting an already-sorted vector returns it unchanged."""
    if not check_assumption(fgraph, node.inputs[0], SORTED):
        return None
    return [node.inputs[0]]


raw = pt.vector("grid", shape=(5,))
grid = SORTED.assume(raw)

# The slice carries the fact, so the sort is dropped.
f_sort = function([raw], pt.sort(grid[1:]), mode="FAST_RUN")
dprint(f_sort);
DeepCopyOp [id A] 1
 └─ Subtensor{start:} [id B] 0
    ├─ grid [id C]
    └─ 1 [id D]

Summary#

  • Declare structural facts with assume(). The result is a runtime no-op view of x.

  • Facts are three-valued (TRUE, FALSE, UNKNOWN), stored per graph, inferred lazily, and linked by a small implication lattice, so asserting the strongest property implies the weaker ones.

  • Contradictions raise ConflictingAssumptionsError.

  • Facts propagate through the graph automatically; inspect them with dprint(..., print_assumptions=True).

  • Compiling with rewrites turns those facts into faster graphs: diagonal matmuls become elementwise products, positive-definite solves become Cholesky solves, orthogonal Gram products fold to the identity, and Kronecker products of diagonals collapse.

  • A new property is a custom AssumptionKey, and constructing one registers it. register_assumption(), register_matrix_property_rules(), register_implies(), and register_constant_inference() say how it behaves, and a node_rewriter that calls check_assumption() turns it into a faster graph. A property need not describe a matrix.

The built-in properties are diagonal, lower_triangular, upper_triangular, symmetric, positive_definite, orthogonal, selection, permutation, and unique_indices.

The full API is documented in assumptions – Structural Assumptions and Assumption-Driven Rewrites.

Authors#

  • Authored by Jesse Grabowski in August 2026

Watermark#

%load_ext watermark
%watermark -n -u -v -iv -w -p pytensor
Last updated: Sun, 23 Aug 2026

Python implementation: CPython
Python version       : 3.14.7
IPython version      : 9.16.1

pytensor: 3.3.0+16.g1a4cc21de

numpy   : 2.5.2
pytensor: 3.3.0+16.g1a4cc21de

Watermark: 2.6.0

License notice#

All the notebooks in this example gallery are provided under a 3-Clause BSD License which allows modification, and redistribution for any use provided the copyright and license notices are preserved.

Citing Pytensor Examples#

To cite this notebook, please use the suggested citation below.

Important

Many notebooks are adapted from other sources: blogs, books… In such cases you should cite the original source as well.

Also remember to cite the relevant libraries used by your code.

Here is an example citation template in bibtex:

@incollection{citekey,
  author    = "<notebook authors, see above>",
  title     = "<notebook title>",
  editor    = "Pytensor Team",
  booktitle = "Pytensor Examples",
}

which once rendered could look like:

Jesse Grabowski . "Structural assumptions and assumption-driven rewrites". In: Pytensor Examples. Ed. by Pytensor Team.