Public API
Every name DeepLog’s public packages export, with its signature and docstring, on one page. These are the names a release keeps stable. Names appear under the package they are first exported from, so a name re-exported for convenience elsewhere is documented once. For every module, including the machinery behind these names, see the internals.
deeplog
DeepLog’s public API: stating a model, compiling it, running it and extending it.
- class Aggregation(
- operation: str,
- binders: tuple[Symbol, ...],
- params: tuple[Atom | UnaryOp | BinaryOp | Transformation | AggregationOp | Aggregation | CircuitNode, ...],
- child: Atom | UnaryOp | BinaryOp | Transformation | AggregationOp | Aggregation | CircuitNode,
An aggregation over
bindersapplyingoperationtochild.Unless
operationisexpectation, its value is its algebra’s aggregator foroperation(aggregation_fns) ofchildandparamsover every assignment ofbinders.Each binder is a variable.
bindersandparamsare tuples (not lists) so the node stays hashable and immutable;fold()convertsbindersback to a list at the factory call boundary. Anexpectationover binders without a distribution is given the one its binders have independently in probability: the product of a factorv(V)per binderV, wherevisV’s name with its leading underscores dropped and its first letter in lowercase.- Raises:
ValueError – If a binder is not a variable.
- class AggregationBuilder(*args, **kwargs)[source]
Builds the modules computing the aggregations of one operation.
Any callable with this signature is a builder.
- class AggregationOp(
- operation: str,
- operands: tuple[Atom | UnaryOp | BinaryOp | Transformation | AggregationOp | Aggregation | CircuitNode, ...],
operationapplied tooperands: its algebra’s aggregator over their values.Its value is the aggregator for
operation(aggregation_fns) of the algebra its operands share, over their values in order, as anAggregationaggregates its body’s values over the assignments of its binders.- Raises:
ValueError – If there is no operand, since its operands give it its algebra.
- class Algebra(
- *,
- name: str,
- values: tuple[Symbol, ...] | None = None,
- operator_fns: dict[str, Callable[[...], Tensor]] = ...,
- aggregation_fns: dict[str, Callable[[...], Tensor]] = ...,
- constant_fn: Callable[[Symbol], float | None] = ...,
- product: str = 'times',
- product_fn: Callable[[...], Tensor] = ...,
- sum: str = 'plus',
- sum_fn: Callable[[...], Tensor] = ...,
- zero: Symbol = ('0',),
- one: Symbol = ('1',),
- negation: str = 'not',
- negation_fn: Callable[[...], Tensor] = ...,
A semiring with an involutive complement.
- negation_fn() Tensor
Default complement:
one - x.
- class AlgebraicStructure(
- *,
- name: str,
- values: tuple[Symbol, ...] | None = None,
- operator_fns: dict[str, Callable[[...], Tensor]] = ...,
- aggregation_fns: dict[str, Callable[[...], Tensor]] = ...,
- constant_fn: Callable[[Symbol], float | None] = ...,
Defines an algebraic structure: a set of values, with operators and aggregators over them.
- values: tuple[Symbol, ...] | None = None
The set of labels a formula over this structure takes (Def 1’s
A_R), in value order, orNonewhen they are not finitely enumerable. A variable associated with this structure inherits these as its domain (of_structure()).
- operator_fns: dict[str, Callable[[...], Tensor]]
The operators a formula over this structure applies, by name.
- aggregation_fns: dict[str, Callable[[...], Tensor]]
The aggregators a formula over this structure can aggregate with (Def 1’s
Agg_R), by the operation an aggregation names.
- property roles: dict[str, str]
The operator name this structure spells each of its roles with.
A role is an operator that an axiom names, so a bare structure declares none: its
operator_fnsare free-form. Each subclass adds the roles its axioms name, which is how one structure resolves another’s operators — the same product whether it is spelledandortimes.
- property identities: dict[str, Symbol]
The symbol this structure names each of its identity elements with.
What
rolesis for operators, this is for the constants an axiom names: an identity crosses between structures by the role it plays, not by the value it happens to have.
- get_constant_value(symbol: Symbol) float | None[source]
The value
symbolnames, orNonewhen it names an atom.See
ConstantFnfor the three answers a caller distinguishes.- Raises:
ValueError – If
symbolnames a constant this structure does not have.
- apply_substitution( ) Symbol[source]
Apply a substitution mapping to a symbolic term.
- Parameters:
term – The term to perform the substitution on.
substitution – A dictionary {…, vi -> ti, …}.
- Returns:
A new term where each instance of vi in the original term is replaced with ti.
- class Atom(atom: Symbol)[source]
A leaf atom.
atomis the structure-wrapped symbol("_", inner, (structure,)), exactly ascreate_atom()receives it.=is symmetric, and an=comparing a written value with a variable holds the variable first:Atomstores=(a, X)as=(X, a), so the two spellings are one atom.
- class AtomBuilder(*args, **kwargs)[source]
Builds the module computing the atoms of one predicate.
A compiler registers a builder under the predicate it builds. Any callable with this signature is a builder; so is every
Predicatesubclass.
- class BinaryOp(
- operator: str,
- lhs: Atom | UnaryOp | BinaryOp | Transformation | AggregationOp | Aggregation | CircuitNode,
- rhs: Atom | UnaryOp | BinaryOp | Transformation | AggregationOp | Aggregation | CircuitNode,
A binary operator combining two operands.
- BOOLEAN = Algebra(name='boolean', values=(('false',), ('true',)), product='and', sum='or', negation='not')
The two truth values under
and/or/not, withfalseas zero andtrueas one, aggregated byexistsandforall. The structure a formula is written in before any reading is put on it.
- calculate_mgu(term1: Symbol, term2: Symbol) dict[Symbol, Symbol] | None[source]
Return the most general unifier of
term1andterm2, orNone.The unifier is the substitution
swithapply_substitution(term1, s) == apply_substitution(term2, s)that every other such substitution refines.Nonemeans the terms do not unify. Variables are identified by name, so every_is the same variable.There is no occurs check. Unifying a variable with a term containing it is not supported: it may raise
RecursionError, or return a substitutionapply_substitution()cannot apply.
- class Compiler(
- variables: Mapping[Symbol, Domain] | None = None,
- reification: AlgebraicStructure = Algebra(name='boolean', values=(('false',), ('true',)), product='and', sum='or', negation='not'),
- structures: Mapping[str, AlgebraicStructure] | None = None,
- aggregation_builders: Mapping[str, AggregationBuilder] | None = None,
- atom_builders: Mapping[tuple[str, int, str], AtomBuilder] | None = None,
- transformation_builders: Mapping[tuple[str, str], TransformationBuilder] | None = None,
Compiles formulas to one module, with the domains, algebras and builders to use.
variablesdeclares the domain each binder ranges over; a binder it does not declare is a reification variable, ranging over the values ofreification.structuresnames the algebras a formula may use beside the registered ones, and wins over them.atom_builders,aggregation_buildersandtransformation_buildersadd builders, keyed by predicate, operation and pair of algebras, and each wins over the default registered for its key. An aggregation whose operation has no builder is computed byreduction().The value test
=/2is the compiler’s own: it reads a variable’s value as its position in the variable’s domain (domain()), which only the compiler knows.An atom no builder computes is an input of the compiled module, named by the atom. Where it reads variables an aggregation binds, it is its ground atoms instead, an input each, named by substituting those variables’ values, and read at the values the aggregation gives them; such a variable must range over named values.
Every argument of an atom has a sort, the domain its predicate declares for it (
domains_of()). A variable ranges over its domain invariables, or else over the named or tensor domain of the arguments it is that each of the others includes; each must include the variable’s domain, and a variable over part of a named one reaches its predicate as a position in it. An argument of sort the values takes a variable over values without names. A variable that no argument gives a domain ranges over its declared one, or, if it is bound and only=tests it, over the values ofreification. A variable an aggregation binds is that aggregation’s own, so two aggregations binding one name may give it different domains; a free variable is one variable in every formula compiled together (Sorts).Configure the compiler with the domains, algebras and builders to use.
- compile(
- formulas: Mapping[str | Symbol, Atom | UnaryOp | BinaryOp | Transformation | AggregationOp | Aggregation | CircuitNode],
- /,
- compile(
- *formulas: Atom | UnaryOp | BinaryOp | Transformation | AggregationOp | Aggregation | CircuitNode,
Compile
formulasto one module with a column per formula, in order.Given as one mapping, each formula’s column is named by its key, a symbol or the text of one; given as formulas, the
i-th column is named@i. A name is labelled with the algebra of its column, asrain_implies_wet _ probability, and equal formulas compile once, whatever their names.Each formula is constructed bottom-up by folding it through a
CircuitFactory, which rewrites every region a circuit can hold into a lump, and the results are lowered together, top-down (Lowering). Equal subformulas of all the formulas are first made one object, and construction runs under one memo, so a subformula is built once however many formulas write it, their shared atoms are one circuit leaf, and counts over one boolean circuit take one knowledge compilation. The atoms whose builder’s module reads none of their variables are computed before any aggregation, by one module per predicate, so a network fed no variable runs once per input, however many aggregations read it and however deep.- Raises:
TypeError – If a mapping is given beside formulas.
ValueError – If two formulas are given one name, or a name is labelled with an algebra its formula’s value is not in.
- domain(binder: Symbol) Domain[source]
The domain
binderranges over.A binder the compiler declares in its
variablesuses that domain. Any other binder is a reification variable, and inherits the values of the compiler’sreificationalgebra as its domain.- Raises:
ValueError – If the binder is undeclared and the reification algebra declares no enumerable values.
- algebra(name: str) AlgebraicStructure[source]
The algebra named
name: the compiler’s own, else the registered one.- Raises:
ValueError – If
nameis neither the compiler’s own nor registered.
- atom_builder( ) AtomBuilder | None[source]
The builder of the
functor/arityatoms instructure, orNone.
- declaring(
- variables: Mapping[Symbol, Domain] | None = None,
- atom_builders: Mapping[tuple[str, int, str], AtomBuilder] | None = None,
A copy of this compiler that also declares
variablesandatom_builders.For a front end that introduces binders and predicates of its own, whose caller cannot know them. Its builders shadow the compiler’s defaults, such as
p/2in probability for a program’s ownp/1extended with a binder. This compiler is left as it is.- Raises:
ValueError – If a binder is already declared with another domain, or this compiler was given a builder for one of the keys.
- compose_modules(
- modules: Iterable[DeepLogModule],
- output_shape: Shape,
- input_shape: Shape | None = None,
Compose modules into one module taking
input_shapeand producingoutput_shape.Each symbol is produced by at most one module. The composed module’s inputs are the symbols no module produces.
input_shapelays them out, and must hold each of them and none a module produces; without it, each is a tensor of its own, in the order the modules first read them. A single module is reshaped to the requested shapes, and returned as it is when it already has them; several become aModuleCircuit, which orders them by what each one’s inputs need and inserts the transformations between them.A capitalised name is a variable. A module whose output holds a variable none of its inputs hold binds it, and gives its values along an axis behind its symbols. A value holding the variable then has an axis for it after its batch, and a module reading such a value runs on a row per value of it. Calling the composed module raises
ValueErrorwhere a module binding a variable gives no axis for it.- Raises:
ValueError – If no module is given, two modules produce one symbol, or
input_shapeholds a symbol a module produces.
- class DeclaresDomains(*args, **kwargs)[source]
A module that declares the domain each argument of its atoms ranges over.
Every
Predicateis one, and every module an atom builder returns is: the compiler gives each variable the domain of the arguments it is (Sorts).
- class DeepLogModule(input_shape: Shape, output_shape: Shape)[source]
A class that extends Torch modules to include information about its input and output shape.
Capture the symbolic input and output shapes for the module.
Registers shape-validation forward hooks when
DEEPLOG_VALIDATEis enabled (the default). Disable viaDEEPLOG_VALIDATE=0in the environment.Validation adds ~1.5 µs per forward call (a small constant for the input/output
correct_shapechecks). For typical workloads where each forward does real computation, this is well under 1% overhead; disabling matters only in tight micro-benchmarks over many trivial modules. The env var is consulted in__init__, so changing it after import only affects newly-constructed instances.- to_graph(graph=None)[source]
Add this module to the provided Graphviz graph and return connection nodes.
- class Domain[source]
The values a variable ranges over, in value order.
- static of_tensor(values: Tensor) Domain[source]
A domain whose values are the rows of
valuesand have no names.
- static of_values() Domain[source]
The open domain of values without names, such as numbers or images.
It is never enumerated, so a variable over it is free: the caller gives it its value.
- static of_structure(
- structure: AlgebraicStructure,
The domain a variable associated with
structureinherits.- Raises:
ValueError – If
structuredeclares no values, i.e. they are not finitely enumerable, so a variable over it needs a domain of its own.
- property values: tuple[Symbol, ...]
The symbol writing each value, in value order.
- Raises:
ValueError – If this domain’s values have no names.
- index(value: Symbol) int[source]
The position of the value
valuewrites.- Raises:
ValueError – If this domain’s values have no names, or
valuewrites none of them.
- enumeration(
- nodes: Sequence[Aggregation],
- lowering: Lowering,
Exact, by evaluating the body at every combination of its variables’ outcomes.
Each variable’s factor is evaluated at every value of its binders, and the body at every combination, missing outcomes included.
- Raises:
ValueError – If an expectation’s body is not boolean, it has more than one param, its distribution’s algebra has no sum and product, one of its binders has no factor, or a leaf that is not boolean reads a binder that may have no value.
- class EqualityPredicate( )[source]
Whether the two arguments of an atom name the same value.
Both arguments range over the domain of the variable the atom compares, so a written value compared with a variable is read as the variable’s value is. Two written values range over the names they write, so they compare by name.
Compare the arguments of each atom,
domain_ofgiving each variable’s domain.- Raises:
ValueError – If a written value is not a value of the domain of the variable it is compared with, or two variables compared with each other range over different domains.
- FormulaNode = deeplog.formula.ast.Atom | deeplog.formula.ast.UnaryOp | deeplog.formula.ast.BinaryOp | deeplog.formula.ast.Transformation | deeplog.formula.ast.AggregationOp | deeplog.formula.ast.Aggregation | deeplog.formula.ast.CircuitNode
A formula node is either still-symbolic (
Atom/UnaryOp/BinaryOp/Transformation/AggregationOp/Aggregation) or a graph-backedCircuitNode, whose fine internal structure lives in the circuit rather than nested objects.Every node exposes a
.structureproperty (str | None) — the symbolic-layer counterpart to the module layer’ssole_structure()over a module’s output symbols. Both read a label off data rather than off an object — an AST node carries it on its atom, a module on the symbols naming its outputs.
- get_predicate(symbol: Symbol) tuple[str, int][source]
Return the predicate functor and arity for the given symbol.
- get_term_variables(symbol: Symbol) Iterable[Symbol][source]
Returns an iterable of all variables that appear in Symbol. These are not unique.
- GODEL = Algebra(name='godel', values=None, product='and', sum='or', negation='not')
Gödel’s fuzzy logic, truth values in
[0, 1]under the minimum t-norm.andis the t-norm,orits dual conorm, the maximum,notthe standard negation1 - x, andimpliesthe t-norm’s residuum, the greatestcwitha and c <= b.forallis the t-norm over a variable’s domain andexiststhe conorm. The minimum distributes over the maximum, so this is anAlgebra.
- LOGPROBABILITY = _ComplementedSemifield(name='logprobability', values=None, product='times', sum='plus', division='divide', negation='negate')
PROBABILITYin log space, where a product adds and a sum islogaddexp, sosumaggregates by log-sum-exp. Zero is-infand one is0.
- class LogProbabilityPredicate(atoms: Iterable[Symbol])[source]
(atom, label)predicate with log-probability-space outputs.Weigh the truth value of each atom by its label.
- class Lowering(compiler: Compiler)[source]
One compile’s walk: lowers constructed formulas top-down, a level at a time.
An aggregation builder receives the walk, and lowers through
lower()what its method needs, with the domains and builders of itscompiler, which declares the domain of each binder of the aggregations it builds.The walk’s handlers mirror the construction factory’s eliminators, one per AST type, but each receives every node of its type in a level, unlowered:
atoms go to their atom builders, one call per predicate;
unary and binary operators become the algebra’s operator functions, read over their operands’ columns;
aggregations of operands become the algebra’s aggregators, one module reading all their operands’ columns;
casts go to the builder registered for their pair of algebras;
aggregations go to the builder registered for their operation, one call per operation, apart from those where one binds a variable another reads free, or two bind one name over different domains;
lumps of one circuit compile into one core, apart from a lump that reads another of its circuit through a cast.
Lower with
compiler’s domains, algebras and builders.- property compiler: Compiler
The compiler whose domains, algebras and builders this walk lowers with.
- lower(
- *nodes: Atom | UnaryOp | BinaryOp | Transformation | AggregationOp | Aggregation | CircuitNode,
One module with a column per node, in the order given.
A variable free in
nodesthat thecompilerdoes not declare ranges over the domain its arguments there give it, from then on.- Raises:
ValueError – If two nodes name one column.
- LUKASIEWICZ = AlgebraicStructure(name='lukasiewicz', values=None)
Łukasiewicz’s fuzzy logic,
GODEL’s connectives and quantifiers under the t-normmax(0, a + b - 1), whose conorm is the bounded summin(1, a + b). As withPRODUCT, this is noSemiring.
- MPE = _ComplementedSemifield(name='mpe', values=None, product='times', sum='plus', division='divide', negation='negate')
Max-product — the most probable explanation. A semiring like any other, so a knowledge-compiled formula reaches it through the ordinary transform rather than through a compile-time override —
maxin place of a sum keeps the single best explanation wherepluswould total them all, andsumaggregates by it too.
- class NetworkPredicate( )[source]
Predicate whose values are the output rows of a provided
torch.nn.Module.Always binary: the first argument is fed to the module, and the second is a value of
domain, which lists the values of the module’s output rows in row order.digit(x, v)is the entry ofx’s row atv’s position.It reads only the first arguments of the atoms it is given, and computes every value of each, running the module once per distinct first argument: asked for
digit(i1, 2)anddigit(i2, D), it computesdigit(i1, 0)todigit(i1, 9)anddigit(i2, 0)todigit(i2, 9), in that order. A second argument only asks for an atom: a written value must be one of the domain’s, written as the domain writes it (values), and a variable may stand there.Compute every value of each first argument of
atomsthroughmodule.- Raises:
ValueError – If
domaindoes not write its values, an atom is not binary, its first argument is a written number, which names no input, or its second is a written value not indomain.
- forward_predicate(inputs: Tensor) Tensor[source]
The module’s output on
inputs, a row of one entry per value for each.- Raises:
ValueError – If the module’s output does not have one row per input of one entry per value of the domain.
- OPEN: Symbol = ('_',)
The term position an occurrence leaves open for the variable’s value.
- parse_dimacs_cnf(
- dimacs: str,
Parse
dimacsinto the boolean formula of its clauses.Variable
iis the variableVi, and the literaliits test=(Vi,true), soexpectation(V1, ..., Vn): φis the probability that the formulaφholds when eachViis true with probabilityvi(true). A negative literal is the negation of its test, a clause the disjunction of its literals, and the formula the conjunction of its clauses. An empty clause isfalse, and a clause holding a literal and its negationtrue.- Raises:
ValueError – If
dimacsis not well-formed DIMACS CNF.
- parse_formula(
- text: str,
Parse
textinto a formula.Equal subformulas are interned to one object via
hash_cons(), so the formula is a value-keyed DAG rather than a tree.
- parse_formula_to_module( ) DeepLogModule[source]
Parse
textand compile it:compiler.compile(parse_formula(text)).compilerdefaults to aCompilerwith the default builders. Withname, the module’s column is named by it, ascompiler.compile({name: parse_formula(text)})names it.
- parse_symbol( ) Symbol[source]
Read the symbol
symbol_str.A symbol is a constant or variable
a, a compound termf(a, b), a list[a, b | T], or a structure-tagged symbola _ s, and brackets around a symbol group it. Text without brackets that is none of these, such asX is Y, is one constant.- Parameters:
symbol_str – The text to read.
parse_argument – Reads each argument, list element, side of
_and bracketed symbol;parse_symbol()itself by default.
- Raises:
ValueError – If a term’s arguments are not closed, text follows the bracket closing them, or brackets enclose nothing.
- class Predicate(
- atoms: Iterable[Symbol],
- domains: Sequence[Domain] | Callable[[tuple[Symbol, ...]], Sequence[Domain]],
- *,
- ignore_arguments: Iterable[int] | None = None,
Base class for predicates backed by torch computations or constants.
A predicate computes the atoms it is given, a column named by each, from their arguments. A compiler registers it under the predicate it computes.
Subclasses parameterize the generic with the tuple of tensor types that
forward_predicate()will receive — one entry per non-ignored argument position. Example:class MyPred(Predicate[torch.Tensor, torch.Tensor]):declares a binary predicate.An argument position asks for each distinct symbol once, not once per evaluation:
digit(i1,0) … digit(i1,9)are ten evaluations over one input, so the input shape holdsi1once. Positions are expanded back to one row per evaluation beforeforward_predicate()sees them.Each argument ranges over a domain, its sort (
domains_of()). A value written where it ranges over a named or a tensor domain is read as what a variable there holds: the domain’s element it writes (index()), its position among the domain’s names or the domain’s own number, in the domain’s dtype. So an atom reads the same whether an aggregation feeds its variable a value or the value is written into it. Where it ranges over the values (of_values()), a written argument is whatresolve_argument()says: by default a number it writes, or else the name of an input.Compute
atoms, a column named by each, from their arguments.domainsgives the domain of each argument, one per argument of the atoms, or is a function giving them for one atom’s arguments (domains_of()).- Raises:
ValueError – If
atomsis empty or its atoms differ in arity,domainsgives an atom other than one domain per argument, or a value written where an argument ranges over a named or a tensor domain is not one of its values.
- forward(*x: Tensor) Tensor[source]
Evaluate the predicate for all provided arguments and return batched results.
A position whose input names no symbol holds only constants, and its tensor, which carries no values, is not read.
- eager_eval( ) Tensor[source]
Evaluate eagerly, resolving any free symbols via
tensors.Free symbols (positions where
resolve_argumentreturned aSymbolrather than a constant) are looked up intensorsand stacked into the input batch for that position. Constant positions use the buffers populated during__init__.Returns a tensor of shape
[n_evaluations, *output_shape]. RaisesKeyErrorif a free symbol is missing fromtensors.
- domains_of( ) tuple[Domain, ...][source]
The domain each argument of an atom with
argumentsranges over.- Raises:
ValueError – If the predicate gives other than one domain per argument.
- resolve_arguments( ) tuple[Symbol | int | float | bool | Tensor, ...][source]
What each argument of one atom stands for.
A value written where an argument ranges over a named or a tensor domain (
domains_of()) is read as what a variable there holds; a variable, and an argument written where it ranges over the values, is whatresolve_argument()says. An ignored position keeps its symbol. A subclass whose reading of one argument depends on another in a way other than through its domain overrides this.- Raises:
ValueError – If a value written where an argument ranges over a named or a tensor domain is not one of its values.
- resolve_argument( ) Symbol | int | float | bool | Tensor[source]
What the argument
symbolat positionindexof an atom stands for.It is asked for a variable, and for an argument written where it ranges over the values (
domains_of()). A subclass overrides this to give such arguments other constant values. By default a written number is that number, and any other argument is a variable, read from the input under its symbol.- Returns:
A symbol, which makes the argument a variable read from the input under that symbol, or a value, which makes it a constant: a tensor is used as it is, and a number or a boolean as a scalar.
- abstractmethod forward_predicate(*args: Tensor) Tensor[source]
Batched implementation of the predicate.
Receives one tensor per non-ignored argument position, in argument index order, with constants and symbol values already substituted. Concrete subclasses can still document or narrow the individual tensor argument types they expect.
- PROBABILITY = _ComplementedSemifield(name='probability', values=None, product='times', sum='plus', division='divide', negation='negate')
Probabilities in
[0, 1]undertimesandplus, withnegatethe complement1 - p, aggregated bysum. Its product is invertible, which is what a conditional needs to divide by its evidence.
- class ProbabilityPredicate(atoms: Iterable[Symbol])[source]
(atom, label)predicate with probability-space outputs.Weigh the truth value of each atom by its label.
- PRODUCT = AlgebraicStructure(name='product', values=None)
Product fuzzy logic,
GODEL’s connectives and quantifiers under the product t-norm, whose conorm is the probabilistic suma + b - a * b. The product does not distribute over that sum, so this is noSemiring.
- REAL = Semiring(name='real', values=None, product='times', sum='plus')
The real numbers under
timesandplus, aggregated bysum. A network’s pre-activation output is real, and so is a count, since theboolean -> realcast readstrueas 1 andfalseas 0. Its values are not finitely enumerable.
- reduction(
- nodes: Sequence[Aggregation],
- lowering: Lowering,
- /,
Compute each aggregation by reducing its operands over its binders’ values.
The operands of the aggregations over the same binders are lowered together, each with an axis for every one of those binders free in it, which the aggregation’s algebra reduces with its aggregator for the aggregation’s operation (
AggregationFn). So each subformula is evaluated once per assignment of the binders free in it, and aggregations over the same binders evaluate what they share once. An atom that holds binders at arguments of sort a named or a tensor domain is read from its ground atoms, one for each combination of those binders’ values, which its builder receives in its place; a binder whose values cannot be written, as rows of a tensor that are not numbers, is not among them. A compiler computes this way every operation it has no other builder for.- Raises:
NotImplementedError – If an aggregation’s algebra has no aggregator for its operation.
- reshape(
- module: DeepLogModule,
- input: tuple[SymTensor, ...] | SymTensor | None = None,
- output: tuple[SymTensor, ...] | SymTensor | None = None,
Wrap
moduleso its input and/or output shape matches the requested shapes.- Parameters:
module – The module whose input and/or output should be reshaped.
input – If provided, the new input shape for
module.output – If provided, the new output shape for
module.
- Returns:
A module that performs identically to the given module under the requested shapes.
- sampling( ) AggregationBuilder[source]
The builder estimating each expectation from
samplesdrawn assignments.An expectation whose distribution is in probability, as one without a distribution is, is sampled. Each variable’s outcome, missing included, is drawn with probability its weight divided by the total; the estimate is the mean of the body over the draws, times those totals. Expectations whose variables agree where they share binders read the same draws, so the ratio of two is estimated on one set of assignments. Every other expectation is enumerated.
gradientreceives the values of the bodies at the draws and the log-probability of drawing them, both of shape(batch, samples, expectations), and returns values equal to the first whose gradient estimates the expectations’.- Raises:
ValueError – If
samplesis not positive.
- score_function(values: Tensor, log_probability: Tensor) Tensor[source]
The score-function estimator, with the other draws’ mean as its baseline.
valuesare what each expectation’s body takes at each drawn assignment andlog_probabilitythe log-probability of drawing it, both of shape(batch, samples, expectations). The result equalsvalues, and its gradient adds each draw’s log-probability gradient, weighted by how far its value lies from the mean of the other draws. That mean does not depend on the draw, so the estimate stays unbiased; a single draw has no baseline.
- class Semifield(
- *,
- name: str,
- values: tuple[Symbol, ...] | None = None,
- operator_fns: dict[str, Callable[[...], Tensor]] = ...,
- aggregation_fns: dict[str, Callable[[...], Tensor]] = ...,
- constant_fn: Callable[[Symbol], float | None] = ...,
- product: str = 'times',
- product_fn: Callable[[...], Tensor] = ...,
- sum: str = 'plus',
- sum_fn: Callable[[...], Tensor] = ...,
- zero: Symbol = ('0',),
- one: Symbol = ('1',),
- division: str = 'divide',
- division_fn: Callable[[...], Tensor] = ...,
A semiring whose product is invertible, so division is defined.
Independent of
Algebra: an invertible product says nothing about a complement. An algebra that divides differently supplies its owndivision_fn.- division_fn(b: Tensor) Tensor
Default division, flooring the denominator at the smallest normal value.
Derived per dtype, not pinned: a constant
1e-12stores as exactly zero in float16, where the clamp would silently do nothing. Bounds the forward pass only — the gradient still overflows just above the floor.
- class Semiring(
- *,
- name: str,
- values: tuple[Symbol, ...] | None = None,
- operator_fns: dict[str, Callable[[...], Tensor]] = ...,
- aggregation_fns: dict[str, Callable[[...], Tensor]] = ...,
- constant_fn: Callable[[Symbol], float | None] = ...,
- product: str = 'times',
- product_fn: Callable[[...], Tensor] = ...,
- sum: str = 'plus',
- sum_fn: Callable[[...], Tensor] = ...,
- zero: Symbol = ('0',),
- one: Symbol = ('1',),
A semiring: a product and a sum with their identities.
- class Sequential(*submodules: DeepLogModule)[source]
Chains multiple DeepLogModules so each submodule consumes the previous output. Functions similarly to torch.nn.Sequential.
Chain the provided submodules, flattening nested Sequential containers.
- to_graph(graph=None)[source]
Render the composed modules into a graph, chaining edges in order.
- forward(*inputs)[source]
Run the input tensors through each submodule sequentially.
- Shape = Shape
What a module declares it reads and writes — one
SymTensornaming a single tensor’s symbols, or a tuple of them, one per tensor.
- class ShapeMismatchException( )[source]
Raised when tensors do not conform to the shape that named them.
Build the message: what
shapenamed, whatargswere, and where.locationis whatever identifies the site for a reader of the message; a module reports(module, "input")or(module, "output").
- structure_of(symbol: Symbol) str | None[source]
Return the algebraic structure
symbolis labelled with, orNone.The total read of the
("_", inner, (structure,))tag: a bare symbol names a value that lives in no algebra, which is a legitimate state outside the formula layer, so absence is reported rather than raised. Counterpart ofwith_structure().
- Symbol = Symbol
A term as a nested tuple — a functor followed by its arguments, each a symbol in turn.
("digit", ("i1",), ("3",))isdigit(i1,3), and a bare("a",)is the constanta.
- symbol_to_pretty_string(symbol: Symbol) str[source]
Format
symbolfor a human reader, infixing the functors that read better.Not the inverse of
parse_symbol();symbol_to_str()is the form that parses back.
- symbol_to_str(symbol: Symbol) str[source]
Format
symbolas the textparse_symbol()reads back.A compound term is
f(a,b), whatever its functor, sois(X,Y)forX is Y, and a structure tag isa _ s. Brackets group an operand that would read otherwise: a side of a tag that is itself tagged, as in(a _ s) _ t, and an argument whose functor holds a comma, as inf((,(a,b))). A functor holding a bracket does not read back.Use
symbol_to_pretty_string()for human-readable output.
- class SymbolDict[source]
A
{Symbol: tensor}mapping that prints symbols and scalars compactly.A plain
dictin every other respect;to_dict()returns one so interactive readouts (print(to_dict(module(x), shape))) stay legible.
- class SymTensor(symtensor_like: SymTensorLike, subtensor_shape: tuple[int, ...] | None = None)[source]
Numpy-backed container that represents symbolic tensor indices.
Creates a symbolic tensor from a SymTensor-like input. If an array-like input of strings is given, then parse_symbol will be used to construct symbols. This flexibility can lead to an ambiguous cases, e.g. with symtensor_like = (‘a’,) which can be interpreted as scalar SymTensor of the constant a, or parsed into a 1-dimensionsal symtensor [a]. In these cases, it will first consider the input to be an array-like of symbols. To avoid this ambiguity, use nested lists instead of tuples as input.
- Parameters:
symtensor_like – An object that can be cast to a SymTensor.
subtensor_shape – The shape of the sub-tensors.
- property array: NDArray[object_]
The underlying numpy array of symbols.
- SymTensorLike = SymTensorLike
Anything
SymTensoraccepts as its symbols — a SymTensor, a symbol, a string parsed as one, a nested sequence of those, or a numpy object array.
- to_dict( ) SymbolDict[source]
Split result tensors into a per-symbol dict following
shape.The read-out counterpart of shape validation:
shape(typically a module’sget_output_shape()) names every entry oftensors, and each symbol maps to its entry with the batch dimension preserved —to_dict(module(x), module.get_output_shape())reads a module’s output by name. The result is aSymbolDict, a plain dict that prints readably.Raises
ShapeMismatchExceptionwhen the tensors do not conform toshapeandValueErrorwhenshapenames the same symbol twice.
- to_symbol(arg: Symbol) Symbol[source]
- to_symbol(arg: str) Symbol
- to_symbol(arg: list[str] | list[Symbol]) list[Symbol]
Turn the given argument into a symbol (or list of symbols).
- class Transformation(
- structure: str,
- child: Atom | UnaryOp | BinaryOp | Transformation | AggregationOp | Aggregation | CircuitNode,
A structure-conversion node mapping
childintostructure.
- class TransformationBuilder(*args, **kwargs)[source]
Builds the module casting values between the pair of algebras it is keyed by.
Any callable with this signature is a builder.
- class TransformationNotPossible( )[source]
This exception is raised when a requested transformation is not possible.
Record the incompatible input/output shapes that triggered the failure.
- class UnaryOp(
- operator: str,
- operand: Atom | UnaryOp | BinaryOp | Transformation | AggregationOp | Aggregation | CircuitNode,
A unary operator applied to a single operand.
- class Variable(name: Symbol, domain: Domain)[source]
A model variable and the domain it ranges over.
A variable owns no atoms. An atom is a predicate applied to terms, and a term may be a variable, so a variable is linked to an atom by occurring in it – see
VariableAtoms. Nothing pairs a value with an atom: the atom asserting a value is what substituting that value into an occurrence yields.
- VariableAtoms = VariableAtoms
Where each variable occurs — the atoms it appears in, with its own term position left
OPEN.digit(i1,_)is the occurrence of the variabledigit(i1)over0 ... 9, anddigit(i1,3)– the atom asserting the value 3 – is what substituting yields.A variable may occur in several atoms and an atom may be an occurrence of several variables, so neither direction is a function. In the degenerate case the occurrence is
OPEN: the whole atom is the variable’s position, so the values are the atoms, which is what a disjunction over unrelated atoms declares.
- weighted_model_count(
- nodes: Sequence[Aggregation],
- lowering: Lowering,
Exact: knowledge-compile each group’s bodies into their distribution’s algebra.
An expectation is counted when its body is a boolean circuit lump, every leaf of which tests one of its binders for a named value of the binder’s domain, and its distribution, in probability or log-probability, is a product of atoms, one for each binder and mentioning only that binder, as an argument. The leaf testing
Vforvthen weighs asV’s factor withvsubstituted, which its predicate reads asVholdingv, since the argument’s sort isV’s domain. Expectations over one circuit, counted into one algebra, whose factors agree on the binders they share, are one group, and each group takes one knowledge compilation. A group reaching two values of one binder compiles with mv-sdd, whichpydeeplog[mvsdd]installs. Every other expectation, and every one in a group whose knowledge compiler is not installed, is enumerated (enumeration()).
- with_structure(atom: Symbol, structure: str) Symbol[source]
Return
atomwrapped withstructure, replacing any existing wrapper.
- without_structure(symbol: Symbol) Symbol[source]
Return
symbolwith any structure tag removed.The tolerant counterpart of
unwrap_structure(): a bare symbol is returned unchanged. Used when re-minting a name from a labelled one, so the tag is re-applied to the outside rather than buried in the new symbol.
- class WrappedModule(
- module: Callable,
- input_shape: Shape,
- output_shape: Shape,
- name: str | None = None,
- vmap: bool = False,
Wrap an arbitrary callable with DeepLogModule shape semantics.
Wrap a callable with declared shapes and optional vmap execution.
namedefaults to the callable’s own__name__when it has one (a function or a class), and to its type name otherwise — annn.Moduleinstance is a callable without a__name__, so wrapping one must not force the caller to invent a label.- forward(*args, **kwargs)[source]
Delegate execution to the wrapped callable.
deeplog.circuit
Algebraic circuits: build one, knowledge-compile it, move it into another algebra, and evaluate it as a torch module.
- class Circuit(structure: str | AlgebraicStructure)[source]
Circuit implementation using an internal graph for efficient construction.
Conversion to torch modules happens via to_module(), which evaluates the circuit as written — in the semiring Klay implements for its structure, or node by node through the structure’s own
operator_fns.Create a circuit configured for the given structure.
The circuit is evaluated as written: its operators mean what the structure’s
operator_fnssay they mean.- Parameters:
structure – The algebraic structure (name or AlgebraicStructure instance).
- property structure: AlgebraicStructure
Return the algebraic structure of this circuit.
Callers wanting the registry name use
circuit.structure.name.
- property leaf_nodes: dict[Symbol, int]
Mapping of leaf symbols to node IDs, keyed by their tagged name.
Leaves are stored bare; the keys here carry the circuit’s structure tag re-appended (
_tagged_leaf_name()), so a predicate leaf appears under its wrapped name — the spelling the module boundary matches on.
- get_leaf_name(node_id: int) Symbol | None[source]
Return the bare canonical leaf symbol for a node ID, or None.
This is the leaf’s identity with its redundant structure tag stripped. For the structure-tagged boundary spelling use
get_symbol_name()orleaf_nodes.
- get_symbol_name(node_id: int) Symbol | None[source]
Return the formula symbol represented by a leaf or constant node.
Both are stored bare and returned with the circuit’s tag re-appended, so formula-level views expose leaves and constants uniformly as atoms.
- reachable_leaf_names(roots: list[int]) list[Symbol][source]
Named leaves reachable from
roots, in topological order (no constants).The leaves-only boundary view as plain symbols. Contrast
reachable_symbol_names(), which also yields constants.
- reachable_symbol_names(roots: list[int]) list[Symbol][source]
Leaf and constant symbols reachable from
roots, in topological order.The generic boundary walk for formula-level views (
CircuitNodechildren): every named leaf and constant once. Contrastreachable_leaf_names(), which omits constants.
- get_leaf_node(name: Symbol) int[source]
Return a node ID for the given symbol, creating it if needed.
A structure-wrapped
name(("_", inner, (structure,))) must carry this circuit’s own structure, orValueErroris raised. The tag is then stripped and the bare inner symbol stored as the canonical leaf identity, so both spellings of an atom resolve to one shared node. Boundary views re-append the tag (_tagged_leaf_name()), so the module input shape still matches its predicate modules.
- get_operator(operator: str) Callable[[...], int][source]
Return a callable that applies the requested operator.
- Parameters:
operator – The operator name (e.g., “and”, “or”, “not”).
- Returns:
A callable that takes node IDs and returns a new node ID.
- operation(node_id: int) tuple[str, tuple[int, ...]][source]
What the node with the given ID is, and the nodes it applies to.
The first is an operator of the circuit’s structure, or
leaforconstant, which apply to no node.
- to_module( ) DeepLogModule[source]
Convert the circuit to a DeepLog module, evaluating it as written.
- Parameters:
roots – A dictionary mapping node IDs to output names.
- Returns:
A DeepLogModule wrapping the circuit as a torch module.
- class CircuitNode( )[source]
A graph-backed formula node — a handle into a circuit graph.
Pairs a
circuitwith thenodeid of one of its roots; this is the compressed counterpart to symbolicUnaryOp/BinaryOpstructure. It lives in the AST (a member ofFormulaNode) but its fine internal structure — the booleanand/or/notgraph — lives in the circuit, not as nested dataclass objects.The compressed chunk has a boundary: the leaf / constant symbols reachable from
node. Each boundary symbol feeds a child formula, andfeedersrecords the non-trivial ones as aname → childmapping. A symbol absent fromfeedersfeeds itself asAtom(name)— so the default emptyfeedersis the identity boundary (every leaf feeds its own atom), reproducing the plain leaf view. A non-identity entry makes the boundary symbolic: a leaf can be fed by an arbitrary sub-formula — including one in a different algebraic structure — without re-materializing the circuit.Pure, frozen, value-keyed data like its symbolic siblings: the boundary map is part of value identity (
feedersis a hashable tuple of pairs), so two lumps over the same circuit node with different feeders are distinct nodes.- property structure: str
The algebraic structure name of the backing circuit.
- property children: tuple[Atom | UnaryOp | BinaryOp | Transformation | AggregationOp | Aggregation | CircuitNode, ...]
Boundary children of this compressed AST chunk.
A
CircuitNodecompresses a whole circuit subgraph, so its formula children are what feeds that subgraph’s boundary, inboundary’s order, not the direct graph-node successors.
- property boundary: tuple[tuple[Symbol, Atom | UnaryOp | BinaryOp | Transformation | AggregationOp | Aggregation | CircuitNode], ...]
Each leaf / constant symbol reachable from
node, with the child feeding it.The symbols come in the circuit’s deterministic topological order, each fed by its
feedersoverride or, by default, its identityAtom, which may name it otherwise: anAtomholds=with the variable first.Cached: computing it walks the whole reachable subgraph and allocates an
Atomper boundary symbol, yet it is read by every walk that reaches the lump throughchildren(), the lowering’s among them. Caching also keeps the identity of thoseAtom``s stable for as long as the lump lives, which the lowering's identity-keyed bookkeeping relies on. Reachability from a fixed node never changes — a circuit only ever grows new nodes — so the cache cannot go stale. (``cached_propertywrites straight into__dict__, so it works on this frozen dataclass, and neither__eq__nor__hash__consults it.)
- knowledge_compile(
- circuit: Circuit,
- roots: list[int],
- *,
- variables: VariableAtoms | None = None,
- structure: str | AlgebraicStructure | None = None,
- leaf_mapping: Callable[[Symbol], Symbol] | None = None,
Rewrite
rootsinto a deterministic, decomposable circuit.Returns
(new_circuit, node_map)— the same contract astransform_circuit(), and composable with it. All roots are compiled together, so what they share stays shared.structureis the algebra to emit into, the source’s own by default. The rewrite preserves roles, so emitting into another algebra applies that algebra’s product, sum and complement to the same diagram — which is what transforming the compiled circuit afterwards would have done, without building it.leaf_mappingrenames each atom on the way, as that transform would have.variablessays where each variable occurs. The compiler follows from that rather than from a caller’s choice: a plain SDD has only two-valued variables, so a variable two or more of whose values the formula reaches needs the multi-valued one, or two of those atoms could hold at once. A variable the formula reaches at most one value of is a plain SDD variable, its remaining values being the one residual an SDD already reads as the complement.
- transform_circuit(
- source: Circuit,
- target_structure: str | AlgebraicStructure,
- roots: list[int],
- *,
- operator_mapping: dict[str, str] | None = None,
- leaf_mapping: Callable[[Symbol], Symbol] | None = None,
- into: tuple[Circuit, dict[int, int]] | None = None,
Transform a circuit to a different algebraic structure.
Creates a new circuit with the target structure by traversing the source circuit and rebuilding each node with mapped operators, leaves, and constants.
The map is exact only insofar as the source’s operators mean in the target what they meant at home. Reading a logical circuit’s
oras a semiring sum requires the source to be deterministic and decomposable, which is whatknowledge_compile()produces.- Parameters:
source – The circuit to transform.
target_structure – The target algebraic structure (name or instance).
roots – Root node IDs defining the subgraph to transform.
operator_mapping – Explicit mapping from source operator names to target operator names, replacing the inferred one. If None, the mapping is inferred from the roles both structures declare (product→product, sum→sum, negation→negation, division→division); an operator the target has no role for raises when a node uses it.
leaf_mapping – Optional callable to remap leaf symbols.
into – An existing
(target_circuit, node_map)to continue transforming into, instead of allocating a fresh target. Source nodes already innode_mapare skipped, so repeated calls sharing one target accumulate and deduplicate exactly as a single multi-root call would. Thenode_mapis mutated in place and returned. Its target structure must matchtarget_structure.
- Returns:
A tuple of (new_circuit, node_map) where node_map maps source node IDs to their corresponding IDs in the new circuit.
deeplog.grounding.prolog
The Prolog grounder: programs, the grounders that prove them, and Prolog terms.
- Builtin = Builtin
A builtin enumerates answer substitutions for a goal’s arguments.
- create_query(body_atoms: list[str] | list[Symbol]) RuleType[source]
Create a query
false ?- b1 , ... , bm.
- create_rule( ) RuleType[source]
Create a rule
h1 ; ... ; hn <functor> b1 , ... , bm.An empty head folds to
FalseSymboland an empty body toTrueSymbol, so facts (empty body) and constraints (empty head) are just special cases.
- get_constraint_body(rule: RuleType) Symbol[source]
Return the body of an integrity constraint
:- body.
- class JanusGrounder[source]
A Prolog grounder based on a meta-prover implemented with SWI-Prolog Janus.
Initialize a Janus-backed grounder and ensure the Prolog code is loaded.
- ground(
- program: Program,
- goal: Symbol,
- open_predicates: OpenPredicates = frozenset({}),
Prove
goalinprogramto one proof formula per ground answer.The proof tables the goals it proves, and drops the tables when it ends, with every other private table of the calling Prolog thread.
- class JanusNotAvailableException[source]
Raised when a Janus prover is built but janus_swi is unavailable.
- class JanusProver(module_file: Path)[source]
A prover written as an SWI-Prolog module, run through Janus.
Load the prover in
module_file, unless it is loaded already.The file is an SWI-Prolog module. It reaches DeepLog’s Prolog library with
:- use_module(deeplog(grounding)).- Raises:
JanusNotAvailableException –
janus_swicannot be imported.
- add_builtin(functor: str, arity: int, builtin_function: Builtin) None[source]
Make
functor/aritya builtin of the goals this prover runs.
- consult(clauses: Iterable[str]) str[source]
Load
clauses, in order, into a module of their own, and return its name.The module is named after the clauses, so the same clauses load once. Loading them reports no singleton variables.
- query( ) Iterator[dict[str, Any]][source]
The solutions of
goal, run in the prover’s module.A goal that reaches
unknown_predicate/1raisesUnknownPredicateException, one that reachesnon_ground_open_predicate/1raisesValueError, and one that runs out of Prolog’s memory, such as its stack limit, raisesMemoryError.
- OpenPredicates = OpenPredicates
The set of open (leaf) predicates, keyed by
(functor, arity).
- Program = Program
The clauses a grounder proves against, in the order they were written.
- class PrologGrounder[source]
Abstract plain-Prolog grounder: proves a goal to a per-answer proof formula.
- abstractmethod ground(
- program: Program,
- goal: Symbol,
- open_predicates: OpenPredicates = frozenset({}),
Prove
goalinprogramand return one proof formula per ground answer.A proof formula is a boolean formula of
and/or/notover leaf atoms, andtruefor an answer proven without one.open_predicatesnames the predicates whose facts become leaf atoms rather than resolving totrue.
- RuleType = RuleType
A clause as a
(functor, head, body)triple, the functor saying whether it is a rule, a query or a constraint.
- class SimpleGrounder[source]
A simple memoizing Prolog grounder without any dependencies.
Create an in-process Prolog-like grounder.
- ground(
- program: Program,
- goal: Symbol,
- open_predicates: OpenPredicates = frozenset({}),
Prove
goalinprogramto one proof formula per ground answer.- Raises:
RecursionError – If a goal calls a variant of itself, as the goals of
e(X,Y) :- e(X,Z), e(Z,Y).do. Resolution alone cannot prove such a program;JanusGroundertables its calls and proves it.
- split_list(term: Symbol) tuple[list[Symbol], Symbol][source]
Return the elements of the list
termand the tail they end in.A list is a
cons/nilchain, so[a, b]is([a, b], nil),[a | T]is([a], T), and a term that is not a list is([], term).
- str_to_rules(code: str) Iterable[RuleType][source]
Parse a plain-Prolog program; clauses may share a line.
- symbol_to_prolog_str(symbol: Symbol) str[source]
Convert a Symbol to a valid Prolog term string using strict prefix notation.
Translates
cons/nilchains (deeplog’s internal list encoding) to Prolog list syntax[h1, h2, ... | tail]so SWI list builtins likenth0/3andmember/2operate on them.
- class UnknownPredicateException[source]
Raised when a goal’s predicate has no clauses, builtin, or open declaration.