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 or Windows (Windows from version 0.1.2), 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.
With an AMD card on Windows there is a third package, pyjuzhen-rocm7 (from
version 0.1.2, for Python 3.11 to 3.13). It needs AMD's ROCm libraries in the
same environment, and pip cannot find those by name: they are on AMD's server,
not on PyPI. Install them first (a download of 1.1 GB), then the package:
pip install https://repo.radeon.com/rocm/windows/rocm-rel-7.2.1/rocm_sdk_core-7.2.1-py3-none-win_amd64.whl https://repo.radeon.com/rocm/windows/rocm-rel-7.2.1/rocm_sdk_libraries_custom-7.2.1-py3-none-win_amd64.whl
pip install pyjuzhen-rocm7
An environment that already runs AMD's PyTorch for Windows has the libraries, and only the second line is needed. More under 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. fit,evaluateandpredictalso take numpy arrays and copy them to the network's device themselves. Everything else takes matrices:net(x),net.jvpand the functions ofjz(make one withjz.array(a, device=...)).- Reading values (
.numpy(),.item(),print) waits for the GPU. - On the CPU, matrix products use one thread per core (on Windows and Linux,
where they come from OpenBLAS);
OPENBLAS_NUM_THREADSset before the import gives another number. Elementwise operations run on one thread. - 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 use1 - 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)isjz.sum(A, 0),A.exp()isjz.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.argmaxandjz.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)withyholding 0..9 works; one-hot rows still do too) and token ids for a network that starts withnn.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. To see
a trained model at work without training one, open examples/write_story.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 |
write_story.ipynb |
a trained transformer writes children's stories: the weights of tinystories.py are downloaded, nothing is trained; word pieces, the probabilities of the next piece, sampling with a temperature |
|
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 |
text_flow.py |
noise that turns into writing: a flow from a Gaussian to the letters of a word, with sines and cosines as inputs; a picture and an animation (needs matplotlib) | |
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 |
tinystories.py |
a 29.5 million parameter transformer that writes children's stories: BPE tokens from disk, a learning-rate schedule, top-k sampling, the weight cache of the C++ demo read and written with numpy; measured against C++ in benchmarks/tinystories_vs_cpp.md |
demo_tinystories.cu |
knn.py |
k nearest neighbours with topk |
knn.cu |
demo.py |
a tour with timings: stacking, slicing, an iteration for a matrix inverse, density-ratio estimation | demo.cu |
demo_gemm.py |
a benchmark of the matrix product | demo_gemm.cu |
pagerank.py |
PageRank by power iteration | pagerank.cu |
demo_training.py |
the shortest training loop: one Linear layer |
demo_training.cu |
helloworld_nn.py |
a small network for regression | helloworld_nn.cu |
demo_classification.py |
two classes, a wide network, labels as class numbers | demo_classification.cu |
demo_llm_tokens.py |
a very small token model: gradient accumulation, clip_grad_norm, checkpoints |
demo_llm_tokens.cu |
demo_zeroflow.py |
a rectified flow between 2-D toy distributions whose velocity vanishes at t = 0.5 when they are equal | demo_zeroflow_web.cu (without the page) |
demo_arithmetic.py |
a transformer learns to add, digit by digit; scored on unseen sums | demo_arithmetic.cu |
demo_discretediffusion.py |
a masked discrete diffusion model on characters: a bidirectional transformer, masked_softmax_cross_entropy, generation by unmasking |
demo_discretediffusion.cu, demo_discretediffusion_web.cu |
demo_diffusion_tinystories.py |
the same on TinyStories word pieces | demo_diffusion_tinystories.cu |
demo_word2vec.py |
word2vec with hand-written gradients, matrix operations only | demo_word2vec.cu |
demo_cnn_rectified.py, sample_cnn_rectified.py |
the CIFAR-10 image generator of the notebook as scripts: train, save, draw samples for FID | demo_cnn_rectified.cu, sample_cnn_rectified.cu |
demo_tsfm.py |
a time-series forecaster in the style of TimesFM: patches, quantiles, a pinball loss written with matrix operations | tsfm/demo_tsfm.cu |
Every demo_ script takes --device cpu|gpu and --steps N and is short by
default: about a minute on a CPU, enough to see it learn. Its first lines say
how to run the full version of the C++ demo. The scripts that need a public
data set (text8, CIFAR-10, TinyStories) download it on first use into
datasets/. demo_mnist_web.cu and demo_transformer_web.cu are web pages
around demo_mnist.py and transformer_charlm.py.
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).
For AMD cards on Windows the workflow also builds ROCm wheels, the package
pyjuzhen-rocm7. They are the same module with device="gpu" on ROCm, for
Radeon RX 7000 and RX 9000 cards and the Ryzen AI 300 and AI Max processors.
Like the CUDA package they carry no GPU library, but pip cannot fetch AMD's by
itself: AMD's ROCm 7.2 packages go into the same environment first, exactly as
AMD describes for PyTorch on Windows (rocm-sdk-core and
rocm-sdk-libraries-custom from repo.radeon.com; the commands are at the top
of this page). The packages of the same names on PyPI are not AMD's, which is
why they cannot be requirements of the package. AMD's HIP SDK installer does
not do instead. python/tools/rocm_variant.py says how the wheels are made.
Metadata
Release files for pyjuzhen-rocm7 0.1.2
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Built distributions (wheels)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| pyjuzhen_rocm7-0.1.2-cp313-cp313-win_amd64.whl | CPython 3.13 | CPython 3.13 | Windows x86-64 | Details for pyjuzhen_rocm7-0.1.2-cp313-cp313-win_amd64.whl |
| pyjuzhen_rocm7-0.1.2-cp312-cp312-win_amd64.whl | CPython 3.12 | CPython 3.12 | Windows x86-64 | Details for pyjuzhen_rocm7-0.1.2-cp312-cp312-win_amd64.whl |
| pyjuzhen_rocm7-0.1.2-cp311-cp311-win_amd64.whl | CPython 3.11 | CPython 3.11 | Windows x86-64 | Details for pyjuzhen_rocm7-0.1.2-cp311-cp311-win_amd64.whl |
Total release size: 40.9 MB
Release files / pyjuzhen_rocm7-0.1.2-cp313-cp313-win_amd64.whl
| Download URL | pyjuzhen_rocm7-0.1.2-cp313-cp313-win_amd64.whl |
|---|---|
| Size | 13.6 MB |
| Tags | CPython 3.13 Windows x86-64 |
|
SHA-256 checksum How to use checksums |
78cb2fd224214b5b77b4a739450403d56d08fde4ef129af321d7c8a67c87e588
|
|
BLAKE2b-256 checksum How to use checksums |
883a8535648952aeedfb4ce164cedddda7476f616265e1392c80e6170ed479b2
|
| 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 Dec 1, 2026.
Transparency logRelease files / pyjuzhen_rocm7-0.1.2-cp312-cp312-win_amd64.whl
| Download URL | pyjuzhen_rocm7-0.1.2-cp312-cp312-win_amd64.whl |
|---|---|
| Size | 13.6 MB |
| Tags | CPython 3.12 Windows x86-64 |
|
SHA-256 checksum How to use checksums |
fedad3611591eba4e4aa2560252da49364663b4ae6b7549b292692ddc47a5be8
|
|
BLAKE2b-256 checksum How to use checksums |
c7fc84d451030469d446ad32d18d61dca65023a27e77c4ba88e55fc2d9c2653e
|
| 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 Dec 1, 2026.
Transparency logRelease files / pyjuzhen_rocm7-0.1.2-cp311-cp311-win_amd64.whl
| Download URL | pyjuzhen_rocm7-0.1.2-cp311-cp311-win_amd64.whl |
|---|---|
| Size | 13.6 MB |
| Tags | CPython 3.11 Windows x86-64 |
|
SHA-256 checksum How to use checksums |
e89b6db0f2e927afd790f09ec619fdf0355ef71b9f5aa7caa5d6ffc733963a0f
|
|
BLAKE2b-256 checksum How to use checksums |
c9b37fa64648e1d89c270ce2f2a4352e769e732ce97e76589fbc0c785d06a63b
|
| 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 Dec 1, 2026.
Transparency logSecurity for pyjuzhen-rocm7 0.1.2
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 3 files in this release have been uploaded with provenance metadata.
Attestation for pyjuzhen_rocm7-0.1.2-cp313-cp313-win_amd64.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 Dec 1, 2026.
Transparency logA 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.