r/cpp • u/Express-Act3158 • Apr 11 '26
Building a Deep learning framework in C++ (from scratch) - training MNIST as a milestone
i am building a deep learning framework called "Forge" completely from scratch in C++, its nowhere near complete yet, training MNIST Classifier shows a functional core on CPU (i'll add a CUDA backend too). My end goal is to train a modern transformer on Forge.
YT video of MNIST training :- www.youtube.com/watch?v=CalrXYYmpfc
this video shows:
-> training an MLP on MNIST
-> loss decreasing over epochs
-> predictions vs ground truth
this stable training proves that the following components are working correctly:-
--> Tensor system (it uses Eigen as math backend, but i'll handcraft the math backend/kernels for CUDA later) and CPU memory allocator.
--> autodiff engine (computation graph is being built and traversed correctly)
-->primitives -- linear layer, relu activation (Forge has sigmoid, softmax, gelu, tanh and leakyrelu too), CrossEntropy loss function (it fuses log softmax and CE. Forge has MSE and BinaryCrossEntropy too, the BCE fuses sigmoid and BCE) and SGD optimizer (i am planning to add momentum in SGD, Adam and AdamW)
[the Forge repo on GitHub is currently private as its WAP]
My GitHub: github.com/muchlakshay
3
u/pdp10gumby Apr 11 '26
This is great! Python is ok, I guess, but too much has to be done in it when I’d rather be more tightly integrated with the rest of the codebase.
2
u/CanadianTuero Apr 14 '26
I've done something similar where I wrote a tensor/autograd/neural network library tinytensor.
If you plan on writing your own tensor type instead of Eigen, I would do that first and getting the design right is tricky and may cause rewrites of the abstracts on top of it. It allows you to do things like cheap views of tensors (i.e. x[2] is a view and not a copy), and getting the gradients to track correctly through the views takes some thought. Also, I would write tests and compare against libtorch (C++ frontend for pytorch). Testing deep learning code can be tricky, as convergence of models can still happen even if you have bugs.