Skip to main content

Simple Autograd Deep Learning: A minimal, readable deep learning framework built on NumPy

Project description

SADL Logo

SADL: Simple Autograd Deep Learning

A minimal, actually readable deep learning framework built on NumPy and CuPy.
Automatic differentiation, neural network primitives, and optimization with just a handful of Python files.

PyPI version Python versions License CI codecov Ruff Pyright Docstring coverage

The tale

Seek out this, to find out the story behind SADL.

Demo

See mnist_demo.ipynb for a working mini example of sadl on mnist.

Getting Started

A light description of all key components with examples: GETTING_STARTED.md

Installation

Using uv for installation is recommended.

(I had to name the pypi project py-sadl instead of sadl, because sadl was too similar to an existing project.)

Install uv with:

curl -LsSf https://astral.sh/uv/install.sh | sh
# Install with uv (recommended)
uv add py-sadl

# With GPU support (CUDA 12.x)
uv add py-sadl --extra gpu

Alternatively, using pip:

# Install with pip
pip install py-sadl

# With GPU support
pip install "py-sadl[gpu]"

Quick Start

import sadl
import numpy as np

# Create tensors
x = sadl.tensor([[1.0, 2.0], [3.0, 4.0]])

# Build a model
model = sadl.Mlp([
    sadl.Linear(dim_in=2, dim_out=4),
    sadl.ReLU(),
    sadl.Linear(dim_in=4, dim_out=1),
])

# Forward pass
output = model(x)
loss = np.sum(output)

# Backward pass and optimization
optimizer = sadl.SGD(list(model.parameters), lr=0.01)
optimizer.backward(loss)
optimizer.step()
optimizer.zero_grad()

Motivation

Modern deep learning frameworks like PyTorch and TensorFlow are powerful but complex. Their codebases span millions of lines, making it difficult to understand how automatic differentiation and neural network training actually work at a fundamental level.

SADL addresses this by providing a complete, functional deep learning framework that remains small enough to read and understand in its entirety. Every component, from tensor operations to backpropagation, is implemented transparently using standard NumPy operations.

The goal is not to replace production frameworks, but to serve as an educational resource and a foundation for experimentation. Researchers and engineers can trace exactly how gradients flow through computations without navigating layers of abstraction.

Related Projects

SADL joins a family of educational and minimal deep learning frameworks that have made autodiff more accessible:

micrograd by Andrej Karpathy is an elegant, minimal autograd engine operating on scalar values. In roughly 150 lines of code, it demonstrates the core concepts of backpropagation with remarkable clarity. micrograd is an excellent starting point for understanding how gradients flow through computations.

tinygrad by George Hotz takes a different approach, building a fully-featured deep learning framework with a focus on simplicity and hardware portability. tinygrad supports multiple backends and has grown into a serious alternative for running models on diverse hardware.

SADL takes inspiration from both projects while pursuing its own path: building directly on NumPy's ndarray infrastructure. By implementing NumPy's operator and dispatch protocols via NDArrayOperatorsMixin, __array_ufunc__, and __array_function__, SADL achieves autograd without introducing a custom array backend. This means existing NumPy code works unchanged, and the mental model stays close to the numerical computing patterns that researchers already know.

Design Principles

Build on NumPy

SADL builds on NumPy. This means:

  • All NumPy operations work out of the box
  • No need to learn a new tensor API
  • Seamless interoperability with the scientific Python ecosystem
  • Only a thin Tensor layer on top of NumPy arrays
  • GPU support through CuPy with zero code changes

Mathematical Functions as First-Class Citizens

Neural network layers are modeled as mathematical functions, matching how they appear in research papers. The Function abstract base class enforces a simple contract: implement __call__ to define the forward pass. This creates a natural bridge between mathematical notation and code.

class Sigmoid(Function):
    def __call__(self, x: Tensor) -> Tensor:
        return 1 / (xp.exp(-x) + 1)

Explicit Over Implicit

SADL favors explicit behavior over magic:

  • Gradients must be explicitly enabled with requires_grad=True
  • Parameters are a distinct type that always tracks gradients
  • The computation graph is visible and inspectable
  • Device transfers (cpu ↔ cuda) are explicit operations

Minimal but Complete

The framework includes only what is necessary for training neural networks:

  • Tensor with autograd support
  • Parameter for learnable weights
  • Function base class for layers
  • Optimizer base class with built-in SGD and Adam due to their frequent use
  • Serialization for model persistence

Additional layers and optimizers can be built on these primitives without modifying core code.

Key Components

Tensor: Wrapper around np.ndarray with additional attributes for autograd. Intercepts NumPy operations to build the computation graph.

Parameter: Tensor subclass for learnable weights. Always requires gradients and retains them after backward pass for gradient accumulation.

Function: Abstract base class for neural network layers. Provides parameter traversal, device management, and train/inference mode switching.

Optimizer: Abstract base class that owns the backward pass. Performs topological sort, gradient computation, and graph cleanup.

GradOp Registry: Dictionary mapping operation names to backward functions. New operations can be registered with a decorator.

Serialization

SADL uses a custom binary format (.sadl files) for efficient tensor storage:

  • 4-byte magic header for format validation
  • Version byte for forward compatibility
  • Compact encoding of dtype, shape, and raw data
  • Support for single tensors or ordered dictionaries of tensors

Contributing

See CONTRIBUTING.md for development setup, commands, and guidelines.

Code of Conduct

See CODE_OF_CONDUCT.md for behavior guidelines. The file was created using the Contributor Covenant.

Future Plans

The goal is to expand the ecosystem without losing the small and readable core. There are definitely many more things worth adding, like more layers, architectures, and domain-specific tooling. But if all of that keeps accumulating inside this repository, it creates exactly the kind of codebase bloat that makes larger frameworks hard to understand in the first place.

That is why the long-term direction is a small core sadl repository, plus separate plugin-style repositories for higher-level functionality, similar in spirit to projects like timm, torchvision, or torchaudio. This keeps the core focused on tensors, gradients, backpropagation, functions, optimizers, and device handling, while allowing the surrounding ecosystem to grow independently.

Built In

  • Static graph compilation for repeated computations

Separate Repositories

  • Additional layers and components (convolution, batch normalization, attention)
  • Higher-level model architectures and domain libraries
  • XLA compilation backend for TPU support
  • Automatic mixed precision training
  • Distributed training primitives

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

py_sadl-1.4.0.tar.gz (2.7 MB view details)

Uploaded Source

Built Distribution

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

py_sadl-1.4.0-py3-none-any.whl (39.1 kB view details)

Uploaded Python 3

File details

Details for the file py_sadl-1.4.0.tar.gz.

File metadata

  • Download URL: py_sadl-1.4.0.tar.gz
  • Upload date:
  • Size: 2.7 MB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: uv/0.10.10 {"installer":{"name":"uv","version":"0.10.10","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for py_sadl-1.4.0.tar.gz
Algorithm Hash digest
SHA256 78cade54a4d31d7257b63df6134b51b101165a8c51af5038324b6abfa2ad07f4
MD5 3096986f7f06e10938163a15f8a7b908
BLAKE2b-256 ac8850c4414f58e3f07715d7666bc609ef1b7c269e1cf9849214ab4aa5db2086

See more details on using hashes here.

File details

Details for the file py_sadl-1.4.0-py3-none-any.whl.

File metadata

  • Download URL: py_sadl-1.4.0-py3-none-any.whl
  • Upload date:
  • Size: 39.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: uv/0.10.10 {"installer":{"name":"uv","version":"0.10.10","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for py_sadl-1.4.0-py3-none-any.whl
Algorithm Hash digest
SHA256 0ba09d225d9db9fbb51ffdee29afd8912ab6ac24072c9144c367d0b6543a97fe
MD5 ec3828d0077be815e2081fab33cc0346
BLAKE2b-256 3b90d6a8d9dff8e66afa7881959b86f102c5d5a8165f381f2e9b52dd0a914364

See more details on using hashes here.

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