Skip to main content

Thoughtformula 🧠

Pure-Python generative Transformer architecture featuring FlashAttention online softmax tiling, vLLM-style Paged KV-Cache, BitNet b1.58 ternary quantization, Grouped Query Attention (GQA), Rotary Positional Embeddings (RoPE), Sparse Mixture of Experts (MoE SwiGLU), LoRA continual learning, Kahneman-Tversky Optimization (KTO), Medusa speculative decoding, persistent binary index (.tfidx), and continuous batching. Built exclusively with Python standard library built-ins.

Tests Python Dependencies Version


Key Features

  • Standard Library Autograd (FlatTensor): 1D contiguous float64 training buffer with symmetric Int8 inference quantization, BitNet b1.58 ternary quantization, and reverse-mode automatic differentiation.
  • FlashAttention Online Softmax Tiling: Dao et al. streaming online softmax eliminates $T \times T$ attention matrix materialization, maintaining $O(N)$ memory across long context windows.
  • vLLM-Style Paged KV-Cache (PagedKVCache): Fixed-size physical memory pages (e.g., 16 tokens/block), block allocator, and page tables supporting non-contiguous allocation and $O(1)$ prompt prefix sharing.
  • BitNet b1.58 Ternary Quantization: Weights in ${-1, 0, 1}$ with scale $\gamma = \text{mean}(|W|)$, 2-bit bitpacking (4 weights/byte), and addition-only matrix multiplication.
  • Kahneman-Tversky Optimization (KTO): Unpaired binary human preference alignment (q :: a ++ and q :: a --) using prospect theory utility loss and frozen base Int8 weights as reference.
  • Interactive Streaming Token Generator: Real-time typewriter output streaming via generate_stream(), generate_speculative_stream(), and generate_medusa_stream().
  • Medusa Multi-Head Speculative Drafter: Lightweight auxiliary heads predicting multiple future tokens simultaneously directly from the final hidden state without extra transformer layers.
  • Persistent Binary Index Format (.tfidx): High-performance binary container persisting precomputed dense embeddings and term inverted postings for large-scale hybrid RAG retrieval.
  • Continuous Batching Engine (ContinuousBatchScheduler): Synchronous iteration-level continuous batcher packing active requests into unified forward passes, amortizing parameter loading across concurrent sessions.
  • C-Speed Matrix Multiplication: Accelerated with compiled C math.sumprod over contiguous transposed weight slices (5x-12x pure-Python speedup).
  • Grouped Query Attention (GQA) & Precomputed RoPE: Memory-efficient query/key-value head grouping with precomputed cos_cache / sin_cache trigonometric lookup tables.
  • Sparse Mixture of Experts (MoE): 4 SwiGLU experts with true sparse token dispatch and Switch Transformer auxiliary load-balancing loss preventing expert collapse.
  • Zero-Memory Direct Preference Optimization (DPO): Align model responses (q :: good || bad) using frozen Int8 base weights as reference policy $\pi_{\text{ref}}$ with 0 extra RAM.
  • Decoupled Weight Decay (AdamW): Bounded weight magnitudes preventing Int8 scale drift.
  • Lossless Speculative Decoding: Leviathan et al. (2023) rejection sampling with N-gram proposal distributions and Int8 KV-cache rollback.
  • Hybrid Dense + Lexical RAG: Okapi BM25 combined with mean-pooled tok_emb dense embeddings via Reciprocal Rank Fusion (RRF).
  • Binary .mgpt Container: Python standard library zipfile binary container eliminating 33% Base64 storage overhead.
  • Built-in Gradient Checker: Finite-difference calculus test harness (/test) verifying all analytical gradients to $< 10^{-10}$.

Quickstart

# Install via pip
pip install thoughtformula

# Run CLI directly
thoughtformula --benchmark

# Or run interactive typewriter REPL
thoughtformula

Run from Source

git clone https://github.com/wispsy/thoughtformula.git
cd thoughtformula

# Run speculative decoding benchmark
PYTHONPATH=src python3 -m thoughtformula.cli --benchmark

# Run interactive typewriter REPL
PYTHONPATH=src python3 -m thoughtformula.cli

REPL Commands & Syntax

Syntax Action
question? RAG retrieval + speculative decoding typewriter output
q :: answer Continual online LoRA adaptation
q :: good || bad Zero-Memory LoRA Direct Preference Optimization (DPO)
q :: answer ++ Kahneman-Tversky Optimization (KTO) Desirable feedback
q :: answer -- Kahneman-Tversky Optimization (KTO) Undesirable feedback
/test Run finite-difference calculus gradient verification
/merge Merge LoRA adapters into base weights
/stats Display model parameter count and cache metrics

Project Structure

thoughtformula/
├── pyproject.toml
├── README.md
├── docs/
│   ├── architecture.md
│   ├── modules.md
│   └── quickstart.md
├── src/
│   └── thoughtformula/
│       ├── __init__.py
│       ├── batching.py
│       ├── cache.py
│       ├── cli.py
│       ├── draft.py
│       ├── gradcheck.py
│       ├── medusa.py
│       ├── micro_gpt_checkpoint.json
│       ├── micro_gpt_v8.py
│       ├── model.py
│       ├── rag.py
│       ├── tensor.py
│       ├── tokenizer.py
│       └── training.py
└── tests/
    ├── test_batching.py
    ├── test_cache.py
    ├── test_draft.py
    ├── test_gradcheck.py
    ├── test_medusa.py
    ├── test_model.py
    ├── test_rag.py
    ├── test_tensor.py
    ├── test_tokenizer.py
    └── test_training.py

Running Tests

All 64 unit tests run using Python's built-in unittest framework with zero external dependencies:

PYTHONPATH=src python3 -m unittest discover tests

License

MIT

Metadata

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

Built distribution (wheel)

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

Total release size: 158.7 kB

Release files / thoughtformula-0.3.0.tar.gz

Download URL thoughtformula-0.3.0.tar.gz
Size 78.1 kB
Tags Source
SHA-256 checksum
How to use checksums
ca181c7e48d32b20312aa0702ed00db4abbc7d273e17bb794a9897f65fb1fea2
BLAKE2b-256 checksum
How to use checksums
d98f2e53a0e93c2ded8f33790dd1163a63bd4036016c772b4cfea6b28686886d
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

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 Nov 17, 2026.

Transparency log

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

Download URL thoughtformula-0.3.0-py3-none-any.whl
Size 80.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
dc39cfad430ac86ea933cf116d4ed264c347eb98cedd9162e21f729265d4eacb
BLAKE2b-256 checksum
How to use checksums
68474b28e5536a49be8700a3c38f0e97904c4a99d80cf3793274edcb31b29823
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

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 Nov 17, 2026.

Transparency log

Security for thoughtformula 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 thoughtformula-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 Nov 17, 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.

Release history Release notifications | RSS feed

This release

0.3.0 This release

2 release files Full provenance

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