Skip to main content

A pure-Python (+numpy) byte-graph that is a 1-bit (ternary) LLM: dunder API, autograd, ultra-edges, visualization.

Project description

ultragraph

CI python license

A pure-Python (+ numpy) byte-graph that is a 1-bit (ternary) LLM.

genesis 251e6ea · themed after pocoo.vaked.dev

ultragraph architecture — micro (node/edge, 1 byte each) → meso (tree) → macro (ultra-graph)

Three levels:

level unit storage
micro node / edge 1 byte eachint8 activation / ternary weight {-1,0,+1}
meso tree a whole graph == one net/module (a Linear/MLP block)
macro ultra-edge (===) typed wiring between trees → the ultra-graph = the model

Weights are ternary (BitNet b1.58 style); activations are int8. Full-precision "master" weights live in an ad-hoc side store during training; the byte buffers are the deployed state. Training uses a straight-through estimator (STE).

Illustrations

Real outputs from a trained ternary mini-GPT — regenerate with uv run python assets/make_figures.py:

ultra-graph causal attention ternary weight bytes
architecture attention weights

Left: the model as an ultra-graph — trees wired by ultra-edges (===), with residual skips. Middle: real causal self-attention weights (lower-triangular → no peeking at the future). Right: a trained query projection's weight bytes, each ∈ {−1, 0, +1}.

Install

pip install ultragraph-1bit    # then: import ultragraph
# or from source (Python >=3.11):
uv sync

Dunder API

>> is overloaded by operand type:

import numpy as np
from ultragraph import Tree, UltraGraph, Tensor, mlp, SGD

# micro-edges inside a sparse tree
g = Tree(4, "g")
g[0] >> g[1]        # node >> node  -> micro-edge
g[2] = 7            # set a node byte
print(len(g), 2 in g, list(g))

# ultra-edges between trees
ug = UltraGraph()
a = ug.add(Tree.dense(8, 16, "a"))
b = ug.add(Tree.dense(16, 4, "b", act="none"))
a >> b              # tree >> tree -> ultra-edge (plain)
a.wire(b, "residual")

Train a tiny ternary net

ug = mlp([4, 16, 2])                 # dense ternary linear trees wired plain
opt = SGD(ug, lr=0.3, momentum=0.9)
x = Tensor(np.random.randn(32, 4).astype("float32"))
for _ in range(300):
    loss = ug.forward(x).cross_entropy(y)
    opt.zero_grad(); loss.backward(); opt.step()   # step() re-quantizes weights

See examples/char_lm.py (MLP LM), examples/transformer_lm.py (single-head attention), and examples/mini_gpt.py (batched multi-head attention + RMSNorm + Adam) for end-to-end char-level ternary language models.

from ultragraph import Embedding, MultiHeadAttention, RMSNorm, linear_tree, Adam
# pre-norm transformer block over a [B, T, d_model] sequence:
#   x = x + mha(norm1(x));  x = x + ff2(ff1(norm2(x)))

A whole ternary GPT

from ultragraph import GPT

m = GPT(vocab=256, d_model=128, n_layers=4, n_heads=4, max_len=256)  # RoPE + KV-cache
logits = m(ids)                       # ids [B, T] -> logits [B, T, vocab]
out = m.generate([72, 105], n_new=64, temperature=0.8, top_k=40, seed=0)

generate decodes with a per-layer KV-cache; since activations are quantized per token, a cached step is byte-for-byte the full-forward result at that position. Positions come from RoPE (rotary embeddings) — relative, and offset-aware so they line up across cached steps.

Tasks

just test        # pytest
just test-fast   # dependency-free runner (stdlib + numpy)
just demo        # char-LM end-to-end
just viz         # render example SVGs

Layout

ultragraph/quant.py     ternary + int8 quantization, STE
ultragraph/autograd.py  numpy autograd tape; ternary_linear (STE); exp/tanh/sigmoid/gelu/silu
ultragraph/core.py      Node/Edge/Tree/UltraEdge/UltraGraph + dunder API
ultragraph/nn.py        linear_tree, mlp, Attention, MultiHeadAttention, RoPE, RMSNorm, LayerNorm, LearnedPositionalEmbedding, MoE, Dropout, Sequential
ultragraph/model.py     TransformerBlock + GPT (embedding + RoPE + pre-norm blocks + ternary head) with cached .generate()
ultragraph/optim.py     SGD + Adam (grad clip, weight decay) + CosineSchedule, re-quantize after step
ultragraph/pack.py      dense ternary bit-packing (5 values/byte, ~1.58-bit)
ultragraph/tokenize.py  byte-level tokenizer (ByteTokenizer, vocab 256)
ultragraph/vaked.py      optional vaked lowering (lower_graph, compile_vaked via vendored vakedc)
ultragraph/viz/         svg.py (pure-SVG) + mpl.py (optional matplotlib) — micro / macro / byte-heatmap
ultragraph/io.py        byte-exact save / load (optional packed weights); save_params/load_params

Design spec: docs/superpowers/specs/2026-07-10-ultragraph-design.md. Graph-theory reading list (Erdős classics): docs/references.md.

Install from source

git clone https://github.com/peterlodri-sec/ultra-graph
cd ultra-graph
uv sync
just test

License

MIT — see LICENSE.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

ultragraph_1bit-0.7.0.tar.gz (4.7 MB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

ultragraph_1bit-0.7.0-py3-none-any.whl (31.5 kB view details)

Uploaded Python 3

File details

Details for the file ultragraph_1bit-0.7.0.tar.gz.

File metadata

  • Download URL: ultragraph_1bit-0.7.0.tar.gz
  • Upload date:
  • Size: 4.7 MB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for ultragraph_1bit-0.7.0.tar.gz
Algorithm Hash digest
SHA256 c7401a59550d11f29fb31151bd8085e1b8956c31e2151948b8ae833500c03205
MD5 b9c4b28750630dac1dd2e804f269b0e8
BLAKE2b-256 d49737be6b2402b6d6e167c23d6a0022549a05d6f5bc6a404653ef4f8842b5eb

See more details on using hashes here.

Provenance

The following attestation bundles were made for ultragraph_1bit-0.7.0.tar.gz:

Publisher: publish.yml on peterlodri-sec/ultra-graph

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file ultragraph_1bit-0.7.0-py3-none-any.whl.

File metadata

  • Download URL: ultragraph_1bit-0.7.0-py3-none-any.whl
  • Upload date:
  • Size: 31.5 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for ultragraph_1bit-0.7.0-py3-none-any.whl
Algorithm Hash digest
SHA256 987cb1d96753813f32d5da6eda9e9e655c518e1de52a693a55bdc001c634aa7f
MD5 6d6afbadd57edeb445af38442fb5382d
BLAKE2b-256 35ead6785f318477b6c8c95e45759ee6ca376f0da4198f357705461142b667cd

See more details on using hashes here.

Provenance

The following attestation bundles were made for ultragraph_1bit-0.7.0-py3-none-any.whl:

Publisher: publish.yml on peterlodri-sec/ultra-graph

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page