Skip to main content

torchtsetlin

GPU-enabled, PyTorch-native Tsetlin machines — models, data preparation, training, evaluation, interpretation and visualisation in one package.

CI docs license

A Tsetlin machine learns propositional rules (IF x0 AND NOT x1 THEN class 1) with teams of learning automata instead of gradients. torchtsetlin implements the family as ordinary torch.nn.Modules: the automata live in tensors, so a model moves between CPU and GPU with .to(device), is saved with state_dict(), and learns from mini-batches with a single model.update(x, y) call.

import torchtsetlin as tt

x_train, y_train = tt.data.make_noisy_xor(5000, noise=0.4)          # Boolean features, int labels
x_test, y_test = tt.data.make_noisy_xor(2000, noise=0.0, seed=1)

model = tt.TsetlinMachine(n_features=12, n_classes=2, n_clauses=20, T=15, s=3.9).to("cuda")

# PyTorch-style loop: update() is the analogue of loss.backward(); optimizer.step()
for epoch in range(50):
    model.train()
    for i in range(0, 5000, 10):
        model.update(x_train[i:i+10].cuda(), y_train[i:i+10].cuda())
    model.eval()
    acc = (model(x_test.cuda()).argmax(1) == y_test.cuda()).float().mean()

print(model.rules()[:2])   # ['IF x0 AND NOT x1 THEN 1', 'IF x1 AND NOT x0 THEN 1']

Or with the built-in trainer:

trainer = tt.Trainer(model, batch_size=10, callbacks=[tt.EarlyStopping(patience=20)])
trainer.fit((x_train, y_train), epochs=100, val_data=(x_test, y_test))
trainer.evaluate((x_test, y_test))          # {'accuracy': 0.99}

Features

Models TsetlinMachine (multi-class, optional integer clause weights), CoalescedTsetlinMachine (shared clauses; multi-class or multi-label), RegressionTsetlinMachine, ConvTsetlinMachine / Conv1dTsetlinMachine and convolutional coalesced / regression variants, SegmentationTsetlinMachine / CoalescedSegmentationTsetlinMachine for dense per-pixel prediction
Learning vote margin T, specificity s, memory depth, boosted true-positive feedback, clause-size constraint, drop-clause / drop-literal, focused negative sampling, batched (GPU-friendly) or exact sequential feedback
Data thermometer, one-hot, bit-plane, adaptive-threshold, colour-thermometer, hypervector and multi-scale pyramid encoders; synthetic datasets (including segmentation scenes); torchvision helpers for classification and segmentation
Training Trainer for tensors / Dataset / DataLoader, callbacks (early stopping, checkpoints, CSV logs, hyper-parameter schedules), History
Evaluation accuracy, confusion matrix, precision/recall/F1, regression and multi-label metrics, IoU / Dice / pixel accuracy / boundary-F1 for segmentation, calibration, trustworthiness curves
Interpretation rule extraction, clause activity/precision, closed-form global & local feature importance, per-example and per-pixel explanations
Visualisation memory plots, automata heat-maps, convolutional clause patches, segmentation overlays and vote maps, confusion matrices, vote distributions

Installation

pip install torch            # pick the CUDA/CPU build from pytorch.org
pip install torchtsetlin     # + optional extras: [viz] [vision] [sklearn] [docs] [all]

From source: pip install -e ".[dev]", then pytest and mkdocs serve.

How learning works (in one paragraph)

Each clause is an AND of literals (x_k or NOT x_k); every (clause, literal) pair has a Tsetlin automaton whose integer state decides whether the literal is included. For a training example, clauses of the true class receive Type I feedback (memorise the example's True literals, forget the rest) and clauses of a random other class receive Type II feedback (add a False literal so the clause stops matching), each with a probability controlled by the vote margin T. torchtsetlin evaluates a mini-batch with one matrix product, counts the feedback events per (clause, literal) with another, and turns the counts into binomial state transitions — the whole update is a handful of tensor ops. See the concept pages for details and references.

Documentation

  • Getting started, concepts, guides, examples and the full API reference: https://vlbthambawita.github.io/torchtsetlin/ (or mkdocs serve locally).
  • Measured CPU vs GPU performance (throughput, scaling, memory, where the time goes): Benchmarks -> CPU vs GPU; the harness lives in benchmarks/.
  • Runnable scripts in examples/ (see its README): Noisy XOR, tabular data with thermometer encoding, regression, MNIST flat and convolutional, four convolutional walkthroughs covering 2-D clauses (shapes_conv.py), 1-D signals (conv1d_ramps.py), convolutional regression (conv_regression_blobs.py) and shared clause pools (mnist_conv.py --coalesced), and semantic segmentation on generated street scenes (segmentation_scenes.py).
  • Worked notebooks in examples/notebooks/: Iris (rules you can read), MNIST (convolutional clauses and GPU throughput) and CIFAR-10 (booleanizing colour images), plus two that work through the Tsetlin-machine segmentation literature — the Convolutional Regression TM (ICMLT 2021) and CTM-UNet (ISTM 2025), the latter building a dense per-pixel Tsetlin segmentation head.

Citation

If you use torchtsetlin in research, please cite the Tsetlin machine papers whose algorithms you rely on (see the documentation) and this package:

@software{torchtsetlin,
  author = {Thambawita, Vajira},
  title  = {torchtsetlin: GPU-enabled, PyTorch-native Tsetlin machines},
  year   = {2026},
  url    = {https://github.com/vlbthambawita/torchtsetlin}
}

License

MIT — see LICENSE.

Metadata

Release files for torchtsetlin 0.3.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 torchtsetlin 0.3.0
File Size Uploaded Provenance Actions
torchtsetlin-0.3.0.tar.gz 83.1 kB With provenance Details for torchtsetlin-0.3.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for torchtsetlin 0.3.0
File Interpreter ABI Platform Actions
torchtsetlin-0.3.0-py3-none-any.whl Python 3 none any Details for torchtsetlin-0.3.0-py3-none-any.whl

Total release size: 162.1 kB

Release files / torchtsetlin-0.3.0.tar.gz

Download URL torchtsetlin-0.3.0.tar.gz
Size 83.1 kB
Tags Source
SHA-256 checksum
How to use checksums
c0e74396ca01b1c3be938dbd95c730bea1a07722604527be7ef3186d74bf4d63
BLAKE2b-256 checksum
How to use checksums
40d182d6a199150f145c09609e4030ea1cc80e2730e5ee5dd03693a267543510
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 1, 2026.

Transparency log

Release files / torchtsetlin-0.3.0-py3-none-any.whl

Download URL torchtsetlin-0.3.0-py3-none-any.whl
Size 79.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
31bfb71a27674c4dbb94f6f23e6748bad0ae5f4fc8e9fb8b83372b2e098ad68c
BLAKE2b-256 checksum
How to use checksums
a7c79bf7e83fc51af7711d5042ae9b6be9142a31bb4ad8aa7b4e0b1c2b7da28b
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 1, 2026.

Transparency log

Security for torchtsetlin 0.3.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for torchtsetlin-0.3.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 1, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

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