Skip to main content

Pylon: A PyTorch Framework for Learning with Constraints

Dependencies

  • Python >= 3.6
  • torch>=1.9.0
  • astor

Installation

Optional, set up virtualenv:

python3 -m venv /path/to/env
source /path/to/env/bin/activate

Install using pip:

pip install pylon-lib

Alternatively, compile from source:

git clone https://github.com/pylon-lib/pylon.git
cd pylon
python3 -m pip install --upgrade pip
pip install flake8 pytest
pip install -r requirements.txt

Make sure to install PyTorch: https://pytorch.org

Basic Example

Our goal is to enforce the XOR constraint on the output of a simple classifier: only one of the outputs can be "on" i.e. set to 1

import torch
import torch.nn.functional as F

class Net(torch.nn.Module):
    def __init__(self, w=None):
        super().__init__()
        if w is not None:
            self.w = torch.nn.Parameter(torch.tensor(w).float().view(6, 1))
        else:
            self.w = torch.nn.Parameter(torch.rand(6, 1))

    def forward(self, x):
        return torch.matmul(self.w, x).view(3, 2)

We define our constraint funciton

from pylon.constraint import constraint
from pylon.brute_force_solver import SatisfactionBruteForceSolver

# Our constraint function accepts a decoding tensor of
# shape (batch_size, ...) and is expected to return
# a tensor fo shape (batch_size, )
def xor(y):
    return y[:, 0] != y[:, 1] and y[:, 1] != y[:, 2]
    
xor_cons = constraint(xor, SatisfactionBruteForceSolver())

And proceed to our training loop

# Create network and optimizer
net = Net()
opt = torch.optim.SGD(net.parameters(), lr=0.1)

# Input and label
x = torch.tensor([1.])
y = torch.tensor([0, 0, 1])

# training loop
y0, y1, y2 = [], [], []
for i in range(500):
    opt.zero_grad()
    y_logit = net(x)
    loss = F.cross_entropy(y_logit[2:], y[2:])
    loss += xor_cons(y_logit.unsqueeze(0)) #Pylon expect tensors of shape (batch_size, ...)
    loss.backward()
    y_prob = torch.softmax(y_logit, dim=-1)
    y0.append(y_prob[0,1].data); y1.append(y_prob[1,1].data); y2.append(y_prob[2,1].data)
    opt.step()

import matplotlib.pyplot as plt
plt.plot(y0, label='y0')
plt.plot(y1, label='y1')
plt.plot(y2, label='y2')
plt.legend()

Image

Release files for pylon-lib 0.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for pylon-lib 0.1.0
File Size Uploaded
pylon-lib-0.1.0.tar.gz 22.4 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for pylon-lib 0.1.0
File Interpreter ABI Platform
pylon_lib-0.1.0-py3-none-any.whl Python 3 none any Details

Total release size:46.7 kB

Release files / pylon-lib-0.1.0.tar.gz

Download URL pylon-lib-0.1.0.tar.gz
Size 22.4 kB
Tags Source
SHA-256 checksum
How to use checksums
03cad55ad255d8a4be1d2bcf5a9c09078b47bed5fc5d19d41abfbece5d829ed7
BLAKE2b-256 checksum
How to use checksums
c5b4c168140a45e185413ef8c0e49953f7236be7745ed62080d83dfb250d6243
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/3.4.2 importlib_metadata/4.8.1 pkginfo/1.7.1 requests/2.26.0 requests-toolbelt/0.9.1 tqdm/4.62.3 CPython/3.9.7

Release files / pylon_lib-0.1.0-py3-none-any.whl

Download URL pylon_lib-0.1.0-py3-none-any.whl
Size 24.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
91d6baeb9558e857acbb8b6b97b89df97b12da7f08b25c39bd146b3b52852d6e
BLAKE2b-256 checksum
How to use checksums
df085b6447ec3902bd95dbcffa1d4034c08b5659eb0758e8cfc2876ff3cb4f16
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/3.4.2 importlib_metadata/4.8.1 pkginfo/1.7.1 requests/2.26.0 requests-toolbelt/0.9.1 tqdm/4.62.3 CPython/3.9.7

Release history Release notifications | RSS feed

This release

0.1.0 This release

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page