This repo will contain simple tutorials for getting familiar with Pytorch quickly for beginners.
Jupyter Notebook
27
962 commits
updated Oct 1, 2026
This repo will contain simple tutorials for getting familiar with Pytorch quickly for beginners. This actually acts as a personal note for myself as well, as I review my old recollection of different algorithms and concepts in Pytorch. I tried to explain everything so in case later on I forget something, I can quickly recall it or see the refs I find useful. I'll tidy things up when I get the time, the following section will be updated as I finish different parts. Some sections are already done (e.g. syle transfer, RNNs, GANs, but they need full explanations, so when that is done, I'll push the changes to this repo. Hope this comes handy to some of you dear fellow software engineers/deeplearning researchers. Have a wonderful day/night :)
Subjcts :
1_Pytorch_basic_introduction.py)
torch.Tensor, torch.tensor, zeros/ones/rand/randn/empty/eye)torch.from_numpy, torch.tensor, .numpy())numpy.ctypes.data vs. Tensor.data_ptr())shape, dtype, device, requires_grad, numel/nelement, ndim/dim, layout, is_contiguous, grad_fn, grad, element_sizeretain_grad(), and when .grad is None.to(), .cuda(), .cpu(), direct-on-device creationdevice_count, get_device_name, get_device_capability, get_device_propertieswith torch.device(...), torch.set_default_device / get_default_device)view vs. reshape vs. resize, squeeze, unsqueeze, permute, contiguity and stridesview(torch.uint8), torch.frombuffer, np.frombuffer) instead of converting it.to(dtype), .float(), .long(), new_ones/new_zeros/new_tensor factoriessum/mean/max/min), .item() vs. raw tensor reprtorch.utils.backcompat.broadcast_warning)@ vs. *, torch.mm, torch.matmul, torch.bmm, 2-D-only vs. broadcasting batch matmul, shape→output summary tablecat, stack, split, chunk, unbind, repeat, expand, repeat_interleave, expand_copymanual_seed, seed, initial_seed, get_rng_state, isolated torch.Generator streamsto_bytes, np.frombuffer, set_printoptions(profile='full'))use_deterministic_algorithms, cudnn.benchmark, cudnn.deterministic, CUBLAS_WORKSPACE_CONFIG, fill_uninitialized_memorytemperature(), utilization(), mem_get_info, memory_reserved, memory_stats, memory_summary, list_gpu_processesempty_cache(), nvidia-smi vs. the caching allocator)torch.mm + manual sigmoid vs. the built-in .sigmoid())print_header, show_tensor, and a hand-written @contextmanager def printoptions(...) emulating np.printoptions2_Pytorch_basic_introduction_NeuralNetworks.py)
ImageFolder (documented), plus custom Dataset usagetransforms.Compose, ToTensor, Normalize, and hand-written transform functors (class ToTensor, class Resize with PIL.Image.BILINEAR)DataLoader, batching, num_workers, and the num_workers=0 debugging adviceSubsetRandomSampler (and why sampler + shuffle=True conflict)nn.Sequential, OrderedDict, python list of layers (and why it hides parameters), nn.ModuleList/nn.ModuleDict, add_moduleSequentialNet7) as the basis of fine-tuningConv+BatchNorm+ReLU block factory (convlayer) and 9 sequential-model variantsFlatten layer (pre-nn.Flatten), and building a MyNet from scratchResBlock and a small Resnetmodules(), children(), named_children(), named_parameters(recurse=), named_buffers(), and a recursive tree printer.data calls, torch.nn.init.*, calculate_gain, kaiming_normal_, model.apply(...)training() / validation() / training_loop() / train_validation_loop()torch.no_grad() for evaluation, .item() to avoid graph accumulation, copy.deepcopy of a modeltorch.max + torch.eq, preds.topk(1) (including the [32,1] vs [32] broadcasting footgun), and batch-mean accuracyCrossEntropyLoss, log_softmax numerics, NLLLoss pairing, sigmoid vs. softmaxisinstance → named_parameters → parameters() progression)MultiStepLR, plus the PyTorch ≥1.1 scheduler.step() ordering changestate_dict only, and a full checkpoint dict (state_dict, optimizer, epoch, accuracies, losses)*_Weights.DEFAULT, weights.transforms(), get_model, get_model_weights, get_weight, list_modelsmodels.quantization.*) and static quantization vs. QATtorch.hub loading, including a hub SimpleNet (coderx7/simplenet_pytorch) and 7 commented variantsrun_inference(), softmax → top-5 percentages, meta["categories"] class names, manual ImageNet preprocessingtorchvision.utils.make_grid, image grids, per-pixel brightness heat-mapstorch.compile() (documented only)MultiTaskLearning.py)
AnimeMTLDataset: reading labels from a CSV, capturing the header row, slicing CSV columns into per-task label groups, a Label_names() human-readable reverse mapargmax-based single-label encoding, multi-hot list comprehensionsBatchNorm1d bottleneck + 5 separate output headsxavier_normal_ init and a 5-tuple forward() returning raw logits (no sigmoid on the multilabel head)BCEWithLogitsLoss for the multi-label head, CrossEntropyLoss for the single-label headstorch.set_grad_enabled(is_training) for train/val sharingoptimizer.add_param_group(...) learning rates (an alternative to freeze/unfreeze)MultiStepLR, 3-way train/val/test SubsetRandomSampler splits, best-checkpoint autosaving on a composite scoreparse_predictions / show_predictions for human-readable multi-task outputconv1d vs conv2d input-dimension sidenote (3-D vs 4-D inputs) and the expected shape errorautoencoders.py)
LinearAutoEncoder (AE)MLPAutoEncoder (MLPAE)ConvAutoEncoder and ConvolutionalAutoEncoder_v2 (ConvAE, widening encoder)add_noise, clamp, MSE against the clean imageL1Penalty autograd Function, L1 on activations, KL-divergence sparsity), layer-wise sparsity metrics, weight-distribution plotsSharedWeightsAE, SharedWeightsAEFunctional)min_kl)mu/std tracking, latent-diversity check, interpolation between latents)Quantizer codebook, nearest-neighbour lookup, straight-through estimator, codebook + commitment loss, EMA codebook update with Laplace smoothing, codebook-collapse/perplexity discussionSequentialLR (linear warmup → cosine), AMP fp16 + GradScaler (with fp16 NaN debugging), best-loss checkpointingget_discrete_latent_codes, latent-map visualization, prior-vs-real comparison, masked-conv receptive-field plotsgans.py)
Discriminator / Generator, label smoothing, separate D/G learning rates, fixed z monitoring, and a long mode-collapse / latent-entanglement debugging lognoise_addition)ConvBlock / ConvTransBlock with residual upsample branches, weights_init_dcgan, no BatchNorm in the first D layer or the last G layer, strided convs instead of pooling (avoiding sparse gradients)CelebAClassifier (ResNet-18 with a 40-logit head)create_graph/retain_graph, (‖∇D‖₂−1)²)spectral_norm with a no_spec_norm_list escape hatch, Dropout2d in D, Upsample+Conv instead of ConvTransposeEqualizedConv2d (runtime weight scaling), PixelNorm, AddBatchStdDev, per-resolution blocks, α fade-in, LR halving, EMA generator with kimg-based warmup, full resume-from-checkpointBlur, EqualizedLinear/EqualizedConv2d (lr multipliers), MappingNetwork, AdaIN, learned NoiseInjection, StyleConvBlock (with an AdaIN-order ablation), learned const_input, 2 blocks per resolutionautocast(enabled=False), style-mixing regularization, truncation (psi) with EMA wupfirdn2d (plus a make_kernel/FIR version), residual discriminator blocks, ModulatedConv2d with weight demodulation, image/skip accumulation across resolutions, AdaAugment (differentiable flip/rotate/scale/translate/cutout/brightness/contrast) and update_ada_pmean_path_length, image-count-based EMA decay, r1_penalty_intervalFourierInput variants, the LeakyReLU sandwich block, no noise injection (logged as an unsuccessful experiment)PatchGAN discriminator, InstanceNorm2d, 6-residual-block CycleGenerator, LSGAN losses, cycle-consistency loss, identity loss, ImageBuffer history mixingIS_FID_Calculator: 2048-d Inception-v3 features, mean/covariance, scipy.linalg.sqrtm, disk caching, 10-split IS)get_status, get_overall_status, loss history, D real/fake score plots, and mode-collapse heuristicslerp and slerp in z and w, truncation sweeps, per-layer style-mixing tables, SVD/SEFA eigen-directions, CLIP text directions, an ipywidgets GUI, and an OpenCV μ/σ findermisc/old_gan_files/)
mnist_gan.py — the original Goodfellow-style MNIST GAN baseline (superseded by gans.py)DCGAN.py — DCGAN on SVHN with the full Salimans "how to train a GAN" tips block (superseded by gans.py)gan_test.py — an MLP GAN and a DCGAN, both on MNIST (superseded by gans.py)CycleGAN.py — the earlier CycleGAN (superseded: gans.py adds the ImageBuffer and the identity loss)face_GANs.py — DCGAN on 64×64 faces plus latent "morphing", and a long essay on mode collapse, Inception Score/FID, StackGAN and IllustrationGANsemi_supervised_training.py — the unique semi-supervised GAN: label masking, a multi-task discriminator with num_classes+1 outputs, GAN logits derived via the log-sum-exp trick, mean feature-matching generator loss, and masked accuracyimage_embedding.py — the unique inverse img2vec encoder trained jointly with the generator so a generated image re-embeds back to its latent, plus latent/embedding-space arithmetic and t-SNEtest.py — a leftover scratch file with no contentrecurrent neural networks.py + rnns_introduction.py)
linspace().sin() corpus with nn.RNN — both filesnn.RNN / nn.LSTM / nn.GRU text generator (rnn_type= argument) — both files1399-0.txt) as the character-level LM corpusrecurrent neural networks.py:
Encoder, BahdanauAttentionDecoder, LSTMBahdanau, a W_v scoring vector, and attention-weight collectioneng-fra.txt), <sos>/<eos>, teacher forcing, greedy topk(1) decoding, and a refactored Dataset + Vocab namedtuplenum_layers=3), BCELoss, accuracy, and per-review inferenceunigram^0.75 noise distribution, custom bmm/sigmoid loss)king−man+woman), nearest neighbours, and PCA / t-SNE embedding plotsunidecode vs ascii vs unicodedata.normalize comparison, and a uint8 vs int32 memory discussionrnns_introduction.py:
detach() / .data pedagogical section on why the hidden state is carried across batches but reset per epochview() vs. reshape() vs. contiguous() debugging walkthrough.size + reshape(-1))clip_grad_norm_) and a punctuation/capitalization-removal essay with academic referencesrnns_introduction.py is the more complete home for sampling methods; recurrent neural networks.py is the only home for attention, seq2seq, sentiment analysis and word embeddingstransformer_tutorial/transformer.py)
encode / decode helpers, compared numerically against tiktoken.get_encoding('gpt2') (65 chars vs. 50,257 BPE tokens)block_size = context_size = 8, and get_batchBigramModel baseline: token-embedding as a count table, F.cross_entropy, and autoregressive generatetril, softmax-by-row-normalization, batched matmul, and proving that a -inf-masked softmax equals a masked averageAttentionHead: separate key/query/value projections, register_buffer for the causal mask, head_size**-0.5 scaling, and dynamic [:T,:T] masking for generationAttentionHeadFused (a single fused kqv projection) with equivalence proofs and a CUDA %timeit benchmark showing no consistent speedupMultiHeadAttention built from a ModuleList (no output projection, noted as a simplification)FeedForward with the paper's 4× inner expansionLayerNormLayerNorm verified against nn.LayerNorm, plus a documented bug post-mortem (missing nn.Parameter and BatchNorm-style last-two-dims aggregation)BigramModelWithAttention redefined six times as the model grows: learned position embeddings → multi-head → FFN → stacked blocks → residuals → LayerNormevaluate_loss (@torch.no_grad(), train/val, model.eval()/train() toggling)AdamW, mixed precision with GradScaler + autocast (scale/step/update), device handling, checkpoint saving, and CUDA memory instrumentationhead_size=8, 4 heads, block/embedding scaling trade-offs, and two large CUDA runs (5.5M and 9.9M params)pcolormesh heatmaps, distance analysis (2-D and 3-D surfaces), pairwise-Euclidean and Gram-matrix heatmaps, and t-SNE / PCA / TruncatedSVD projectionsdata/tiny_shakespear.txt and data/names.txt; the paper is vendored in transformer_tutorial/docs/transformer_tutorial/refresher_neuralnetworks_innerworkings/)
micro_grad.py — a from-scratch autograd engine: the Value class with + - * / ** exp tanh relu, a DFS topological backwardit(), graphviz computation-graph rendering, and a finite-difference gradient_checkmicro_grad.py — a tiny NN library (Neuron, Layer, MLP) plus manual-SGD training on a toy dataset (no optimizer classes)part1.py — character-bigram counting, probability normalization, torch.multinomial sampling, likelihood / log-likelihood / NLL loss, epsilon and count smoothing, and a 1-layer neural bigram trained to the same losspart2.py — Bengio et al. 2003 neural probabilistic LM: learned character embeddings, a 2-layer MLP, softmax numerical-stability demos, and learning-rate sweeps plus decaypart3_BN.py — initialization, saturation analysis, fan-in normalization / Kaiming init, a hand-written BatchNorm1d with running statistics, custom Linear/Tanh/Embedding/Flatten modules, and full activation/gradient/update-ratio diagnostics with and without BatchNormpart4_backprop.py — a full manual backward pass verified against PyTorch autograd with a compare() helper, including 7 different ways of computing the embedding gradientpart5.py — a WaveNet-style hierarchical character LM: a mini Module framework, FlattenConsecutive, progressively doubled receptive fields, a Sequential with a training property, and eval-mode generation from running statisticsplot_logs.py — a leftover ImageNet-style training-log plotter (unrelated to this tutorial's losses)nlp_diffusion_etc_tutorials/diffusion_models.py + notes/nlp.py + Stable Diffusion Deep Dive.ipynb)
diffusion_models.py — using pretrained Stable Diffusion pipelines
StableDiffusionPipeline / DiffusionPipeline / AutoPipelineForText2Image, fp16 variants, and pipeline/scheduler introspectionDDIMScheduler.from_configprompt, negative_prompt, guidance_scale, num_inference_steps, eta, generator, num_images_per_prompt, timestepsload_ip_adapter, set_ip_adapter_scale, multi-reference prompting) with OpenCLIP-ViT-H-14diffusion_models.py — training diffusion models from scratch
Unet, ConvBnAct/DeconvBnAct, create_betas, forward_diffusion, L1 loss, ancestral DDPM sampling) and its 3000-epoch training loopUnetModel + ResBlock + SkipBlock + DiffusionMnist with class and timestep conditioning, add-skip decoding, and per-block embedding controlSinusoidalPositionalEncoding and FourierFeatures timestep embeddingsDiffusionNew — an alternative hour-glass (non-U-Net) architecture experimentv-prediction EDM losseta) samplers, EMA of the weights (ema_update), AMP fp16 + GradScaler, MultiStepLR, and a custom GradualWarmupSchedulerbeta_end, timestep count, batch size, learning rate, dropout, weight decay and overfittingimgs_generated_dirs/imgs_gen_<ts>/args_train.yaml plus per-interval sample gridsnn.Embedding, DDIM sampling, noise-schedule plots) and a commented ResNet-style variantnotes/nlp.py — a reusable log-domain diffusion module
GaussianDiffusion with the full log-space maths (alphas_cum, tilde_betas, q_posterior, p_mean_variance, _predict_x0_from_eps)p_mean_varianceddim_p_mean_variance, ddim_sample) with linear and quadratic timestep discretizations, and trainlosstorch.distributed.get_rank()Stable Diffusion Deep Dive.ipynb — the internals
AutoencoderKL, CLIPTokenizer/CLIPTextModel, UNet2DConditionModel and LMSDiscreteScheduler individuallyStableDiffusionPipeline.__call__, and the img2img "start from a noised input" variantpil_to_latent / latents_to_piladd_noise / scale_model_input, and variance-preserving vs. variance-exploding scheduleslearned_embeds.binlatents_x0 = latents - sigma*noise_pred, and step-by-step progress videos via ffmpegblue_loss) with a loss-scale sweepdiffusion_models.py; only the Textual-Inversion inference swap is actually executed (in the notebook)gans.pynlp_diffusion_etc_tutorials/detection.py)
google/owlvit-base-patch32/16, -large-patch14) and OWLv2 (google/owlv2-*) via transformersmodel.image_guided_detection), and ROI-based detection with cv2.selectROIprocessor.post_process(), post_process_image_guided_detection (score threshold + NMS), and normalized cx,cy,w,h box decodingdenormalize_owlv2 (inverting the CLIP mean/std) and OpenCV box drawingnlp_diffusion_etc_tutorials/image_captioning.py)
Encoder with swappable backbones: resnet50(pretrained=True) or the local SimpleNetDecoder LSTM comparing HIDDEN_STATE conditioning (image features as the initial hidden state) vs. INPUT conditioning (image features as the first token)EncoderDecoderImageCaption built on nn.Transformer / nn.TransformerDecoder with a frozen encoderBertTokenizer-based captioning variantTokenizer with <pad>/<start>/<end>/<unk>, caption-length statistics, and a vocabs.pkl dumpOurColateFN (a functor, not a lambda, for DDP) with pack_padded_sequence / pad_sequence / unpad_sequence and dynamic per-batch paddingdatasets.load_dataset variants)evaluate), ROUGE-1/2/L/Lsum, brevity penalty, length ratio, average generation length, and a compute_metrics hook for the HF Trainermodel.generate(do_sample=True, top_k=3)StepLR, CrossEntropyLoss(ignore_index=pad_token_id), fp16 GradScaler/autocast, torch.compile()VisionEncoderDecoderModel.from_pretrained('nlpconnect/vit-gpt2-image-captioning') for inferencefrom_encoder_decoder_pretrained('microsoft/swin-base-patch4-window7-224-in22k', 'gpt2') and Seq2SeqTrainer / Seq2SeqTrainingArguments fine-tuning (fp16, predict_with_generate, torch_compile, resume_from_checkpoint)results_imgcaptioning-swin-gpt2/link.txtnlp_diffusion_etc_tutorials/sentiment_analysis.py)
SentimentLSTM (embedding → LSTM → dropout → Linear → sigmoid) with BCELoss, StepLR and clip_grad_norm_data/reviews.txt + data/labels.txt (25,000 reviews, 12,500/12,500 split), word-frequency vocabulary analysis, and pad_inputclassify_text() single-sentence inference helperpipeline('sentiment-analysis') with distilbert-base-uncased-finetuned-sst-2-englishDistilBertForSequenceClassification fine-tuning with a custom ReviewDataset (80/10/10 split), TrainingArguments and TrainerTrainerDistilBertConfig → DistilBertModel) and adding a custom classifier headnlp_diffusion_etc_tutorials/notes/*.ipynb)
HuggingFaceH4/ultrachat_200k dataset, mistralai/Mistral-7B-v0.1, and apply_chat_template for the chat formatBitsAndBytesConfig and attn_implementation='flash_attention_2'trl.SFTTrainer, peft.LoraConfig, sequence packing, gradient checkpointing, and cosine schedulingHuggingFaceH4/ultrafeedback_binarized (from openbmb/UltraFeedback), alignment-handbook/zephyr-7b-sft-lora, and assistant_prefix templatingtrl.DPOTrainer with QLoRA, beta=0.01, paged AdamW 32-bit, and a DPO vs. KTO vs. IPO comparisonPeftModel.from_pretrained, verifying only the adapter parameters are trainableAutoModelForCausalLM.from_pretrained(..., load_in_4bit=True, device_map='auto')nlp_diffusion_etc_tutorials/docs/ (a DPO presentation video link and the HuggingFace DPO slides)nlp_diffusion_etc_tutorials/huggingface_tutorials.py + notes/*.py)
transformers, tokenizers (BPE, fast vs. slow), accelerate, data collators, and prompt engineeringexp(loss)), cross-entropy, and causal-LM evaluationnotes/efficient_models_quantization_pruning_etc.py — a reference-only list: dynamic 4-bit quantization, FP4 LLM training, SYCL/Intel-GPU sync, torch.ao pruning + quantization, and distributed trainingnotes/feature_extraction.py, notes/text_summarization.py, notes/GANs.py — reference-only stubs (links and pip installs)notes/utils.py — AverageMeter, RecorderMeter (with plot_curve), and time-formatting helpersmisc/Face verification Siamese Networks/siamese.py)
Dataset that samples anchor/positive/negative on top of ImageFoldersiamese_net backbone (5 strided conv layers, Dropout2d, a custom global_max_pooling instead of Flatten so it is input-size agnostic)nn.PairwiseDistance and a clamped margin (α = 0.2)Dataset) and a discussion of online (in-batch) mining.pgm 92×112 grayscale images, 37 training identities and 3 held-out identities (s5, s6, s7)misc/word2vec_negsampling_old.py + the word-embedding chapter of recurrent neural networks.py)
NLLLoss — both filesmultinomial noise sampler, and a custom bmm+sigmoid loss — both filesCounter-based vocabulary building, and frequency-sorted word2int / int2wordking−man+woman analogy test (RNN version only)state_dict; an embedding-dim / epoch sweep (600, 300, 50, 10)text8 corpus, plus analogy testing and a cleaner loss)f(w)^(3/4) noise distribution are not implemented (the old file's noise distribution is uniform, and CBOW appears only in a comment)text8 corpus itself is not committed (data/ is git-ignored) and must be downloaded to run either filenlp_diffusion_etc_tutorials/simplenet.py + notes/testsimplenet.py)
simplenet_cifar_310k/460k/5m/5m_extra_pool and the ImageNet small / 5m / 9m models (m1, m2 and the small dropout variants)k1 convolutions, Xavier-uniform init, MaxPool2d + Dropout2d pairs, and a stride-mode tabledefault_cfgs (input size, crop percentage, interpolation, mean/std)image_captioning.py (and loadable from torch.hub inside 2_Pytorch_basic_introduction_NeuralNetworks.py)notes/testsimplenet.py — commented-out checkpoint loading, remove_dropout_layers, and OpenCV SIFT/DAISY unit testsnlp_diffusion_etc_tutorials/data/{corpus.txt, reviews.txt, labels.txt}, transformer_tutorial/data/{tiny_shakespear.txt, names.txt}, and the 400 .pgm face images under misc/eng-fra.txt, text8, and the summer↔winter Yosemite setnlp_diffusion_etc_tutorials/imgs_generated_dirs/ — 134 timestamped CIFAR diffusion sample runs, each with an args_train.yamlnlp_diffusion_etc_tutorials/vocabs.pkl — the COCO caption vocabulary written by image_captioning.pynlp_diffusion_etc_tutorials/results_imgcaptioning-swin-gpt2/link.txt and the MEGA download links in weights/weights.txt (weights and visualizations, ~31 GB)pixelCNN_blindspot.png, contractive_autoencoder_u1_u2_axis_plot.png, and the positional-encoding plots in transformer_tutorial/imgs/.gitignore excludes data/, results/, weights/, FutureTodos/ and notebook_exports/transformer_tutorial/ instead)notes/ lists them only)This update brings in the tutorials I originally wrote for myself back in 2018/2019,
I didnt plan on publishing them publicly initially, as they were only my
practice files, reminders and definitely not in a shape fit for others hence why
It took a fair amount of work to consolidate and clean them up into something usable.
While organizing them, I also added a few more architectures, so the repo now covers
a reasonable range of topics, all heavily commented and explained.
Each file/section/chapter includes the references I used while writing it. aside
from the original papers and their implementations, many of the exercises
and projects here are simply me implementing concepts I was learning at the time
some inspired by online courses such as Coursera (deeplearning course) or
Udacity (Pytorch introduction) circa 2017~2019.
Please refer to each file for further references.
I used LLMs such as ChatGPT, Gemini, Claude, Microsoft Copilot, Grok, and DeepSeek as
a secondary aid throughout my work post-2023. I mainly used these for debugging, proofreading,
and sanity-checking my explanations, mostly concerning newer architectures that I had not
previously implemented, such as new GAN architectures, and, to a lesser degree, my existing
explanations especially when I had made an incorrect assumption or explanation that needed to be corrected.
Some chapters need more edits/proofing than others, but you should be able to read/experiment
nonetheless. hopefully I'll take care of them when my time allows me and do a cleanup later on.
TOPICS.md contains an auto generated summary of what these tutorials cover
I generated it using claude.
This repo will contain simple tutorials for getting familiar with Pytorch quickly for beginners.
Jupyter Notebook
27
962 commits
updated Oct 1, 2026
This repo will contain simple tutorials for getting familiar with Pytorch quickly for beginners. This actually acts as a personal note for myself as well, as I review my old recollection of different algorithms and concepts in Pytorch. I tried to explain everything so in case later on I forget something, I can quickly recall it or see the refs I find useful. I'll tidy things up when I get the time, the following section will be updated as I finish different parts. Some sections are already done (e.g. syle transfer, RNNs, GANs, but they need full explanations, so when that is done, I'll push the changes to this repo. Hope this comes handy to some of you dear fellow software engineers/deeplearning researchers. Have a wonderful day/night :)
Subjcts :
1_Pytorch_basic_introduction.py)
torch.Tensor, torch.tensor, zeros/ones/rand/randn/empty/eye)torch.from_numpy, torch.tensor, .numpy())numpy.ctypes.data vs. Tensor.data_ptr())shape, dtype, device, requires_grad, numel/nelement, ndim/dim, layout, is_contiguous, grad_fn, grad, element_sizeretain_grad(), and when .grad is None.to(), .cuda(), .cpu(), direct-on-device creationdevice_count, get_device_name, get_device_capability, get_device_propertieswith torch.device(...), torch.set_default_device / get_default_device)view vs. reshape vs. resize, squeeze, unsqueeze, permute, contiguity and stridesview(torch.uint8), torch.frombuffer, np.frombuffer) instead of converting it.to(dtype), .float(), .long(), new_ones/new_zeros/new_tensor factoriessum/mean/max/min), .item() vs. raw tensor reprtorch.utils.backcompat.broadcast_warning)@ vs. *, torch.mm, torch.matmul, torch.bmm, 2-D-only vs. broadcasting batch matmul, shape→output summary tablecat, stack, split, chunk, unbind, repeat, expand, repeat_interleave, expand_copymanual_seed, seed, initial_seed, get_rng_state, isolated torch.Generator streamsto_bytes, np.frombuffer, set_printoptions(profile='full'))use_deterministic_algorithms, cudnn.benchmark, cudnn.deterministic, CUBLAS_WORKSPACE_CONFIG, fill_uninitialized_memorytemperature(), utilization(), mem_get_info, memory_reserved, memory_stats, memory_summary, list_gpu_processesempty_cache(), nvidia-smi vs. the caching allocator)torch.mm + manual sigmoid vs. the built-in .sigmoid())print_header, show_tensor, and a hand-written @contextmanager def printoptions(...) emulating np.printoptions2_Pytorch_basic_introduction_NeuralNetworks.py)
ImageFolder (documented), plus custom Dataset usagetransforms.Compose, ToTensor, Normalize, and hand-written transform functors (class ToTensor, class Resize with PIL.Image.BILINEAR)DataLoader, batching, num_workers, and the num_workers=0 debugging adviceSubsetRandomSampler (and why sampler + shuffle=True conflict)nn.Sequential, OrderedDict, python list of layers (and why it hides parameters), nn.ModuleList/nn.ModuleDict, add_moduleSequentialNet7) as the basis of fine-tuningConv+BatchNorm+ReLU block factory (convlayer) and 9 sequential-model variantsFlatten layer (pre-nn.Flatten), and building a MyNet from scratchResBlock and a small Resnetmodules(), children(), named_children(), named_parameters(recurse=), named_buffers(), and a recursive tree printer.data calls, torch.nn.init.*, calculate_gain, kaiming_normal_, model.apply(...)training() / validation() / training_loop() / train_validation_loop()torch.no_grad() for evaluation, .item() to avoid graph accumulation, copy.deepcopy of a modeltorch.max + torch.eq, preds.topk(1) (including the [32,1] vs [32] broadcasting footgun), and batch-mean accuracyCrossEntropyLoss, log_softmax numerics, NLLLoss pairing, sigmoid vs. softmaxisinstance → named_parameters → parameters() progression)MultiStepLR, plus the PyTorch ≥1.1 scheduler.step() ordering changestate_dict only, and a full checkpoint dict (state_dict, optimizer, epoch, accuracies, losses)*_Weights.DEFAULT, weights.transforms(), get_model, get_model_weights, get_weight, list_modelsmodels.quantization.*) and static quantization vs. QATtorch.hub loading, including a hub SimpleNet (coderx7/simplenet_pytorch) and 7 commented variantsrun_inference(), softmax → top-5 percentages, meta["categories"] class names, manual ImageNet preprocessingtorchvision.utils.make_grid, image grids, per-pixel brightness heat-mapstorch.compile() (documented only)MultiTaskLearning.py)
AnimeMTLDataset: reading labels from a CSV, capturing the header row, slicing CSV columns into per-task label groups, a Label_names() human-readable reverse mapargmax-based single-label encoding, multi-hot list comprehensionsBatchNorm1d bottleneck + 5 separate output headsxavier_normal_ init and a 5-tuple forward() returning raw logits (no sigmoid on the multilabel head)BCEWithLogitsLoss for the multi-label head, CrossEntropyLoss for the single-label headstorch.set_grad_enabled(is_training) for train/val sharingoptimizer.add_param_group(...) learning rates (an alternative to freeze/unfreeze)MultiStepLR, 3-way train/val/test SubsetRandomSampler splits, best-checkpoint autosaving on a composite scoreparse_predictions / show_predictions for human-readable multi-task outputconv1d vs conv2d input-dimension sidenote (3-D vs 4-D inputs) and the expected shape errorautoencoders.py)
LinearAutoEncoder (AE)MLPAutoEncoder (MLPAE)ConvAutoEncoder and ConvolutionalAutoEncoder_v2 (ConvAE, widening encoder)add_noise, clamp, MSE against the clean imageL1Penalty autograd Function, L1 on activations, KL-divergence sparsity), layer-wise sparsity metrics, weight-distribution plotsSharedWeightsAE, SharedWeightsAEFunctional)min_kl)mu/std tracking, latent-diversity check, interpolation between latents)Quantizer codebook, nearest-neighbour lookup, straight-through estimator, codebook + commitment loss, EMA codebook update with Laplace smoothing, codebook-collapse/perplexity discussionSequentialLR (linear warmup → cosine), AMP fp16 + GradScaler (with fp16 NaN debugging), best-loss checkpointingget_discrete_latent_codes, latent-map visualization, prior-vs-real comparison, masked-conv receptive-field plotsgans.py)
Discriminator / Generator, label smoothing, separate D/G learning rates, fixed z monitoring, and a long mode-collapse / latent-entanglement debugging lognoise_addition)ConvBlock / ConvTransBlock with residual upsample branches, weights_init_dcgan, no BatchNorm in the first D layer or the last G layer, strided convs instead of pooling (avoiding sparse gradients)CelebAClassifier (ResNet-18 with a 40-logit head)create_graph/retain_graph, (‖∇D‖₂−1)²)spectral_norm with a no_spec_norm_list escape hatch, Dropout2d in D, Upsample+Conv instead of ConvTransposeEqualizedConv2d (runtime weight scaling), PixelNorm, AddBatchStdDev, per-resolution blocks, α fade-in, LR halving, EMA generator with kimg-based warmup, full resume-from-checkpointBlur, EqualizedLinear/EqualizedConv2d (lr multipliers), MappingNetwork, AdaIN, learned NoiseInjection, StyleConvBlock (with an AdaIN-order ablation), learned const_input, 2 blocks per resolutionautocast(enabled=False), style-mixing regularization, truncation (psi) with EMA wupfirdn2d (plus a make_kernel/FIR version), residual discriminator blocks, ModulatedConv2d with weight demodulation, image/skip accumulation across resolutions, AdaAugment (differentiable flip/rotate/scale/translate/cutout/brightness/contrast) and update_ada_pmean_path_length, image-count-based EMA decay, r1_penalty_intervalFourierInput variants, the LeakyReLU sandwich block, no noise injection (logged as an unsuccessful experiment)PatchGAN discriminator, InstanceNorm2d, 6-residual-block CycleGenerator, LSGAN losses, cycle-consistency loss, identity loss, ImageBuffer history mixingIS_FID_Calculator: 2048-d Inception-v3 features, mean/covariance, scipy.linalg.sqrtm, disk caching, 10-split IS)get_status, get_overall_status, loss history, D real/fake score plots, and mode-collapse heuristicslerp and slerp in z and w, truncation sweeps, per-layer style-mixing tables, SVD/SEFA eigen-directions, CLIP text directions, an ipywidgets GUI, and an OpenCV μ/σ findermisc/old_gan_files/)
mnist_gan.py — the original Goodfellow-style MNIST GAN baseline (superseded by gans.py)DCGAN.py — DCGAN on SVHN with the full Salimans "how to train a GAN" tips block (superseded by gans.py)gan_test.py — an MLP GAN and a DCGAN, both on MNIST (superseded by gans.py)CycleGAN.py — the earlier CycleGAN (superseded: gans.py adds the ImageBuffer and the identity loss)face_GANs.py — DCGAN on 64×64 faces plus latent "morphing", and a long essay on mode collapse, Inception Score/FID, StackGAN and IllustrationGANsemi_supervised_training.py — the unique semi-supervised GAN: label masking, a multi-task discriminator with num_classes+1 outputs, GAN logits derived via the log-sum-exp trick, mean feature-matching generator loss, and masked accuracyimage_embedding.py — the unique inverse img2vec encoder trained jointly with the generator so a generated image re-embeds back to its latent, plus latent/embedding-space arithmetic and t-SNEtest.py — a leftover scratch file with no contentrecurrent neural networks.py + rnns_introduction.py)
linspace().sin() corpus with nn.RNN — both filesnn.RNN / nn.LSTM / nn.GRU text generator (rnn_type= argument) — both files1399-0.txt) as the character-level LM corpusrecurrent neural networks.py:
Encoder, BahdanauAttentionDecoder, LSTMBahdanau, a W_v scoring vector, and attention-weight collectioneng-fra.txt), <sos>/<eos>, teacher forcing, greedy topk(1) decoding, and a refactored Dataset + Vocab namedtuplenum_layers=3), BCELoss, accuracy, and per-review inferenceunigram^0.75 noise distribution, custom bmm/sigmoid loss)king−man+woman), nearest neighbours, and PCA / t-SNE embedding plotsunidecode vs ascii vs unicodedata.normalize comparison, and a uint8 vs int32 memory discussionrnns_introduction.py:
detach() / .data pedagogical section on why the hidden state is carried across batches but reset per epochview() vs. reshape() vs. contiguous() debugging walkthrough.size + reshape(-1))clip_grad_norm_) and a punctuation/capitalization-removal essay with academic referencesrnns_introduction.py is the more complete home for sampling methods; recurrent neural networks.py is the only home for attention, seq2seq, sentiment analysis and word embeddingstransformer_tutorial/transformer.py)
encode / decode helpers, compared numerically against tiktoken.get_encoding('gpt2') (65 chars vs. 50,257 BPE tokens)block_size = context_size = 8, and get_batchBigramModel baseline: token-embedding as a count table, F.cross_entropy, and autoregressive generatetril, softmax-by-row-normalization, batched matmul, and proving that a -inf-masked softmax equals a masked averageAttentionHead: separate key/query/value projections, register_buffer for the causal mask, head_size**-0.5 scaling, and dynamic [:T,:T] masking for generationAttentionHeadFused (a single fused kqv projection) with equivalence proofs and a CUDA %timeit benchmark showing no consistent speedupMultiHeadAttention built from a ModuleList (no output projection, noted as a simplification)FeedForward with the paper's 4× inner expansionLayerNormLayerNorm verified against nn.LayerNorm, plus a documented bug post-mortem (missing nn.Parameter and BatchNorm-style last-two-dims aggregation)BigramModelWithAttention redefined six times as the model grows: learned position embeddings → multi-head → FFN → stacked blocks → residuals → LayerNormevaluate_loss (@torch.no_grad(), train/val, model.eval()/train() toggling)AdamW, mixed precision with GradScaler + autocast (scale/step/update), device handling, checkpoint saving, and CUDA memory instrumentationhead_size=8, 4 heads, block/embedding scaling trade-offs, and two large CUDA runs (5.5M and 9.9M params)pcolormesh heatmaps, distance analysis (2-D and 3-D surfaces), pairwise-Euclidean and Gram-matrix heatmaps, and t-SNE / PCA / TruncatedSVD projectionsdata/tiny_shakespear.txt and data/names.txt; the paper is vendored in transformer_tutorial/docs/transformer_tutorial/refresher_neuralnetworks_innerworkings/)
micro_grad.py — a from-scratch autograd engine: the Value class with + - * / ** exp tanh relu, a DFS topological backwardit(), graphviz computation-graph rendering, and a finite-difference gradient_checkmicro_grad.py — a tiny NN library (Neuron, Layer, MLP) plus manual-SGD training on a toy dataset (no optimizer classes)part1.py — character-bigram counting, probability normalization, torch.multinomial sampling, likelihood / log-likelihood / NLL loss, epsilon and count smoothing, and a 1-layer neural bigram trained to the same losspart2.py — Bengio et al. 2003 neural probabilistic LM: learned character embeddings, a 2-layer MLP, softmax numerical-stability demos, and learning-rate sweeps plus decaypart3_BN.py — initialization, saturation analysis, fan-in normalization / Kaiming init, a hand-written BatchNorm1d with running statistics, custom Linear/Tanh/Embedding/Flatten modules, and full activation/gradient/update-ratio diagnostics with and without BatchNormpart4_backprop.py — a full manual backward pass verified against PyTorch autograd with a compare() helper, including 7 different ways of computing the embedding gradientpart5.py — a WaveNet-style hierarchical character LM: a mini Module framework, FlattenConsecutive, progressively doubled receptive fields, a Sequential with a training property, and eval-mode generation from running statisticsplot_logs.py — a leftover ImageNet-style training-log plotter (unrelated to this tutorial's losses)nlp_diffusion_etc_tutorials/diffusion_models.py + notes/nlp.py + Stable Diffusion Deep Dive.ipynb)
diffusion_models.py — using pretrained Stable Diffusion pipelines
StableDiffusionPipeline / DiffusionPipeline / AutoPipelineForText2Image, fp16 variants, and pipeline/scheduler introspectionDDIMScheduler.from_configprompt, negative_prompt, guidance_scale, num_inference_steps, eta, generator, num_images_per_prompt, timestepsload_ip_adapter, set_ip_adapter_scale, multi-reference prompting) with OpenCLIP-ViT-H-14diffusion_models.py — training diffusion models from scratch
Unet, ConvBnAct/DeconvBnAct, create_betas, forward_diffusion, L1 loss, ancestral DDPM sampling) and its 3000-epoch training loopUnetModel + ResBlock + SkipBlock + DiffusionMnist with class and timestep conditioning, add-skip decoding, and per-block embedding controlSinusoidalPositionalEncoding and FourierFeatures timestep embeddingsDiffusionNew — an alternative hour-glass (non-U-Net) architecture experimentv-prediction EDM losseta) samplers, EMA of the weights (ema_update), AMP fp16 + GradScaler, MultiStepLR, and a custom GradualWarmupSchedulerbeta_end, timestep count, batch size, learning rate, dropout, weight decay and overfittingimgs_generated_dirs/imgs_gen_<ts>/args_train.yaml plus per-interval sample gridsnn.Embedding, DDIM sampling, noise-schedule plots) and a commented ResNet-style variantnotes/nlp.py — a reusable log-domain diffusion module
GaussianDiffusion with the full log-space maths (alphas_cum, tilde_betas, q_posterior, p_mean_variance, _predict_x0_from_eps)p_mean_varianceddim_p_mean_variance, ddim_sample) with linear and quadratic timestep discretizations, and trainlosstorch.distributed.get_rank()Stable Diffusion Deep Dive.ipynb — the internals
AutoencoderKL, CLIPTokenizer/CLIPTextModel, UNet2DConditionModel and LMSDiscreteScheduler individuallyStableDiffusionPipeline.__call__, and the img2img "start from a noised input" variantpil_to_latent / latents_to_piladd_noise / scale_model_input, and variance-preserving vs. variance-exploding scheduleslearned_embeds.binlatents_x0 = latents - sigma*noise_pred, and step-by-step progress videos via ffmpegblue_loss) with a loss-scale sweepdiffusion_models.py; only the Textual-Inversion inference swap is actually executed (in the notebook)gans.pynlp_diffusion_etc_tutorials/detection.py)
google/owlvit-base-patch32/16, -large-patch14) and OWLv2 (google/owlv2-*) via transformersmodel.image_guided_detection), and ROI-based detection with cv2.selectROIprocessor.post_process(), post_process_image_guided_detection (score threshold + NMS), and normalized cx,cy,w,h box decodingdenormalize_owlv2 (inverting the CLIP mean/std) and OpenCV box drawingnlp_diffusion_etc_tutorials/image_captioning.py)
Encoder with swappable backbones: resnet50(pretrained=True) or the local SimpleNetDecoder LSTM comparing HIDDEN_STATE conditioning (image features as the initial hidden state) vs. INPUT conditioning (image features as the first token)EncoderDecoderImageCaption built on nn.Transformer / nn.TransformerDecoder with a frozen encoderBertTokenizer-based captioning variantTokenizer with <pad>/<start>/<end>/<unk>, caption-length statistics, and a vocabs.pkl dumpOurColateFN (a functor, not a lambda, for DDP) with pack_padded_sequence / pad_sequence / unpad_sequence and dynamic per-batch paddingdatasets.load_dataset variants)evaluate), ROUGE-1/2/L/Lsum, brevity penalty, length ratio, average generation length, and a compute_metrics hook for the HF Trainermodel.generate(do_sample=True, top_k=3)StepLR, CrossEntropyLoss(ignore_index=pad_token_id), fp16 GradScaler/autocast, torch.compile()VisionEncoderDecoderModel.from_pretrained('nlpconnect/vit-gpt2-image-captioning') for inferencefrom_encoder_decoder_pretrained('microsoft/swin-base-patch4-window7-224-in22k', 'gpt2') and Seq2SeqTrainer / Seq2SeqTrainingArguments fine-tuning (fp16, predict_with_generate, torch_compile, resume_from_checkpoint)results_imgcaptioning-swin-gpt2/link.txtnlp_diffusion_etc_tutorials/sentiment_analysis.py)
SentimentLSTM (embedding → LSTM → dropout → Linear → sigmoid) with BCELoss, StepLR and clip_grad_norm_data/reviews.txt + data/labels.txt (25,000 reviews, 12,500/12,500 split), word-frequency vocabulary analysis, and pad_inputclassify_text() single-sentence inference helperpipeline('sentiment-analysis') with distilbert-base-uncased-finetuned-sst-2-englishDistilBertForSequenceClassification fine-tuning with a custom ReviewDataset (80/10/10 split), TrainingArguments and TrainerTrainerDistilBertConfig → DistilBertModel) and adding a custom classifier headnlp_diffusion_etc_tutorials/notes/*.ipynb)
HuggingFaceH4/ultrachat_200k dataset, mistralai/Mistral-7B-v0.1, and apply_chat_template for the chat formatBitsAndBytesConfig and attn_implementation='flash_attention_2'trl.SFTTrainer, peft.LoraConfig, sequence packing, gradient checkpointing, and cosine schedulingHuggingFaceH4/ultrafeedback_binarized (from openbmb/UltraFeedback), alignment-handbook/zephyr-7b-sft-lora, and assistant_prefix templatingtrl.DPOTrainer with QLoRA, beta=0.01, paged AdamW 32-bit, and a DPO vs. KTO vs. IPO comparisonPeftModel.from_pretrained, verifying only the adapter parameters are trainableAutoModelForCausalLM.from_pretrained(..., load_in_4bit=True, device_map='auto')nlp_diffusion_etc_tutorials/docs/ (a DPO presentation video link and the HuggingFace DPO slides)nlp_diffusion_etc_tutorials/huggingface_tutorials.py + notes/*.py)
transformers, tokenizers (BPE, fast vs. slow), accelerate, data collators, and prompt engineeringexp(loss)), cross-entropy, and causal-LM evaluationnotes/efficient_models_quantization_pruning_etc.py — a reference-only list: dynamic 4-bit quantization, FP4 LLM training, SYCL/Intel-GPU sync, torch.ao pruning + quantization, and distributed trainingnotes/feature_extraction.py, notes/text_summarization.py, notes/GANs.py — reference-only stubs (links and pip installs)notes/utils.py — AverageMeter, RecorderMeter (with plot_curve), and time-formatting helpersmisc/Face verification Siamese Networks/siamese.py)
Dataset that samples anchor/positive/negative on top of ImageFoldersiamese_net backbone (5 strided conv layers, Dropout2d, a custom global_max_pooling instead of Flatten so it is input-size agnostic)nn.PairwiseDistance and a clamped margin (α = 0.2)Dataset) and a discussion of online (in-batch) mining.pgm 92×112 grayscale images, 37 training identities and 3 held-out identities (s5, s6, s7)misc/word2vec_negsampling_old.py + the word-embedding chapter of recurrent neural networks.py)
NLLLoss — both filesmultinomial noise sampler, and a custom bmm+sigmoid loss — both filesCounter-based vocabulary building, and frequency-sorted word2int / int2wordking−man+woman analogy test (RNN version only)state_dict; an embedding-dim / epoch sweep (600, 300, 50, 10)text8 corpus, plus analogy testing and a cleaner loss)f(w)^(3/4) noise distribution are not implemented (the old file's noise distribution is uniform, and CBOW appears only in a comment)text8 corpus itself is not committed (data/ is git-ignored) and must be downloaded to run either filenlp_diffusion_etc_tutorials/simplenet.py + notes/testsimplenet.py)
simplenet_cifar_310k/460k/5m/5m_extra_pool and the ImageNet small / 5m / 9m models (m1, m2 and the small dropout variants)k1 convolutions, Xavier-uniform init, MaxPool2d + Dropout2d pairs, and a stride-mode tabledefault_cfgs (input size, crop percentage, interpolation, mean/std)image_captioning.py (and loadable from torch.hub inside 2_Pytorch_basic_introduction_NeuralNetworks.py)notes/testsimplenet.py — commented-out checkpoint loading, remove_dropout_layers, and OpenCV SIFT/DAISY unit testsnlp_diffusion_etc_tutorials/data/{corpus.txt, reviews.txt, labels.txt}, transformer_tutorial/data/{tiny_shakespear.txt, names.txt}, and the 400 .pgm face images under misc/eng-fra.txt, text8, and the summer↔winter Yosemite setnlp_diffusion_etc_tutorials/imgs_generated_dirs/ — 134 timestamped CIFAR diffusion sample runs, each with an args_train.yamlnlp_diffusion_etc_tutorials/vocabs.pkl — the COCO caption vocabulary written by image_captioning.pynlp_diffusion_etc_tutorials/results_imgcaptioning-swin-gpt2/link.txt and the MEGA download links in weights/weights.txt (weights and visualizations, ~31 GB)pixelCNN_blindspot.png, contractive_autoencoder_u1_u2_axis_plot.png, and the positional-encoding plots in transformer_tutorial/imgs/.gitignore excludes data/, results/, weights/, FutureTodos/ and notebook_exports/transformer_tutorial/ instead)notes/ lists them only)This update brings in the tutorials I originally wrote for myself back in 2018/2019,
I didnt plan on publishing them publicly initially, as they were only my
practice files, reminders and definitely not in a shape fit for others hence why
It took a fair amount of work to consolidate and clean them up into something usable.
While organizing them, I also added a few more architectures, so the repo now covers
a reasonable range of topics, all heavily commented and explained.
Each file/section/chapter includes the references I used while writing it. aside
from the original papers and their implementations, many of the exercises
and projects here are simply me implementing concepts I was learning at the time
some inspired by online courses such as Coursera (deeplearning course) or
Udacity (Pytorch introduction) circa 2017~2019.
Please refer to each file for further references.
I used LLMs such as ChatGPT, Gemini, Claude, Microsoft Copilot, Grok, and DeepSeek as
a secondary aid throughout my work post-2023. I mainly used these for debugging, proofreading,
and sanity-checking my explanations, mostly concerning newer architectures that I had not
previously implemented, such as new GAN architectures, and, to a lesser degree, my existing
explanations especially when I had made an incorrect assumption or explanation that needed to be corrected.
Some chapters need more edits/proofing than others, but you should be able to read/experiment
nonetheless. hopefully I'll take care of them when my time allows me and do a cleanup later on.
TOPICS.md contains an auto generated summary of what these tutorials cover
I generated it using claude.