yusiwen/dl-from-scratch
0
DL From Scratch
Implement mainstream deep learning models from scratch.
Project Structure
├── main.py
├── pyproject.toml
├── .gitignore
├── README.md
├── ROADMAP.md
├── ml/ # Classical Machine Learning (pure NumPy)
│ ├── mlp/ # MLP (MNIST, manual backprop)
│ └── basics/ # 12 standalone models (lin/log reg, SVM, K-Means, PCA, RF, GBDT, etc.)
├── cv/ # Computer Vision
│ ├── simplecnn/ # SimpleCNN (CIFAR-10, Conv×3+Pool×3+FC×2)
│ ├── resnet18/ # ResNet18 (CelebA, 15 attrs, skip connections)
│ ├── resnet34/ # ResNet34 (CelebA, 40 attrs, [3,4,6,3] blocks)
│ ├── resnet50/ # ResNet50 (Bottleneck block 1×1→3×3→1×1)
│ ├── mobilenet/ # MobileNet (depthwise separable conv, CIFAR-10)
│ ├── vit/ # Vision Transformer (patch embed + BERT encoder, CIFAR-10)
│ ├── unet/ # UNet (Oxford-IIIT Pet segmentation)
│ └── yolo/ # YOLO (Pascal VOC object detection)
├── gen/ # Generative Models
│ ├── dcgan/ # DCGAN (CelebA, transposed conv)
│ ├── vae/ # VAE (reparameterization trick, KL divergence)
│ ├── ddpm/ # DDPM (CIFAR-10, denoising diffusion)
│ └── simclr/ # SimCLR (CIFAR-10, contrastive learning)
├── graph/ # Graph Neural Networks
│ └── gcn/ # GCN (Cora, spectral graph convolution)
├── rl/ # Reinforcement Learning
│ └── dqn/ # DQN (CartPole, experience replay)
├── nlp/ # Natural Language Processing
│ ├── bert/ # BERT (MLM pretrain + classification finetune)
│ ├── gpt/ # GPT (decoder-only, causal attention, KV cache)
│ ├── lstm/ # LSTM (hand-written gates, IMDB sentiment)
│ ├── word2vec/ # Word2Vec (CBOW + Skip-gram, negative sampling)
│ ├── seq2seq/ # Seq2Seq Transformer (EN→DE translation)
│ └── lora/ # LoRA (parameter-efficient GPT fine-tuning)
├── utils/ # Shared Infrastructure
│ ├── config.py # YAML config loading/saving
│ ├── seed.py # Reproducibility seed locking
│ └── device.py # CUDA → MPS → CPU auto-detection
└── scripts/ # Notebook generation scripts
│ ├── __init__.py
│ ├── config.yaml # DCGAN hyperparameters
│ ├── model.py # Generator + Discriminator
│ ├── data.py # CelebA images (64×64, no labels)
│ ├── train.py # Adversarial training loop (G/D alternating)
│ └── generate.py # Generate sample grid from trained model
├── vit/
│ ├── __init__.py
│ ├── config.yaml # ViT hyperparameters (patch_size, d_model, n_layers, etc.)
│ ├── model.py # ViT: PatchEmbed → Transformer encoder (reused from BERT) → CLS head
│ ├── data.py # CIFAR-10 via HF datasets
│ ├── train.py # Training loop
│ └── eval.py # Per-class accuracy on test split
├── unet/
│ ├── __init__.py
│ ├── config.yaml # UNet hyperparameters
│ ├── model.py # U-Net: encoder–decoder with skip connections
│ ├── data.py # Oxford-IIIT Pet (image + mask) with augmentation
│ ├── train.py # Training loop (pixel-wise CrossEntropy)
│ └── eval.py # IoU and pixel accuracy
├── cnn/
│ ├── __init__.py
│ ├── data.py # CIFAR-10 via HF datasets (uoft-cs/cifar10)
│ ├── model.py # Plain CNN (Conv×3 + Pool×3 + FC×2)
│ ├── train.py # Training script (Adam + CosineAnnealingLR)
│ └── eval.py # Test evaluation + confusion matrix
├── mlp/
│ ├── __init__.py
│ ├── data.py # MNIST via HF datasets (ylecun/mnist)
│ ├── model.py # MLP — pure NumPy (Linear, ReLU, SoftmaxCrossEntropy, SGD)
│ ├── train.py # Training script
│ └── eval.py # Test evaluation (per-digit accuracy)
├── utils/
│ ├── __init__.py
│ ├── config.py # YAML config loading/saving (load_config / save_config)
│ └── seed.py # set_seed() — lock torch + numpy + random + cudnn
├── nlp/
│ ├── bert/
│ ├── word2vec/
│ ├── lstm/
│ ├── gpt/
│ └── seq2seq/
│ ├── __init__.py
│ ├── tokenizer.py # Word-level tokenizer (5000 vocab, from text8)
│ ├── model.py # Decoder-only Transformer (Causal Attention + KV Cache)
│ ├── train.py # Autoregressive LM on text8
│ └── generate.py # Text generation (temperature + top-k + [SEP] blocked)
│ └── seq2seq/
│ ├── __init__.py
│ ├── config.yaml # Transformer hyperparameters
│ ├── model.py # Encoder (from BERT) + Decoder (cross-attention) → Seq2Seq
│ ├── data.py # Multi30k EN→DE, word-level tokenizer
│ ├── train.py # Teacher forcing training
│ └── generate.py # Greedy decoding translation demo
├── basics/
│ ├── __init__.py
│ ├── logistic_regression.py # Single Linear layer + Softmax (92.3% on MNIST)
│ ├── linear_regression.py # California Housing (Normal Equation + GD, R²=0.583)
│ ├── k_means.py # Unsupervised clustering (pure NumPy)
│ ├── svm.py # SVM — GD (primal) + SMO (dual, Linear/RBF kernels)
│ ├── decision_tree.py # ID3/CART on Iris (ASCII tree, ~93% acc)
│ ├── random_forest.py # Bagging + random feature subsets, Iris 93.3%
│ ├── gbdt.py # Gradient boosting (MSE reg + binary logloss cls)
│ ├── naive_bayes.py # Gaussian NB on MNIST (generative classifier)
│ ├── pca.py # SVD-based dimensionality reduction (MNIST 2D visualisation)
│ ├── knn.py # k-Nearest Neighbors (instance-based, MNIST)
│ └── perceptron.py # Single neuron (Rosenblatt 1958, step activation)
├── .gitattributes # LFS: *.zip *.pt
└── uv.lockInfrastructure
Usage
# View training curves (all models)
tensorboard --logdir runs
# Edit hyperparameters in YAML instead of code
vim cv/resnet18/config.yaml
# then train as usual:
uv run python -m cv.resnet18.trainCV/ResNet18
CV/ResNet34
CV/ResNet50
GEN/VAE
NLP/Seq2Seq Transformer
GEN/DDPM
GRAPH/GCN
RL/DQN
GEN/SimCLR
CV/YOLO
NLP/LoRA
CV/MobileNet
DCGAN
CV/ViT
CV/UNet
CV/SimpleCNN
ML/MLP
BERT
Word2Vec
LSTM
GPT
Basics
SVM implementations
See resnet18/README.md for details.
Core Concepts
Every model in this project was written from scratch to teach a specific set of ML/DL concepts. The table below maps each model to the key ideas it demonstrates.
Setup & Run
uv sync# Train / Evaluate ResNet18
uv run python -m cv.resnet18.train
uv run python -m cv.resnet18.eval
# Train / Evaluate ResNet34
uv run python -m cv.resnet34.train
uv run python -m cv.resnet34.eval
# Train / Evaluate ResNet50
uv run python -m cv.resnet50.train
uv run python -m cv.resnet50.eval
# Train / Generate VAE
uv run python -m gen.vae.train
uv run python -m gen.vae.generate
# Train / Translate Seq2Seq
uv run python -m nlp.seq2seq.train
uv run python -m nlp.seq2seq.generate
# Train / Evaluate GCN
uv run python -m graph.gcn.train
uv run python -m graph.gcn.eval
# Train DQN
uv run python -m rl.dqn.train
# Train SimCLR
uv run python -m gen.simclr.train
# Train / Demo YOLO
uv run python -m cv.yolo.train
uv run python -m cv.yolo.demo --image my_image.jpg --conf 0.3 --iou 0.5
# Train / Generate LoRA (requires nlp/gpt/gpt_text8.pt)
uv run python -m nlp.lora.train
uv run python -m nlp.lora.generate
# Train / Evaluate MobileNet
uv run python -m cv.mobilenet.train
uv run python -m cv.mobilenet.eval
uv run python -m cv.yolo.train
# Train / Generate DDPM
uv run python -m gen.ddpm.train
uv run python -m gen.ddpm.generate
# Train / Generate DCGAN
uv run python -m gen.dcgan.train
uv run python -m gen.dcgan.generate
# Train / Evaluate / Demo ViT
uv run python -m cv.vit.train
uv run python -m cv.vit.eval
uv run python -m cv.vit.demo --image my_image.jpg
# Train / Evaluate / Demo UNet
uv run python -m cv.unet.train
uv run python -m cv.unet.eval
uv run python -m cv.unet.demo --image my_image.jpg
# Train / Evaluate CNN
uv run python -m cv.simplecnn.train
uv run python -m cv.simplecnn.eval
# Train / Evaluate MLP (pure NumPy)
uv run python -m mlp.train
uv run python -m mlp.eval
# Basics
uv run python -m basics.logistic_regression
uv run python -m basics.k_means
uv run python -m basics.linear_regression
uv run python -m basics.svm
uv run python -m basics.decision_tree
uv run python -m basics.random_forest
uv run python -m basics.gbdt
uv run python -m basics.naive_bayes
uv run python -m basics.pca
uv run python -m basics.knn
uv run python -m basics.perceptron
# NLP
uv run python -m nlp.bert.pretrain
uv run python -m nlp.bert.finetune
uv run python -m nlp.bert.eval
# Word2Vec
uv run python -m nlp.word2vec.train
uv run python -m nlp.word2vec.eval
# LSTM
uv run python -m nlp.lstm.train
uv run python -m nlp.lstm.eval
# GPT
uv run python -m nlp.gpt.train
uv run python -m nlp.gpt.generateModels
Trained weights are not tracked in git (.gitignore'ed). Each model saves its weights locally after training; paths are shown below for reference.
