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 | PyPI

CI PyPI


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.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 stackgrad 0.3.0
File Size Uploaded Provenance Actions
stackgrad-0.3.0.tar.gz 48.7 kB Without provenance Details for stackgrad-0.3.0.tar.gz

Built distribution (wheel)

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

Total release size: 110.4 kB

Release files / stackgrad-0.3.0.tar.gz

Download URL stackgrad-0.3.0.tar.gz
Size 48.7 kB
Tags Source
SHA-256 checksum
How to use checksums
cd5cd99f1dd6465a6aba00e03ac09c411b997eddf767402b41ef6b40b645d593
BLAKE2b-256 checksum
How to use checksums
c3a41d3c967752358a2649a5bb14eb09a9b6cf64fdf4fe384fffe3f67e46d23e
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.3.0-py3-none-any.whl

Download URL stackgrad-0.3.0-py3-none-any.whl
Size 61.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
a65fe8ecb411e0635abc944c589229e888198b852c4a2dca22c6f7cb6592ac98
BLAKE2b-256 checksum
How to use checksums
57bfdd3ea20ec4b732a511f25064f3cc75ee3287c749d7a536965f36b0ae3f9d
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.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.

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