Contents

Prog Langs

Raw PyTorch Classifier

View as:

Code Lab 01 - Raw PyTorch Classifier

A small CNN image classifier trained end-to-end in raw PyTorch - no Trainer class, no wrapper library. This lab exists to make every mechanic from the Notes files (Dataset/DataLoader, the hand-written training loop, checkpointing, mixed precision) concrete in one runnable script.

โ† Back to Overview: PyTorch Fundamentals ยท Back to Concepts: Training Loop From Scratch ยท Checkpointing & Mixed Precision


What's In This Lab

PropertyDetail
TaskImage classification (MNIST digits, via torchvision.datasets)
ModelA small hand-written CNN (SimpleCNN in model.py)
TrainingHand-written loop - custom Dataset usage via torchvision, DataLoader, forward/backward/step
CheckpointingSaves model + optimizer state every N epochs to checkpoints/
Mixed Precisiontorch.cuda.amp.autocast() + GradScaler (auto-disabled gracefully on CPU-only machines)
OutputFinal train/val accuracy printed at the end of the run
ComplexityBeginner-Intermediate
Files01-Raw-PyTorch-Classifier/{train.py, model.py, requirements.txt, README.mdx}

Architecture

flowchart LR
    D["๐Ÿ“ฆ torchvision.datasets.MNIST"] --> DL["๐Ÿ”„ DataLoader\nbatch_size=64, shuffle=True"]
    DL --> M["๐Ÿง  SimpleCNN\nconv โ†’ pool โ†’ conv โ†’ pool โ†’ fc"]
    M --> L["๐Ÿ“‰ CrossEntropyLoss"]
    L --> BW["โฌ…๏ธ backward() + GradScaler"]
    BW --> OPT["๐Ÿ”ง optimizer.step()"]
    OPT -->|every N epochs| CKPT["๐Ÿ’พ checkpoints/model_epochN.pt"]
    OPT --> Next["๐Ÿ” next epoch"]
    Next -->|after final epoch| Eval["๐Ÿ“Š Final train/val accuracy"]

    style D fill:#d8dfe8,stroke:#b0bac8
    style DL fill:#e8e0d4,stroke:#c8b89a
    style M fill:#dde4dc,stroke:#b0c4b0
    style L fill:#dde4dc,stroke:#b0c4b0
    style BW fill:#ddd8e4,stroke:#b8b0c8
    style OPT fill:#ddd8e4,stroke:#b8b0c8
    style CKPT fill:#d8dfe8,stroke:#b0bac8
    style Eval fill:#e8e0d4,stroke:#c8b89a

Running

cd 11-Prog-Langs/PyTorch/CodeLabs/01-Raw-PyTorch-Classifier
pip install -r requirements.txt
python train.py

Full details, code walkthrough, and what each part demonstrates: see README.

โšกAI-assisted content - always verify, always explore multiple perspectivesยท