Skip to content

pysignet

pysignet logo

GitHub

CI

pysignet is a PyTorch library that converts symbolic predicate logic expressions (written in SymPy notation) into differentiable loss functions, enabling you to train neural networks with logical constraints using First-Order Logic (FOL). It bridges symbolic reasoning and gradient-based optimization so that logical rules like implication, mutual exclusion, or quantified constraints become training signals.

Quick Start

Let us look at an example first. We will define a logical constraint in SymPy notation, map each predicate symbol to a neural network, and compile it into a differentiable loss whose gradients flow back through the logic to every model involved.

import torch
import torch.nn as nn
from pysignet import Symbol, Variable, Implies, logic_to_loss

# Define predicate symbols and FOL variables
P, Q = Symbol("P Q")
X = Variable("X")

# "For all inputs X: if P(X) then Q(X)"
expr = Implies(P(X), Q(X))

# Map symbols to neural network models
model_p = nn.Sequential(nn.Linear(10, 1), nn.Sigmoid())
model_q = nn.Sequential(nn.Linear(10, 1), nn.Sigmoid())

predicates = {
    "P": model_p,
    "Q": model_q,
}

# Compile to a loss function
logic_loss = logic_to_loss(expr, predicates)

# Training loop
x = torch.randn(32, 10)
loss = logic_loss.loss(X=x)   # Bind X to x to get a scalar loss
loss.backward()               # Gradients flow to both models

Installation

pip install pysignet

Or with Poetry:

poetry add pysignet

Next Steps