Skip to main content
stackgrad

stackgrad: A deep learning framework written from scratch, up to a served Qwen3 with retrieval and a tool-using agent.

Homepage | Documentation | Write-up

CI


Qwen3-0.6B streaming a worked answer through stackgrad's chat endpoint

stackgrad is an end-to-end deep learning stack:

  • a tensor library with lazy evaluation and autograd, every gradient in one file
  • three backends (NumPy, MLX, CuPy) and attention kernels written in Metal and Triton
  • layers, optimizers, a BPE tokenizer, and a transformer trained from nothing
  • Qwen3-0.6B loaded, served behind an OpenAI-style endpoint, and fine-tuned with LoRA and GRPO
  • retrieval and a tool-using agent on that server

The stackgrad/ package is under 3,000 lines, and CI keeps it there.

PyTorch, tiktoken, and transformers appear only in the tests, as the references each piece is checked against.


Laziness

Try a matmul. Nothing runs until you ask for the result.

import numpy as np
from stackgrad import Tensor
from stackgrad.profile import profile

N = 1024
a, b = Tensor(np.random.randn(N, N)), Tensor(np.random.randn(N, N))
with profile() as p:
  c = (a @ b).relu().sum()       # records four ops, runs none
  print(c.shape, dict(p.calls))  # () {}
  c.realize()                    # Matmul, Less, Where, Sum run, once each
print(p.table())

relu shows up as Less and Where: it composes primitives, so it never defines a gradient of its own.

Neural networks

import numpy as np
from stackgrad import Tensor, Module, Linear, Adam, cross_entropy_loss

class LinearNet(Module):
  def __init__(self):
    super().__init__()
    self.l1, self.l2 = Linear(784, 128), Linear(128, 10)

  def forward(self, x):
    return self.l2(self.l1(x.reshape(x.shape[0], -1)).relu())

model = LinearNet()
opt = Adam(model.parameters(), lr=0.001)

x, y = Tensor(np.random.rand(4, 1, 28, 28)), np.array([2, 4, 3, 7])  # replace with real mnist

for i in range(10):
  loss = cross_entropy_loss(model(x), y)
  opt.zero_grad()
  loss.backward()
  opt.step()
  print(i, loss.item())

See train_gpt.py for the full version: a 22.7M-parameter transformer that trains on TinyStories to a validation loss of 1.399 in 71 minutes on one RTX 3090.

Accelerators

  • CPU, NumPy
  • METAL, MLX, with attention and quantized-matmul kernels in Metal
  • CUDA, CuPy, with FlashAttention-2 in Triton

A new backend is one module that exports the 27 names cpu.py exports.

Installation

pip install stackgrad   # add [metal] for Apple GPUs, [cuda] for NVIDIA
stackgrad               # a quick example and links to the docs

From source:

git clone https://github.com/samitmohan/stackgrad.git
cd stackgrad
uv sync --extra metal --extra serve   # Apple silicon; NVIDIA: uv sync --extra cuda --no-dev

Documentation

The docs website has a quickstart, the API reference, and a showcase of what stackgrad runs, with every measured number and the command that produced it. It builds from the docs/ directory. The write-up, Modern AI: Autograd to Agents, explains each piece from first principles.

Quick example comparing to PyTorch

import numpy as np
from stackgrad import Tensor

x = Tensor(np.eye(3), requires_grad=True)
y = Tensor([[2.0, 0, -2.0]], requires_grad=True)
z = (y @ x).sum()
z.backward()

print(x.grad.tolist())  # dz/dx
print(y.grad.tolist())  # dz/dy

The same thing but in PyTorch:

import torch

x = torch.eye(3, requires_grad=True)
y = torch.tensor([[2.0, 0, -2.0]], requires_grad=True)
z = y.matmul(x).sum()
z.backward()

print(x.grad.tolist())  # dz/dx
print(y.grad.tolist())  # dz/dy

Running tests

uv run python test_grads.py   # every gradient against finite differences
uv run python tests/parity.py # every op and layer against PyTorch

The CI workflow runs the rest.

Metadata

Release files for stackgrad 0.2.1

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

Source distribution (sdist)

Source distribution for stackgrad 0.2.1
File Size Uploaded Provenance Actions
stackgrad-0.2.1.tar.gz 46.9 kB Without provenance Details for stackgrad-0.2.1.tar.gz

Built distribution (wheel)

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

Total release size: 106.4 kB

Release files / stackgrad-0.2.1.tar.gz

Download URL stackgrad-0.2.1.tar.gz
Size 46.9 kB
Tags Source
SHA-256 checksum
How to use checksums
9da98c1db151f2a8afbc7d87a8b6764c021ea7e65955f19eefed43fb75bdf1ea
BLAKE2b-256 checksum
How to use checksums
d28cbb8212650bb6d6be3c91d8ea06bbf9aee6f0c5e26843781c8148ca497c87
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.11.12 {"installer":{"name":"uv","version":"0.11.12","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Release files / stackgrad-0.2.1-py3-none-any.whl

Download URL stackgrad-0.2.1-py3-none-any.whl
Size 59.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
2227c7579d4e292ff22dbd6aa69ce610ae5941727305c0f12dac67a1d0050db8
BLAKE2b-256 checksum
How to use checksums
199ee08d367e47d6a9ee8451ea3b5c519d17a5c75f78d0339bae344f3c5de86d
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.11.12 {"installer":{"name":"uv","version":"0.11.12","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Security for stackgrad 0.2.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.

No provenance found

None of the files in this release were uploaded with provenance metadata.

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