Skip to main content

juzhen for Python

Python interface to Juzhen, a small, readable C++ library of matrices and neural networks.

pip install pyjuzhen

No compiler is needed on Windows (x64), Linux (x64) and macOS on Apple silicon, with Python 3.9 to 3.15. The package is called pyjuzhen; the module is juzhen. It computes on the CPU, and on the GPU through Metal on a Mac.

With an NVIDIA card on Linux, install the CUDA package instead:

pip install pyjuzhen-cu12

It is the same module with device="gpu" on CUDA. It needs the NVIDIA driver and nothing else: pip brings the CUDA 12 libraries along as NVIDIA's own packages (about 1.4 GB). Install one of the two, not both: they are the same juzhen module. On a machine without the card it still imports and computes on the CPU. For CUDA on Windows or for ROCm, build from source (see Building).

import juzhen as jz

# the folder with datasets/MNIST/dataset.zip of the repository (not in the pip package)
X, Y, X_test, Y_test = jz.datasets.mnist("MNIST")  # one sample per row

model = jz.Sequential(jz.Dense(256, activation="relu"), jz.Linear(10))
model.fit(X, Y, epochs=3, lr=1e-3)
print(model.evaluate(X_test, Y_test))
  • @ is the matrix product and * is elementwise, as in numpy.
  • Data is one sample per row (N x d). Inside, the C++ layers see the same bytes as d x N, the layout they are written for, so nothing is copied or rearranged.
  • Matrices live in Juzhen's memory pool, on the CPU or with device="gpu" on the GPU backend of the build. Converting to or from numpy copies.
  • Reading values (.numpy(), .item(), print) waits for the GPU.
  • Comparisons work element by element and give a matrix of 1s and 0s: (A > 0) * A, jz.mean(A == B). A numpy array has to be made a matrix first (jz.array(y)); for the accuracy of a classifier use 1 - jz.nn.error_rate(scores, labels).
  • A 1 x 1 matrix can be used as its number: f"{jz.mean(A):.3f}", float(), round(), if jz.max(A) > 1:.
  • Every function of one matrix is also a method: A.sum(0) is jz.sum(A, 0), A.exp() is jz.exp(A). Results keep two dimensions (A.sum(1) is n x 1).
  • Whole numbers are numpy arrays of integers: class numbers, token ids, and the positions from jz.argmax and jz.topk. jz.argmax(scores) can index (names[p[0]], X[p]) and be compared with labels (np.mean(jz.argmax(scores) == y)).
  • Numbers are juzhen matrices. Whole numbers that name things are numpy integer arrays or lists: class numbers for a loss (model.fit(X, y) with y holding 0..9 works; one-hot rows still do too) and token ids for a network that starts with nn.Embedding.
  • Weights start at a scale that trains: N(0, 2/fan_in) in front of a ReLU, N(0, 1/fan_in) otherwise, zero biases. init= on a layer overrides it with a standard deviation.

A language model on token ids is an ordinary Sequential. This one learns to continue a repeating sequence, with the training step written out:

import numpy as np
import juzhen as jz
from juzhen import nn, optim

vocab, seq_len, batch = 16, 8, 32
device = "gpu" if jz.has_gpu() else "cpu"
model = nn.Sequential(
    nn.Embedding(vocab, 64),             # token ids -> vectors
    nn.PositionEmbedding(seq_len),       # + a learned vector per position
    nn.Transformer(64, 64, 256, seq_len, batch, heads=4),
    nn.LayerNorm(),
    nn.Linear(vocab, tied=True),         # scores from the embedding table
    device=device)
opt = optim.AdamW(model.parameters(), lr=3e-3)

rng = np.random.default_rng(0)
for step in range(200):
    start = rng.integers(0, vocab, (batch, 1))
    ids = (start + np.arange(seq_len + 1)) % vocab     # integers, shape (batch, seq_len + 1)
    out = model(ids[:, :-1])                           # one row of scores per token
    loss = nn.softmax_cross_entropy(out, ids[:, 1:])   # the targets are the next ids
    opt.zero_grad()
    model.backward(loss.grad)                          # no autograd: the loss hands over its gradient
    opt.step()
print(f"loss {loss:.3f}")

# After training: a copy of the weights as they are now, for one sequence at a
# time. The copy does not follow later training of `model`.
generator = model.copy(batch_size=1)
prompt = np.arange(3, 3 + seq_len)[None, :] % vocab
print("next token:", jz.argmax(generator.predict(prompt))[-1])   # 11

New to the library? Start with the notebook examples/tutorial.ipynb.

Performance notes

Every operator returns a new matrix: A @ B / n computes A @ B, then a second matrix for the division. The C++ library reuses the temporary in that case; Python cannot tell that A @ B is a temporary. On large matrices, scale or accumulate in place instead:

n = 2000
A1, A2, A3 = jz.randn(n, n), jz.randn(n, n), jz.zeros(n, n)

A3 += A1 @ A2 / n        # one extra matrix and pass over memory for "/ n"

C = A1 @ A2              # the same result without it
C /= n                   # in place: += and -= (a number or a matrix), *= and /= (a number)
A3 += C

On an RTX 4090 with 5000 x 5000 matrices the first form runs at 43 TFLOPS, the second at 46 TFLOPS, the speed of the C++ demo. Matrix products and the layers themselves run at the speed of C++.

@jz.compile does this for a whole function. The first call records the function's matrix operations; later calls run the record, in which an expression written twice is computed once and a result goes into a matrix that nothing reads again. The results have the same bits as without it (only a NaN may come out with the other sign).

@jz.compile
def step(W, X, Y, lr):
    P = jz.tanh(X @ W)
    E = P - Y
    W -= lr * (X.T @ (E * (1 - P * P))) / X.shape[0]
    return jz.mean(E * E)

W, X, Y = jz.randn(20, 3) * 0.1, jz.randn(64, 20), jz.randn(64, 3)
for _ in range(100):
    loss = step(W, X, Y, 0.1)
step.explain()           # the operations it runs: 5 new matrices in each call instead of 13

It gains the most for chains of + - * on large matrices (1.5 to 3 times at 4096 x 4096) and nothing where a matrix product or a network takes the time; python/benchmarks/compile_bench.py measures it. Networks, optimizers and losses can be used inside. A value cannot be read out of a matrix inside a compiled function (float(), .numpy(), if A > 0:): that would happen once, while recording, so it is an error that says what to write instead. Float arguments may change from call to call; for each new shape, and each new value of a whole-number argument, the function is recorded again. step.profile(W, X, Y, 0.1) prints the time each of its operations takes.

Reading a value back (.item(), .numpy()) waits for the GPU to finish, so in a training loop read the loss every few hundred steps rather than every step when speed matters.

Examples

The scripts in examples/ run on the GPU when the build has one; --device cpu (or cpu as the first argument of the fit_ ones) runs them on the CPU.

file what it shows C++ original
tutorial.ipynb a guided tour of the whole library, step by step
cifar_rectified_flow.ipynb an image generator on CIFAR-10: a UNet built from Sequential pieces, with a speed comparison against C++ demo_cnn_rectified.cu
helloworld.py matrix arithmetic on both devices helloworld.cu
fit_mnist.py fit() and evaluate()
fit_sin.py a hand-written training loop
demo_mnist.py an MLP on MNIST, step by step demo_mnist.cu
cnn_mnist.py convolutions on MNIST demo_cnn_mnist.cu
rectified_flow.py a generative flow; hstack, Euler sampling demo_rectified.cu
transformer_charlm.py a character transformer LM on token ids: Embedding, PositionEmbedding, a tied output, copy(batch_size=1) for generation demo_transformer.cu (one-hot), demo_llm_tokens.cu
knn.py k nearest neighbours with topk knn.cu

See misc/python_interface_plan.md for the design.

Building

The package is called pyjuzhen because the name juzhen on PyPI belongs to an unrelated project; do not install that one next to it. The wheels on PyPI are built by .github/workflows/wheels.yml. They do not contain the MNIST files: download datasets/MNIST/dataset.zip from this repository and give its folder to jz.datasets.mnist(path); a build from source finds it by itself.

To build from source, from the repository root:

pip install ./python                                   # CPU
pip install ./python -C cmake.define.NVIDIA_CUDA=ON    # CUDA
pip install ./python -C cmake.define.ROCM_HIP=ON       # ROCm
pip install ./python -C cmake.define.APPLE_SILICON=ON  # Metal
pytest python/tests

On Windows build from a Visual Studio developer prompt (MSVC).

Metadata

Release files for pyjuzhen-cu12 0.1.1

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

Built distributions (wheels)

Table of built distributions (wheels) for pyjuzhen-cu12 0.1.1
File Actions
pyjuzhen_cu12-0.1.1-cp315-cp315-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl CPython 3.15 CPython 3.15 Linux glibc 2.28+ x86-64, Linux glibc 2.27+ x86-64 Details for pyjuzhen_cu12-0.1.1-cp315-cp315-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl
pyjuzhen_cu12-0.1.1-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl CPython 3.14 CPython 3.14 Linux glibc 2.28+ x86-64, Linux glibc 2.27+ x86-64 Details for pyjuzhen_cu12-0.1.1-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl
pyjuzhen_cu12-0.1.1-cp313-cp313-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl CPython 3.13 CPython 3.13 Linux glibc 2.28+ x86-64, Linux glibc 2.27+ x86-64 Details for pyjuzhen_cu12-0.1.1-cp313-cp313-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl
pyjuzhen_cu12-0.1.1-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl CPython 3.12 CPython 3.12 Linux glibc 2.28+ x86-64, Linux glibc 2.27+ x86-64 Details for pyjuzhen_cu12-0.1.1-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl
pyjuzhen_cu12-0.1.1-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl CPython 3.11 CPython 3.11 Linux glibc 2.28+ x86-64, Linux glibc 2.27+ x86-64 Details for pyjuzhen_cu12-0.1.1-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl
pyjuzhen_cu12-0.1.1-cp310-cp310-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl CPython 3.10 CPython 3.10 Linux glibc 2.28+ x86-64, Linux glibc 2.27+ x86-64 Details for pyjuzhen_cu12-0.1.1-cp310-cp310-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl
pyjuzhen_cu12-0.1.1-cp39-cp39-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl CPython 3.9 CPython 3.9 Linux glibc 2.28+ x86-64, Linux glibc 2.27+ x86-64 Details for pyjuzhen_cu12-0.1.1-cp39-cp39-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl

Total release size: 96.4 MB

Release files / pyjuzhen_cu12-0.1.1-cp315-cp315-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl

Download URL pyjuzhen_cu12-0.1.1-cp315-cp315-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl
Size 13.8 MB
Tags CPython 3.15 Linux glibc 2.27+ x86-64 Linux glibc 2.28+ x86-64
SHA-256 checksum
How to use checksums
432b9356dfd845049512678b168bbf68731933875a08cf1b4464f568366f96dc
BLAKE2b-256 checksum
How to use checksums
3c97734df521012473005e112ef5070da041e3cdac9b0106db512b7aee226d31
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 29, 2026.

Transparency log

Release files / pyjuzhen_cu12-0.1.1-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl

Download URL pyjuzhen_cu12-0.1.1-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl
Size 13.8 MB
Tags CPython 3.14 Linux glibc 2.27+ x86-64 Linux glibc 2.28+ x86-64
SHA-256 checksum
How to use checksums
25b943c6f182af2fc8c44e4ccd5361840cf37ab3a1b9a90cd4c2b153d36066af
BLAKE2b-256 checksum
How to use checksums
ec5a607afc54fea9d55c730ccf813b4d708192252d9233c09b19c72649c1b402
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 29, 2026.

Transparency log

Release files / pyjuzhen_cu12-0.1.1-cp313-cp313-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl

Download URL pyjuzhen_cu12-0.1.1-cp313-cp313-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl
Size 13.8 MB
Tags CPython 3.13 Linux glibc 2.27+ x86-64 Linux glibc 2.28+ x86-64
SHA-256 checksum
How to use checksums
48a4639e97dc4349cc8b79172e16ac2e4fb188fdd7e29d33f3b8c0eefabac1ce
BLAKE2b-256 checksum
How to use checksums
a0cd1c966debdcb8fafe1895e0ce2c5368502f24e922e0b318cea661c298bd31
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 29, 2026.

Transparency log

Release files / pyjuzhen_cu12-0.1.1-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl

Download URL pyjuzhen_cu12-0.1.1-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl
Size 13.8 MB
Tags CPython 3.12 Linux glibc 2.27+ x86-64 Linux glibc 2.28+ x86-64
SHA-256 checksum
How to use checksums
785989d165a03d6141ee59ca2c8b5bb56e5bb08b735ba8cac97f014e2fe77075
BLAKE2b-256 checksum
How to use checksums
2991cd5345285efaa25b32999e3f5f4f66d6474564e4467124d1cc8b0245d402
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 29, 2026.

Transparency log

Release files / pyjuzhen_cu12-0.1.1-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl

Download URL pyjuzhen_cu12-0.1.1-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl
Size 13.8 MB
Tags CPython 3.11 Linux glibc 2.27+ x86-64 Linux glibc 2.28+ x86-64
SHA-256 checksum
How to use checksums
318cde80d83ffc9ba6bd4a847f02007d924c000e1c43116a475ca8a71b321099
BLAKE2b-256 checksum
How to use checksums
8653047b21ad1bff7f64af5c440763180bccd1163aaab546323feacb717350dd
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 29, 2026.

Transparency log

Release files / pyjuzhen_cu12-0.1.1-cp310-cp310-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl

Download URL pyjuzhen_cu12-0.1.1-cp310-cp310-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl
Size 13.8 MB
Tags CPython 3.10 Linux glibc 2.27+ x86-64 Linux glibc 2.28+ x86-64
SHA-256 checksum
How to use checksums
79754decd1047289b51464db091a61e384679d3c75836e7e2bee8b963d62800d
BLAKE2b-256 checksum
How to use checksums
a54bcea698bf207f7d8ca787d3748ba6131c52274093890a6ddd39c7bd4dd03e
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 29, 2026.

Transparency log

Release files / pyjuzhen_cu12-0.1.1-cp39-cp39-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl

Download URL pyjuzhen_cu12-0.1.1-cp39-cp39-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl
Size 13.8 MB
Tags CPython 3.9 Linux glibc 2.27+ x86-64 Linux glibc 2.28+ x86-64
SHA-256 checksum
How to use checksums
a45b09d2b5e4257493ca80d0747c774cbe120b67d1d3648778df50d101c5ca7d
BLAKE2b-256 checksum
How to use checksums
cbe07f794c661ed27be61d79b33e43753d0db453e9de99130c687c0f060f317c
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 29, 2026.

Transparency log

Security for pyjuzhen-cu12 0.1.1

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

All 7 files in this release have been uploaded with provenance metadata.

Select from 7 files

Attestation for pyjuzhen_cu12-0.1.1-cp315-cp315-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl

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 29, 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.1.1 This release

7 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