TinyTorch is a small neural-network framework built from scratch to understand what actually happens underneath high-level deep-learning APIs. It implements the framework-level abstractions you find in libraries like PyTorch or Keras — modules, layers, loss functions, optimizers, and a trainer — while currently relying on PyTorch's tensors and autograd engine to compute gradients.
Status: TinyTorch currently relies on PyTorch's autograd engine for automatic differentiation. The framework's forward-pass, model composition, loss, optimization, training, and visualization abstractions are implemented as part of this project. A custom automatic differentiation/backpropagation engine is a planned next step.
I wanted to understand what happens underneath high-level deep-learning APIs instead of just calling them. Rather than treating model.fit() as a black box, I'm implementing the pieces myself — how a Linear layer holds its weights, how a Sequential container chains layers together, how an optimizer turns gradients into parameter updates, and how a training loop ties all of that together. PyTorch's autograd currently handles the actual differentiation, but building everything around it is what's teaching me how the rest of the machinery fits together.
At a component level, TinyTorch splits into two groups — the building blocks (Modules) and the machinery that drives them (Training):
TinyTorch
│
┌───────────┴───────────┐
│ │
Modules Training
│ │
┌────┼────┐ ┌───────┼────────┐
│ │ │ │ │ │
Linear ReLU Sequential Loss Optimizer Trainer
│
└───────────┐
↓
PyTorch Tensor
↓
PyTorch Autograd
Linear (and the other activation modules) hold PyTorch tensors as their parameters, and it's those tensors' .backward() that PyTorch autograd drives — everything above that line is TinyTorch code.
At a data-flow level, a single training step looks like this:
Input
↓
Linear (TinyTorch)
↓
Activation (TinyTorch)
↓
Sequential (TinyTorch — chains the layers above)
↓
Loss (TinyTorch)
↓
Autograd (PyTorch — .backward())
↓
Optimizer (TinyTorch — reads .grad, updates parameters manually)
↓
Updated Parameters
Everything except the backward pass itself is TinyTorch code. Linear.forward and the activation functions build a normal PyTorch computation graph, loss.backward() (PyTorch autograd) populates .grad on each parameter tensor, and TinyTorch's own optimizer code (SGD, Momentum, Adam) then reads those gradients and applies the update rule by hand, wrapped in torch.no_grad().
Only what's actually implemented in the repository:
Module— base class all layers inherit from. Providesforward()/__call__, recursiveparameters()andchildren()collection (walks__dict__, handles nested modules and lists of modules), andtrain()/eval()mode toggling.Linear— a fully connected layer. Weights are initialized with a He-style scaled random normal (randn * sqrt(2/input_size)), bias initialized to zero, both markedrequires_grad_()so PyTorch autograd tracks them.- Activations —
ReLU,Sigmoid,Tanh,Softmax,LeakyReLU. Each is a thinModulesubclass wrapping the equivalent PyTorch tensor operation (torch.max,torch.sigmoid,torch.tanh,torch.softmax). Sequential— chains an arbitrary list of layers, runningforward()through each in order. Supportsadd(),len(), and indexing.- Loss functions —
MSELoss,CrossEntropyLoss,BCE, all implemented as plain tensor arithmetic over PyTorch tensors (mean squared error, log-softmax negative log-likelihood, and clamped binary cross-entropy respectively). - Optimizers —
SGD,Momentum, andAdam, each implementing its update rule manually (velocity terms, first/second moment estimates with bias correction for Adam) rather than callingtorch.optim. Trainer— wraps a model, loss function, and optimizer into atrain_step()/train()/predict()/evaluate()loop, with basic NaN/Inf loss detection and a loss history log.NeuralNetworkVisualizer— matplotlib-based inspection tool (see Visualization below).
Tinytorch/
├── tinytorch/
│ ├── module.py # Base Module class
│ ├── linear.py # Linear (fully connected) layer
│ ├── activation.py # ReLU, Sigmoid, Tanh, Softmax, LeakyReLU
│ ├── sequential.py # Sequential container
│ ├── losses.py # MSELoss, CrossEntropyLoss, BCE
│ ├── optim.py # SGD, Momentum, Adam
│ ├── trainer.py # Training loop wrapper
│ ├── visualizer.py # NeuralNetworkVisualizer
│ └── main.py # End-to-end usage example
└── tests/
└── test_framework.py # unittest test suite
Note: the modules import each other with flat, non-package-style imports (e.g. from module import Module rather than from tinytorch.module import Module). There's no __init__.py/setup.py/pyproject.toml making tinytorch an installable package yet, so scripts need to be run with the tinytorch/ directory itself on the Python path (see Installation).
This is the actual model construction and training code from main.py:
import torch
from linear import Linear
from activation import Tanh
from sequential import Sequential
from losses import MSELoss
from optim import SGD
from trainer import Trainer
torch.manual_seed(42)
x = torch.tensor([[2.0, 3.0], [4.0, 5.0], [6.0, 7.0]])
y = torch.tensor([[1.0], [-1.0], [1.0]])
model = Sequential(
Linear(2, 256),
Tanh(),
Linear(256, 256),
Tanh(),
Linear(256, 1)
)
loss_fn = MSELoss()
optimizer = SGD(model.parameters(), lr=0.0068185)
trainer = Trainer(model=model, loss_fn=loss_fn, optimizer=optimizer)
history = trainer.train(x, y, epochs=1000, print_every=100)
final_loss = trainer.evaluate(x, y)
prediction = trainer.predict(x)The example network is a 2 → 256 → 256 → 1 fully connected network (two hidden layers of 256 units each, Tanh activations, scalar output). Parameter count, layer by layer:
| Layer | Weights | Biases | Total |
|---|---|---|---|
Linear(2, 256) |
2 × 256 = 512 | 256 | 768 |
Linear(256, 256) |
256 × 256 = 65,536 | 256 | 65,792 |
Linear(256, 1) |
256 × 1 = 256 | 1 | 257 |
| Total | 66,817 |
This matches what model.parameters() and the visualizer's parameter_summary() would report for this architecture.
visualizer.py implements NeuralNetworkVisualizer, which wraps a Sequential model and automatically finds its Linear layers. It currently supports:
parameter_summary()— prints a per-layer breakdown of weight/bias shapes and parameter counts, plus a running total.architecture()— a matplotlib diagram of the full network: neurons per layer as circles (large layers are subsampled to a representative subset), connections drawn between layers with line weight/opacity roughly reflecting the connection's weight magnitude, and a parameter-count caption.inspect_neuron()— prints every incoming weight and the bias for a specific neuron, and if given sample input values, walks through the weighted sum and (for a Tanh neuron) the resulting activation.neuron_diagram()— a matplotlib diagram of a single neuron's incoming connections, with per-connection weight values labeled.show_weight_matrix()— prints and plots (as a heatmap) a given layer's full weight matrix; large matrices are truncated to a 10×10 preview in the printed output.
All of this operates on the actual weights/bias tensors stored on each Linear layer — it's not a mock or placeholder visualization.
Trainer.train_step() runs, in order:
- Forward pass — TinyTorch:
self.model(x)runs the input throughSequential's chain ofLinear/activation layers. - Loss calculation — TinyTorch: the configured loss function (e.g.
MSELoss) computes a scalar loss from the prediction and target. - Backpropagation / autograd — PyTorch:
loss.backward()uses PyTorch's autograd engine to populate.gradon every parameter tensor. TinyTorch does not currently implement its own differentiation. - Gradient update — TinyTorch: the optimizer (
SGD,Momentum, orAdam) reads each parameter's.gradand applies its update rule manually insidetorch.no_grad(). - Repeated training —
Trainer.train()callstrain_step()for the configured number of epochs, logging loss toself.historyand optionally printing progress everyprint_everyepochs.
train_step() also includes a NaN/Inf guard on the loss (training stops updating and reports the bad loss value instead of propagating NaNs further) and a gradient-magnitude inspection block intended to surface exploding gradients — though as written, that block checks for a layer.weight attribute, while Linear actually stores its weight tensor as layer.weights, so it doesn't currently pick anything up for Linear layers (see Current Limitations).
Each piece has one job:
Moduleis purely structural — it knows how to find its own parameters and sub-modules and how to toggle train/eval mode, but has no idea what a "layer" computes.Linearowns exactly one thing: a weight matrix, a bias vector, and the affine transform between them. It has no knowledge of activations, loss, or training.- Activations are stateless
Modules wrapping a single elementwise (or row-wise, forSoftmax) function. Sequentialis a container, not a layer type — it just knows how to run a list ofModules in order.- Loss functions are separate from both the model and the optimizer, taking only a prediction and a target.
- Optimizers know nothing about the model's structure — they operate on a flat list of parameter tensors and their gradients.
Traineris the only piece that knows about all of the above simultaneously; it's the orchestration layer, not where any actual math lives.
This mirrors how PyTorch itself separates nn.Module, nn.Linear, loss functions, and torch.optim — the goal is to understand why that separation exists by rebuilding it, not to invent a different architecture.
Being direct about where the current implementation stops:
- No custom autograd. Gradient computation is done entirely by PyTorch's
.backward(). TinyTorch's own code starts after gradients already exist in.grad. - Not an installable package yet. Modules import each other with flat imports (
from module import Module), so there's notinytorch.<module>namespace — running any script requires thetinytorch/directory to be onPYTHONPATHdirectly. - No
requirements.txt,pyproject.toml, orsetup.pyin the repository. - No license file is present.
- Only one layer type (
Linear) — no convolutional, recurrent, normalization, or dropout layers. - No dataset/DataLoader abstraction. The training example passes raw in-memory tensors directly.
- No model checkpointing — no save/load functionality for trained parameters.
LeakyReLU.__init__doesn't callsuper().__init__(), so it skipsModule's base initialization (this has no visible effect for its current forward-only usage, but is inconsistent with the other activation classes).- The gradient-magnitude check in
Trainer.train_step()doesn't currently find anything forLinearlayers, since it looks for alayer.weightattribute andLinearstores it aslayer.weights— the diagnostic silently does nothing rather than raising an error. - Only tested on tiny, hand-written example datasets (3–10 samples) — no evaluation on a real dataset yet.
v0.1
Framework architecture
↓
v0.2
Custom backward/autograd
↓
v0.3
More layers
↓
v0.4
More advanced models
v0.1 — Framework architecture (current)
- Core
Moduleabstraction with parameter/submodule discovery Linearlayer, five activation functions,Sequentialcontainer- Three loss functions (
MSELoss,CrossEntropyLoss,BCE) - Three optimizers (
SGD,Momentum,Adam) with manually implemented update rules Trainerwith a full train/evaluate/predict loop and loss history- Architecture, weight-matrix, and single-neuron visualization tooling
- Initial
unittesttest suite covering layers, activations, losses, the optimizer step, and an end-to-end training run
v0.2 — Custom backward/autograd (planned)
- Replace PyTorch's
.backward()with a hand-built automatic differentiation / backpropagation engine - Own tensor-like value type with gradient tracking, or a
.grad_fn-style computation graph
v0.3 — More layers (planned)
- Additional layer types (e.g. convolutional, batch normalization, dropout)
- Dataset/DataLoader support for real datasets rather than in-memory tensors
- More rigorous, broader test coverage
- Packaging (
pyproject.toml) so TinyTorch can be installed and imported astinytorch.<module>
v0.4 — More advanced models (planned)
- Larger, more advanced model architectures built on top of the above
- Better visualization (interactive, larger-scale networks)
There's no packaging or requirements.txt in the repository yet, so setup is manual. TinyTorch code depends on:
torch— used throughout for tensors and autogradmatplotlibandnumpy— used only byvisualizer.py
pip install torch matplotlib numpyBecause the modules use flat imports (from module import Module, not from tinytorch.module import Module), you need tinytorch/ on your Python path — the simplest way is to run scripts from inside that directory:
git clone <your-repo-url>
cd Tinytorch/tinytorch
pip install torch matplotlib numpyFrom inside the tinytorch/ directory:
python main.pyThis builds the 2 → 256 → 256 → 1 example network, trains it for 1000 epochs with SGD, and prints the model summary, training progress, final loss, and predictions — matching the code shown in Example above.
To run the visualizer's own example directly:
python visualizer.pyThis builds the same network, prints a parameter summary, and opens matplotlib windows for the architecture diagram, a single-neuron inspection, and a layer's weight-matrix heatmap.
No license file is currently included in the repository. Add one (e.g. MIT, Apache 2.0) before treating this as reusable by others.
This project is a hands-on learning exercise, developed while studying neural network fundamentals — including educational material from Andrej Karpathy on building neural networks and autograd engines from scratch. It is not affiliated with or endorsed by him; it's simply part of the material that motivated learning this way rather than only using existing frameworks.