Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
name: CI

on:
push:
branches: [main]
pull_request:
branches: [main]

jobs:
test:
runs-on: ubuntu-latest
strategy:
matrix:
python-version: ["3.10", "3.11", "3.12", "3.13"]
steps:
- uses: actions/checkout@v5

- uses: actions/setup-python@v6
with:
python-version: ${{ matrix.python-version }}

- name: Install
run: pip install -e ".[test]"

- name: Test
run: pytest -q
14 changes: 14 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
# learngrad

[![CI](https://github.com/devpparikh/learngrad/actions/workflows/ci.yml/badge.svg)](https://github.com/devpparikh/learngrad/actions/workflows/ci.yml)
[![PyPI](https://img.shields.io/pypi/v/learngrad)](https://pypi.org/project/learngrad/)
[![Python](https://img.shields.io/pypi/pyversions/learngrad)](https://pypi.org/project/learngrad/)

A minimal scalar-valued autograd engine with neural network primitives, built for learning purposes. Inspired by [micrograd](https://github.com/karpathy/micrograd).

## Install
Expand Down Expand Up @@ -53,3 +57,13 @@ Reaches ~94% val accuracy in 100 epochs.

- Python >= 3.10
- numpy

## Tests

```bash
pip install -e ".[test]"
pytest
```

Every operation's backward pass is checked against a finite-difference
gradient, and each optimizer is checked to fit a simple linear model.
4 changes: 0 additions & 4 deletions learngrad/engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,3 @@ def build_topo(v):
self.grad = 1
for val in reversed(topo):
val._backward()

def __repr__(self):
return f"Value(data={self.data}, grad={self.grad})"

5 changes: 3 additions & 2 deletions learngrad/nn.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ def __repr__(self) -> str:
for key, group in groupby(self.neurons, key=str):
count = sum(1 for _ in group)
result.append(f"{count} x {key}" if count > 1 else key)
return f"Layer({", ".join(result)})"
return "Layer(" + ", ".join(result) + ")"


class MLP(Module):
Expand All @@ -66,4 +66,5 @@ def parameters(self):
return [p for layer in self.layers for p in layer.parameters()]

def __repr__(self):
return f"MLP(\n{',\n'.join(str(layer) for layer in self.layers)}\n)"
layers = ",\n".join(str(layer) for layer in self.layers)
return f"MLP(\n{layers}\n)"
13 changes: 10 additions & 3 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"

[project]
name = "learngrad"
version = "0.2.1"
version = "0.2.2"
description = "A minimal scalar-valued autograd engine with neural network primitives, built for learning purposes."
readme = "README.md"
requires-python = ">=3.10"
Expand All @@ -16,11 +16,18 @@ keywords = ["autograd", "neural-network", "deep-learning", "education", "optimiz
classifiers = [
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 3",
"Operating System :: OS Independent",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12",
"Programming Language :: Python :: 3.13",
"Operating System :: OS Independent",
]

[project.optional-dependencies]
test = ["pytest>=8"]

[project.urls]
Homepage = "https://github.com/devparikh0506/learngrad"
Homepage = "https://github.com/devpparikh/learngrad"

[tool.setuptools.packages.find]
include = ["learngrad*"]
83 changes: 83 additions & 0 deletions tests/test_engine.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
"""Gradient checks: every op's backward pass must match a finite-difference estimate."""

import math

import pytest

from learngrad.engine import Value

EPS = 1e-6


def numeric_grad(f, *xs):
"""Central-difference gradient of scalar f with respect to each input."""
grads = []
for i in range(len(xs)):
hi = list(xs)
lo = list(xs)
hi[i] += EPS
lo[i] -= EPS
grads.append((f(*hi) - f(*lo)) / (2 * EPS))
return grads


def analytic_grad(f, *xs):
vals = [Value(x) for x in xs]
f(*vals).backward()
return [v.grad for v in vals]


CASES = [
("add", lambda a, b: a + b, (2.0, -3.0)),
("sub", lambda a, b: a - b, (2.0, -3.0)),
("mul", lambda a, b: a * b, (2.0, -3.0)),
("div", lambda a, b: a / b, (2.0, -3.0)),
("pow", lambda a, b: a**3 + b * 0, (1.5, 0.0)),
("neg", lambda a, b: -a + b, (2.0, 1.0)),
("radd", lambda a, b: 4 + a + b, (2.0, 1.0)),
("rsub", lambda a, b: 4 - a * b, (2.0, 1.0)),
("rmul", lambda a, b: 4 * a * b, (2.0, 1.0)),
("rtruediv", lambda a, b: 4 / (a + b), (2.0, 1.0)),
("exp", lambda a, b: (a * b).exp(), (0.5, -1.2)),
("composite", lambda a, b: (a * b + a**2 - b / a).exp() * 0.1, (0.7, 0.4)),
]


@pytest.mark.parametrize("name,f,xs", CASES, ids=[c[0] for c in CASES])
def test_gradients_match_finite_differences(name, f, xs):
analytic = analytic_grad(f, *xs)

def scalar(*ys):
out = f(*[Value(y) for y in ys])
return out.data

numeric = numeric_grad(scalar, *xs)
for a, n in zip(analytic, numeric):
assert math.isclose(a, n, rel_tol=1e-4, abs_tol=1e-6)


def test_relu_gradient_is_zero_for_negative_input():
x = Value(-2.0)
x.relu().backward()
assert x.grad == 0


def test_relu_passes_gradient_for_positive_input():
x = Value(3.0)
y = x.relu()
y.backward()
assert y.data == 3.0
assert x.grad == 1


def test_gradient_accumulates_when_a_value_is_reused():
x = Value(3.0)
(x * x + x).backward() # d/dx (x^2 + x) = 2x + 1
assert x.grad == 7.0


def test_readme_example():
x = Value(2.0)
y = x**2 + x * 3
y.backward()
assert x.grad == 7.0
61 changes: 61 additions & 0 deletions tests/test_nn_and_optimizers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import random

import pytest

from learngrad.engine import Value
from learngrad.nn import MLP, Layer, Neuron
from learngrad.optimizers import SGD, Adam, RMSProp, SGDMomentum


def test_parameter_counts():
assert len(Neuron(3).parameters()) == 4
assert len(Layer(3, 2).parameters()) == 8
# 2->4 (12) + 4->4 (20) + 4->1 (5)
assert len(MLP(2, [4, 4, 1]).parameters()) == 37


def test_mlp_forward_returns_scalar_for_single_output():
out = MLP(2, [4, 1])([Value(1.0), Value(-1.0)])
assert isinstance(out, Value)


def test_reprs():
assert repr(Neuron(3)) == "ReLUNeuron(3)"
assert repr(Layer(3, 2, nonlin=False)) == "Layer(2 x LinearNeuron(3))"
assert repr(MLP(2, [3, 1])) == "MLP(\nLayer(3 x ReLUNeuron(2)),\nLayer(LinearNeuron(3))\n)"


def test_zero_grad_resets_all_parameters():
model = MLP(2, [3, 1])
model([Value(1.0), Value(2.0)]).backward()
model.zero_grad()
assert all(p.grad == 0 for p in model.parameters())


@pytest.mark.parametrize(
"make_opt",
[
lambda ps: SGD(ps, lr=0.05),
lambda ps: SGDMomentum(ps, lr=0.05),
lambda ps: RMSProp(ps, lr=0.01),
lambda ps: Adam(ps, lr=0.05),
],
ids=["SGD", "SGDMomentum", "RMSProp", "Adam"],
)
def test_optimizers_reduce_loss_on_a_linear_fit(make_opt):
random.seed(0)
model = MLP(1, [1]) # a single linear neuron
opt = make_opt(model.parameters())
xs = [-2.0, -1.0, 0.0, 1.0, 2.0]
ys = [2 * x + 1 for x in xs]

def loss():
return sum((model([Value(x)]) - y) ** 2 for x, y in zip(xs, ys)) / len(xs)

start = loss().data
for _ in range(200):
opt.zero_grad()
current = loss()
current.backward()
opt.step()
assert loss().data < start * 0.05
Loading