Leanpub Header

Skip to main content

Building Large Language Models from Scratch

A Practical Guide to Training Your Own Transformer-Based AI in Python

This book is 100% completeLast updated on 2026-07-13

Learn how large language models work instead of relying on black-box APIs. Building Large Language Models from Scratch takes you through training a Transformer model in PyTorch, from raw text to a working inference API, covering tokenization, attention, distributed training, and alignment along the way.

Minimum price

$19.00

$29.00

You pay

Author earns

$

Also available for 1 book credit with a Reader Membership

PDF
EPUB
136
Pages
About

About

About the Book

Large language models power some of the most powerful software tools ever built, yet their inner workings remain mysterious to most developers. This book changes that. Starting from raw text and ending with a live inference API, you will build a complete LLM training pipeline from scratch using PyTorch. Every concept is explained clearly, every code listing is production-quality, and every chapter ends with hands-on exercises that cement your understanding. By the time you finish, you will understand tokenization, attention, positional encoding, transformer architecture, data curation, distributed training, fine-tuning, alignment, evaluation, and deployment at a level that no API wrapper can provide.

Bundle

Bundles that include this book

Author

About the Author

Steve Publications

Steve is a technology professional with more than 20 years of experience in software development, server infrastructure, cybersecurity, vulnerability research and reverse engineering. Throughout his career, he has designed, secured, analyzed and tested complex software and infrastructure, with a particular focus on understanding how systems fail and how they can be made more secure.

Outside of work, Steve enjoys sharing knowledge with the technology community. He collaborates with researchers, industry experts and technology professionals to write practical books covering software development, cybersecurity, cloud computing, networking, DevOps, artificial intelligence and enterprise technologies. His books focus on practical learning through clear explanations, real-world examples and hands-on exercises. With more than two decades of industry experience, his goal is to help IT professionals, students and technology enthusiasts build useful skills and stay current in a rapidly changing industry.

We believe readers deserve to know how our books are created. Most of our authors are not native English speakers, so we use AI to help translate, proofread manuscripts, fix grammar, improve sentence structure and make technical explanations easier to read. AI is used as an editing tool only. It does not replace the research, technical knowledge or hands-on experience behind our books. Some of our authors also prefer to remain anonymous for privacy or professional reasons. In those cases, we publish their work under a different name. The author's name may be different, but the quality of the content and our review process remain the same.

Every book is written, reviewed and maintained by experienced technology professionals, with contributions from our private technical community of more than 400 engineers and researchers from Ukraine, Belarus and Russia. We spend far more time validating technical accuracy and keeping our content up to date than generating text. We are always interested in working with experienced professionals who have deep expertise in a particular technology or domain. If you would like to publish a book with us or help review an existing manuscript, we'd love to hear from you. Send us a message describing your area of expertise. We are especially interested in niche technologies, specialized skills and emerging topics that are underrepresented in existing technical literature.

If you look through the contents of our books, you'll see practical examples, detailed explanations and material that is regularly updated. Our goal is to publish books that professionals can actually rely on, not low-effort AI-generated content. If you ever feel that one of our books does not meet that standard, Leanpub offers a 60-day money-back guarantee. Feel free to request a refund if you are not satisfied with your purchase.

Contents

Table of Contents

A Practical Guide to Training Your Own Transformer-Based AI in Python

Introduction: Why Build from Scratch?

  1. The Black Box Problem
  2. What You Will Build
  3. Prerequisites and How to Use This Book
  4. A Note on Hardware Requirements

Chapter 1: Tokens, Vocabularies, and Tokenization

  1. From Text to Numbers: The Tokenization Pipeline
  2. Character-Level vs Word-Level vs Subword Tokenization
  3. Building a Byte-Pair Encoding (BPE) Tokenizer
  4. Vocabulary Size, Special Tokens, and Edge Cases
  5. Exercise: Tokenize the Shakespeare Corpus

Chapter 2: Embeddings: Turning Tokens into Vectors

  1. The Embedding Layer as a Lookup Table
  2. Learning vs Pre-trained Embeddings
  3. Vector Space Geometry and Similarity
  4. Implementing Embedding Layers in PyTorch
  5. Exercise: Visualize an Embedding Space

Chapter 3: The Attention Mechanism

  1. What Is Attention and Why It Matters
  2. Scaled Dot-Product Attention from First Principles
  3. Multi-Head Attention: Parallelizing Understanding
  4. Causal Masking for Decoder-Only Models
  5. Exercise: Trace Attention Through a Sentence

Chapter 4: Positional Encoding and Sequence Structure

  1. The Permutation Invariance Problem
  2. Sinusoidal Absolute Positional Encodings
  3. Learned Position Embeddings
  4. Rotary Positional Embeddings (RoPE)
  5. Exercise: Implement Three Position Encoding Schemes

Chapter 5: Building the Decoder-Only Transformer Architecture

  1. The Decoder-Only Design Decision
  2. Feed-Forward Networks and MLP Blocks
  3. Residual Connections and Layer Normalization
  4. Assembling the Full Transformer Block
  5. The Complete Decoder-Only Model
  6. Exercise: Build a 3-Layer Decoder from Scratch

Chapter 6: Data Preparation for Language Model Training

  1. The Data Landscape: Where Does Training Data Come From?
  2. Cleaning and Filtering Pipeline Design
  3. Deduplication Strategies
  4. Dataset Mixing and Domain Balancing
  5. Synthetic Data Generation Strategies
  6. Exercise: Build a Mini C4 Dataset

Chapter 7: The Training Loop: Loss, Optimizers, and Gradient Flow

  1. Cross-Entropy Loss and Next-Token Prediction
  2. The AdamW Optimizer and Why It Works
  3. Learning Rate Schedules: Warmup, Cosine Decay, and Beyond
  4. Gradient Clipping and Training Stability
  5. The Complete Training Loop
  6. Exercise: Train on a Tiny Dataset and Monitor Loss Curves

Chapter 8: Memory-Efficient Training Patterns

  1. The Memory Wall: Why Models Don’t Fit in GPU RAM
  2. Mixed-Precision Training with BF16/FP16
  3. Gradient Accumulation for Effective Batch Sizes
  4. Activation Checkpointing and Recomputation
  5. Exercise: Train a 10x Larger Model on the Same Hardware

Chapter 9: Distributed Training and Parallelism Strategies

  1. Data Parallelism and Distributed Data Parallel (DDP)
  2. Tensor Parallelism for Massive Models
  3. Pipeline Parallelism: Splitting the Forward Pass
  4. Fully Sharded Data Parallel (FSDP)
  5. Exercise: Multi-GPU Training Setup

Chapter 10: Checkpointing, Experiment Tracking, and Reproducibility

  1. Checkpointing Strategies and Recovery
  2. Experiment Tracking: Metrics, Configs, and Artifacts
  3. Reproducibility: Seeds, Determinism, and Hardware Variability
  4. Logging Design for Long Training Runs
  5. Exercise: Set Up a Production-Style Training Dashboard

Chapter 11: Fine-Tuning: LoRA, QLoRA, and Instruction Tuning

  1. The Fine-Tuning Landscape: Full vs Parameter-Efficient
  2. Low-Rank Adaptation (LoRA) from First Principles
  3. Quantized LoRA (QLoRA) for Memory-Constrained Fine-Tuning
  4. Instruction Tuning Dataset Design
  5. Exercise: Fine-Tune a Model on a Custom Task

Chapter 12: Alignment: RLHF and Beyond

  1. Why Raw Models Need Alignment
  2. The RLHF Pipeline: Reward Models and PPO
  3. Direct Preference Optimization (DPO) as a Simpler Alternative
  4. Constitutional AI and Rule-Based Alignment
  5. Exercise: Build a Simple Preference Dataset

Chapter 13: Evaluation: Metrics, Benchmarks, and Red Teaming

  1. Perplexity as a Training Metric vs Real-World Performance
  2. Standard Benchmark Suites (MMLU, GSM8K, HumanEval)
  3. Qualitative Evaluation and LLM-as-Judge
  4. Safety Testing and Red Teaming Methodologies
  5. Exercise: Build an Evaluation Harness

Chapter 14: Deployment: Inference, Quantization, and Serving

  1. Inference Optimization: KV Cache and Speculative Decoding
  2. Quantization Strategies: FP16 -> INT8 -> INT4
  3. Building a Serving API with FastAPI
  4. Containerization and Production Deployment Patterns
  5. Exercise: Deploy Your Model Behind a Live API

Capstone Project: From Raw Data to Live Inference

  1. Project Setup and Architecture Overview
  2. Data Preparation: Curating a 100M-Token Dataset
  3. Training Run: Configuration, Execution, and Monitoring
  4. Evaluation: Benchmarking Against Baselines
  5. Deployment: Containerized API with Health Checks
  6. Post-Mortem: What Went Well and What Would Be Different

Conclusion: The Road Ahead

  1. What You Have Accomplished
  2. Where to Go From Here: Scaling Up
  3. The Future of Language Models
  4. A Final Word on Building vs Using

References

Get the free sample chapters

Click the buttons to get the free sample in PDF or EPUB, or read the sample online here

The Leanpub 60 Day 100% Happiness Guarantee

Within 60 days of purchase you can get a 100% refund on any Leanpub purchase, in two clicks.

See full terms...

Earn $8 on a $10 Purchase, and $16 on a $20 Purchase

We pay 80% royalties on purchases of $7.99 or more, and 80% royalties minus a 50 cent flat fee on purchases between $0.99 and $7.98. You earn $8 on a $10 sale, and $16 on a $20 sale. So, if we sell 5000 non-refunded copies of your book for $20, you'll earn $80,000.

(Yes, some authors have already earned much more than that on Leanpub.)

In fact, authors have earned over $15 million writing, publishing and selling on Leanpub.

Learn more about writing on Leanpub

Free Updates. DRM Free.

If you buy a Leanpub book, you get free updates for as long as the author updates the book! Many authors use Leanpub to publish their books in-progress, while they are writing them. All readers get free updates, regardless of when they bought the book or how much they paid (including free).

Most Leanpub books are available in PDF (for computers) and EPUB (for phones, tablets and Kindle). The formats that a book includes are shown at the top right corner of this page.

Finally, Leanpub books don't have any DRM copy-protection nonsense, so you can easily read them on any supported device.

Learn more about Leanpub's ebook formats and where to read them

Write and Publish on Leanpub

You can use Leanpub to easily write, publish and sell in-progress and completed ebooks and online courses!

Leanpub is a powerful platform for serious authors, combining a simple, elegant writing and publishing workflow with a store focused on selling in-progress ebooks.

Leanpub is a magical typewriter for authors: just write in plain text, and to publish your ebook, just click a button. (Or, if you are producing your ebook your own way, you can even upload your own PDF and/or EPUB files and then publish with one click!) It really is that easy.

Learn more about writing on Leanpub