assumptions – Structural Assumptions and Assumption-Driven Rewrites#

The pytensor.assumptions module records structural facts about symbolic tensors – that a matrix is diagonal, triangular, symmetric, positive-definite – so that graph rewrites can replace an expensive operation with a cheaper specialized one without inserting 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.

For a worked introduction, see the assumptions gallery notebook.

Declaring assumptions#

pytensor.assumptions.assume(x, diagonal=None, lower_triangular=None, upper_triangular=None, symmetric=None, positive_definite=None, orthogonal=None, selection=None, permutation=None, unique_indices=None, tridiagonal=None, unit_magnitude=None, **assumptions)[source]#

Attach structural assumptions to a symbolic tensor.

Returns a tensor identical to x at runtime but carrying the declared assumptions so that graph rewrites can exploit them. Each keyword may be True (assert the property holds), False (assert it does not hold), or None (no assertion).

Parameters:
  • x (tensor-like) – The input to annotate.

  • diagonal (bool, optional) – Assert that x is (or is not) a diagonal matrix.

  • lower_triangular (bool, optional) – Assert that x is (or is not) lower-triangular.

  • upper_triangular (bool, optional) – Assert that x is (or is not) upper-triangular.

  • symmetric (bool, optional) – Assert that x is (or is not) symmetric.

  • positive_definite (bool, optional) – Assert that x is (or is not) positive-definite.

  • orthogonal (bool, optional) – Assert that x is (or is not) orthogonal. For complex x this means unitary.

  • selection (bool, optional) – Assert that x is (or is not) a selection matrix

  • permutation (bool, optional) – Assert that x is (or is not) a permutation matrix

  • unique_indices (bool, optional) – Assert that x’s entries address distinct positions when used as an index (or that they do not): no value repeats, and no negative entry aliases a non-negative one (e.g. -1 and n-1). Such an index can never enlarge the axis it indexes, so it can be lifted earlier through operations without risk of duplicating computation.

  • tridiagonal (bool, optional) – Assert that x is (or is not) tridiagonal.

  • unit_magnitude (bool, optional) – Assert that every element of x has absolute value one.

  • **assumptions (bool, optional) – Assumptions registered by downstream libraries, passed by key name, e.g. time_varying=True.

Returns:

out – A view of x with the assumptions attached.

Return type:

TensorVariable

Examples

import pytensor.tensor as pt

x = pt.dmatrix("x")
x_diag = assume(x, diagonal=True)
x_not_sym = assume(x, symmetric=False)
class pytensor.assumptions.SpecifyAssumptions(assumptions)[source]#

No-op that declares structural assumptions on a tensor for use by graph rewrites.

assumptions is a tuple of (AssumptionKey, FactState) pairs sorted by key name. Declaring a fact therefore requires holding the key itself, and constructing a key registers it, so a graph cannot carry an assumption the system has never heard of. Two instances with the same fact set compare equal via __props__, so PyTensor’s graph merge collapses duplicates.

Parameters:

assumptions (dict mapping AssumptionKey to FactState) – The facts to declare.

Inspecting assumptions#

pytensor.assumptions.check_assumption(fgraph, var, key)[source]#

Return True iff key is definitively TRUE for var in fgraph.

Lazily attaches AssumptionFeature to fgraph if it is not already present.

class pytensor.assumptions.AssumptionFeature[source]#

FunctionGraph feature that tracks symbolic assumptions about variables.

Assumptions (e.g. “this matrix is diagonal”) are represented as (variable, AssumptionKey) -> FactState mappings. Facts are inferred lazily via per-Op rules registered with register_assumption().

Attached lazily by check_assumption() on first use. Results are cached and automatically refreshed when the graph changes.

check(var, key)[source]#

Return True iff the assumption is definitively TRUE for var.

get(var, key)[source]#

Return the inferred FactState for (var, key).

Raise ConflictingAssumptionsError when the cached state is FactState.CONFLICT — surfaces conflicts from substitutions or owner-inferred rules at the point of query, where the graph is stable and the caller can react.

class pytensor.assumptions.FactState(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)[source]#

Three-valued logic for assumption inference.

The three fact states are TRUE, FALSE and UNKNOWN.

UNKNOWN is the default condition, in which we cannot confirm or deny the fact. TRUE and FALSE are definitive states. If we have evidence that a fact is both TRUE and FALSE, we get CONFLICT. In general, a CONFLICT state should not be possible.

class pytensor.assumptions.ConflictingAssumptionsError[source]#

Raised when joining evidence about a (variable, key) produces FactState.CONFLICT.

Surfaces contradictions between user-asserted facts and inferred facts (or between multiple sources of inferred facts) before they can silently corrupt downstream rewrites.

pytensor.assumptions.summarize_assumptions(feature, var)[source]#

Return a compact {...} tag of the facts known about var.

Each TRUE fact appears as its short_name; each FALSE fact as !short_name. Implied facts are pruned: a TRUE fact is dropped when a stronger fact (one that implies it) is also TRUE, and a FALSE fact is dropped when a weaker fact (one it implies) is also FALSE. Return "" when nothing is known.

pytensor.assumptions.assumption_tags(outputs)[source]#

Map each variable reachable from outputs to its summarize_assumptions() tag, omitting variables with no known facts.

Properties#

Each property is an AssumptionKey. The built-in keys are DIAGONAL, LOWER_TRIANGULAR, UPPER_TRIANGULAR, SYMMETRIC, POSITIVE_DEFINITE, ORTHOGONAL, SELECTION, PERMUTATION, and UNIQUE_INDICES. MATRIX_KEYS holds the eight that describe a matrix; ALL_KEYS is a live view of every registered key, including those added by downstream libraries.

class pytensor.assumptions.AssumptionKey(name, short_name='')[source]#

Identifies a named structural property (e.g. “diagonal” or “triangular”).

Constructing a key registers it in KEY_REGISTRY and installs every rule declared with register_universal_assumption() for it, which is all a downstream library must do to add a property of its own.

name is the key’s identity: it is what assume() accepts as a keyword and what two keys may not share unless they are identical in every field.

Parameters:
  • name (str) – Unique identifier for the property, also the keyword assume() accepts.

  • short_name (str, optional) – Abbreviated label used by debugprint(print_assumptions=True). Falls back to name when empty.

Examples

import pytensor.tensor as pt
from pytensor.assumptions import AssumptionKey, FactState, register_assumption
from pytensor.tensor.elemwise import Elemwise

TOEPLITZ = AssumptionKey("toeplitz", short_name="toep")

x = TOEPLITZ.assume(pt.matrix("x"))
TOEPLITZ.holds(x)  # True
TOEPLITZ.holds(pt.exp(x))  # False -- no rule teaches it about Elemwise yet

A key answers only what its rules can derive, so teach it the Ops it should see through. Constant diagonals survive an entrywise op, unless an input broadcasts along one of the last two axes while varying along the other:

@register_assumption(TOEPLITZ, Elemwise)
def _elemwise_is_toeplitz(key, op, feature, fgraph, node, input_states):
    entrywise = all(
        feature.check(inp, key)  # the operand is itself Toeplitz
        or all(inp.type.broadcastable[-2:])  # or broadcasts a single value
        for inp in node.inputs
    )
    return [FactState.TRUE if entrywise else FactState.UNKNOWN]

TOEPLITZ.holds(pt.exp(x))  # True
TOEPLITZ.holds(x + x)  # True
TOEPLITZ.holds(x + pt.vector("v"))  # False -- the row varies along one axis

See register_matrix_property_rules() for the rules a property of the trailing two axes needs to survive transposes, reshapes, and indexing.

assume(x, *, state=True)[source]#

Return a view of x declaring this assumption.

Parameters:
  • x (tensor-like) – The input to annotate.

  • state (bool, optional) – Whether to assert the property holds or that it does not. Default True.

Returns:

out – A view of x with the assumption attached.

Return type:

TensorVariable

holds(var, fgraph=None)[source]#

Return True iff this assumption is provably TRUE for var.

Parameters:
  • var (Variable) – The variable to ask about.

  • fgraph (FunctionGraph, optional) – Graph to resolve the question in. Pass one when asking about several variables of the same graph: without it a throwaway FunctionGraph is built per call, which walks the ancestors of var and discards the inference cache afterwards.

Returns:

holds – True when the property is known to hold, False when it is known not to hold or is simply unknown.

Return type:

bool

Defining a new property#

Constructing an AssumptionKey registers it, after which assume() accepts it by name and debugprint(print_assumptions=True) reports it. The functions below say how the new property behaves.

pytensor.assumptions.register_assumption(key, *op_types, prepend=False)[source]#

Decorator that registers an inference rule for (key, op_type) pairs.

The decorated function is called as fn(key, op, feature, fgraph, node, input_states) and must return a list of FactState with one entry per node output.

Parameters:
  • key (AssumptionKey) – The property the rule infers.

  • *op_types (type) – Op classes the rule applies to.

  • prepend (bool, optional) – Run this rule ahead of those already registered for the same pair rather than after them. Rules are tried in order until one returns a non-UNKNOWN state, so this is how a key overrides a rule it inherited from a bundle. Default False.

pytensor.assumptions.register_matrix_property_rules(key)[source]#

Register the standard propagation rules for a property of the trailing two axes.

Every rule here answers one question: does the Op leave the trailing two axes undisturbed? The bundle thus suits any property of a matrix that batch dimensions carry elementwise, such as triangularity or a fixed sparsity pattern.

Rules are tried in registration order until one returns a non-UNKNOWN state, so a key needing different behavior for one Op registers its own with register_assumption(..., prepend=True).

Parameters:

key (AssumptionKey) – The property to install the rules for.

Examples

from pytensor.assumptions import AssumptionKey, register_matrix_property_rules

TOEPLITZ = AssumptionKey("toeplitz", short_name="toep")
register_matrix_property_rules(TOEPLITZ)
pytensor.assumptions.register_universal_assumption(*op_types)[source]#

Decorator registering an inference rule that applies to every assumption key.

Use this for rules that are indifferent to what the property means – an Op that forwards its input unchanged, or one that delegates to another Op. The rule is installed for keys that already exist and for every key created later.

Parameters:

*op_types (type) – Op classes the rule applies to.

pytensor.assumptions.register_implies(stronger, *weaker)[source]#

Declare that stronger being TRUE implies each weaker key is also TRUE.

pytensor.assumptions.register_constant_inference(key, fn)[source]#

Register fn as the literal-constant inference for key.